@exabugs/dynamodb-client 1.26.0 → 1.27.1

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 (146) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/dist/__generated__/models/apiOperation.d.ts +1 -0
  3. package/dist/__generated__/models/apiOperation.d.ts.map +1 -1
  4. package/dist/__generated__/models/apiOperation.js +1 -0
  5. package/dist/__generated__/models/apiOperation.js.map +1 -1
  6. package/dist/__generated__/models/bulkOperationResult.d.ts +2 -0
  7. package/dist/__generated__/models/bulkOperationResult.d.ts.map +1 -1
  8. package/dist/__generated__/models/countParams.d.ts +31 -0
  9. package/dist/__generated__/models/countParams.d.ts.map +1 -0
  10. package/dist/__generated__/models/countParams.js +2 -0
  11. package/dist/__generated__/models/countParams.js.map +1 -0
  12. package/dist/__generated__/models/countResult.d.ts +37 -0
  13. package/dist/__generated__/models/countResult.d.ts.map +1 -0
  14. package/dist/__generated__/models/countResult.js +2 -0
  15. package/dist/__generated__/models/countResult.js.map +1 -0
  16. package/dist/__generated__/models/countResultConsumedCapacity.d.ts +35 -0
  17. package/dist/__generated__/models/countResultConsumedCapacity.d.ts.map +1 -0
  18. package/dist/__generated__/models/countResultConsumedCapacity.js +25 -0
  19. package/dist/__generated__/models/countResultConsumedCapacity.js.map +1 -0
  20. package/dist/__generated__/models/executeOperationBodyOp.d.ts +1 -0
  21. package/dist/__generated__/models/executeOperationBodyOp.d.ts.map +1 -1
  22. package/dist/__generated__/models/executeOperationBodyOp.js +1 -0
  23. package/dist/__generated__/models/executeOperationBodyOp.js.map +1 -1
  24. package/dist/__generated__/models/findResultPageInfo.d.ts +2 -0
  25. package/dist/__generated__/models/findResultPageInfo.d.ts.map +1 -1
  26. package/dist/__generated__/models/index.d.ts +3 -0
  27. package/dist/__generated__/models/index.d.ts.map +1 -1
  28. package/dist/__generated__/models/index.js +3 -0
  29. package/dist/__generated__/models/index.js.map +1 -1
  30. package/dist/client/Collection.d.ts +7 -0
  31. package/dist/client/Collection.d.ts.map +1 -1
  32. package/dist/client/Collection.js +20 -1
  33. package/dist/client/Collection.js.map +1 -1
  34. package/dist/scripts/repair-shadows.js +86 -42
  35. package/dist/scripts/repair-shadows.js.map +1 -1
  36. package/dist/scripts/utils/cliParser.d.ts +9 -22
  37. package/dist/scripts/utils/cliParser.d.ts.map +1 -1
  38. package/dist/scripts/utils/cliParser.js +14 -37
  39. package/dist/scripts/utils/cliParser.js.map +1 -1
  40. package/dist/scripts/utils/shadowAudit.d.ts +49 -0
  41. package/dist/scripts/utils/shadowAudit.d.ts.map +1 -0
  42. package/dist/scripts/utils/shadowAudit.js +84 -0
  43. package/dist/scripts/utils/shadowAudit.js.map +1 -0
  44. package/dist/scripts/utils/shadowRepair.d.ts +42 -0
  45. package/dist/scripts/utils/shadowRepair.d.ts.map +1 -0
  46. package/dist/scripts/utils/shadowRepair.js +110 -0
  47. package/dist/scripts/utils/shadowRepair.js.map +1 -0
  48. package/dist/server/handler.cjs +1237 -1122
  49. package/dist/server/handler.cjs.map +4 -4
  50. package/dist/server/handler.js +2 -2
  51. package/dist/server/handler.js.map +1 -1
  52. package/dist/server/media-handler.cjs +2 -2
  53. package/dist/server/media-process-handler-dlq.cjs +19 -3
  54. package/dist/server/media-process-handler-dlq.cjs.map +2 -2
  55. package/dist/server/media-process-handler.cjs +19 -3
  56. package/dist/server/media-process-handler.cjs.map +2 -2
  57. package/dist/server/operations/count.d.ts +3 -0
  58. package/dist/server/operations/count.d.ts.map +1 -0
  59. package/dist/server/operations/count.js +81 -0
  60. package/dist/server/operations/count.js.map +1 -0
  61. package/dist/server/operations/deleteMany.d.ts.map +1 -1
  62. package/dist/server/operations/deleteMany.js +2 -1
  63. package/dist/server/operations/deleteMany.js.map +1 -1
  64. package/dist/server/operations/deleteOne.d.ts.map +1 -1
  65. package/dist/server/operations/deleteOne.js +3 -12
  66. package/dist/server/operations/deleteOne.js.map +1 -1
  67. package/dist/server/operations/find/handler.d.ts.map +1 -1
  68. package/dist/server/operations/find/handler.js +4 -1
  69. package/dist/server/operations/find/handler.js.map +1 -1
  70. package/dist/server/operations/find/keyCondition.d.ts +38 -0
  71. package/dist/server/operations/find/keyCondition.d.ts.map +1 -0
  72. package/dist/server/operations/find/keyCondition.js +184 -0
  73. package/dist/server/operations/find/keyCondition.js.map +1 -0
  74. package/dist/server/operations/find/nearQuery.d.ts +4 -1
  75. package/dist/server/operations/find/nearQuery.d.ts.map +1 -1
  76. package/dist/server/operations/find/nearQuery.js +30 -42
  77. package/dist/server/operations/find/nearQuery.js.map +1 -1
  78. package/dist/server/operations/find/shadowQuery.d.ts.map +1 -1
  79. package/dist/server/operations/find/shadowQuery.js +16 -143
  80. package/dist/server/operations/find/shadowQuery.js.map +1 -1
  81. package/dist/server/operations/find/utils.d.ts.map +1 -1
  82. package/dist/server/operations/find/utils.js +0 -5
  83. package/dist/server/operations/find/utils.js.map +1 -1
  84. package/dist/server/operations/insertMany.d.ts.map +1 -1
  85. package/dist/server/operations/insertMany.js +1 -4
  86. package/dist/server/operations/insertMany.js.map +1 -1
  87. package/dist/server/operations/insertOne.d.ts.map +1 -1
  88. package/dist/server/operations/insertOne.js +2 -6
  89. package/dist/server/operations/insertOne.js.map +1 -1
  90. package/dist/server/operations/operationDispatcher.d.ts.map +1 -1
  91. package/dist/server/operations/operationDispatcher.js +3 -0
  92. package/dist/server/operations/operationDispatcher.js.map +1 -1
  93. package/dist/server/operations/updateMany.d.ts.map +1 -1
  94. package/dist/server/operations/updateMany.js +23 -17
  95. package/dist/server/operations/updateMany.js.map +1 -1
  96. package/dist/server/operations/updateOne.d.ts.map +1 -1
  97. package/dist/server/operations/updateOne.js +10 -21
  98. package/dist/server/operations/updateOne.js.map +1 -1
  99. package/dist/server/query/nearSearch.d.ts +37 -25
  100. package/dist/server/query/nearSearch.d.ts.map +1 -1
  101. package/dist/server/query/nearSearch.js +87 -125
  102. package/dist/server/query/nearSearch.js.map +1 -1
  103. package/dist/server/types.d.ts +7 -1
  104. package/dist/server/types.d.ts.map +1 -1
  105. package/dist/server/utils/bulkError.d.ts +12 -0
  106. package/dist/server/utils/bulkError.d.ts.map +1 -0
  107. package/dist/server/utils/bulkError.js +21 -0
  108. package/dist/server/utils/bulkError.js.map +1 -0
  109. package/dist/server/utils/chunking.d.ts +9 -1
  110. package/dist/server/utils/chunking.d.ts.map +1 -1
  111. package/dist/server/utils/chunking.js +20 -3
  112. package/dist/server/utils/chunking.js.map +1 -1
  113. package/dist/server/utils/filter.d.ts +3 -105
  114. package/dist/server/utils/filter.d.ts.map +1 -1
  115. package/dist/server/utils/filter.js +14 -218
  116. package/dist/server/utils/filter.js.map +1 -1
  117. package/dist/server/utils/updateOperators.d.ts +12 -1
  118. package/dist/server/utils/updateOperators.d.ts.map +1 -1
  119. package/dist/server/utils/updateOperators.js +53 -6
  120. package/dist/server/utils/updateOperators.js.map +1 -1
  121. package/docs/README.md +9 -12
  122. package/package.json +1 -1
  123. package/dist/scripts/operations/bulkRecordRepair.d.ts +0 -17
  124. package/dist/scripts/operations/bulkRecordRepair.d.ts.map +0 -1
  125. package/dist/scripts/operations/bulkRecordRepair.js +0 -76
  126. package/dist/scripts/operations/bulkRecordRepair.js.map +0 -1
  127. package/dist/scripts/operations/singleRecordRepair.d.ts +0 -18
  128. package/dist/scripts/operations/singleRecordRepair.d.ts.map +0 -1
  129. package/dist/scripts/operations/singleRecordRepair.js +0 -46
  130. package/dist/scripts/operations/singleRecordRepair.js.map +0 -1
  131. package/dist/scripts/utils/awsUtils.d.ts +0 -15
  132. package/dist/scripts/utils/awsUtils.d.ts.map +0 -1
  133. package/dist/scripts/utils/awsUtils.js +0 -31
  134. package/dist/scripts/utils/awsUtils.js.map +0 -1
  135. package/dist/scripts/utils/clientFactory.d.ts +0 -22
  136. package/dist/scripts/utils/clientFactory.d.ts.map +0 -1
  137. package/dist/scripts/utils/clientFactory.js +0 -36
  138. package/dist/scripts/utils/clientFactory.js.map +0 -1
  139. package/dist/scripts/utils/repairUtils.d.ts +0 -58
  140. package/dist/scripts/utils/repairUtils.d.ts.map +0 -1
  141. package/dist/scripts/utils/repairUtils.js +0 -52
  142. package/dist/scripts/utils/repairUtils.js.map +0 -1
  143. package/dist/server/utils/ttl.d.ts +0 -17
  144. package/dist/server/utils/ttl.d.ts.map +0 -1
  145. package/dist/server/utils/ttl.js +0 -64
  146. package/dist/server/utils/ttl.js.map +0 -1
@@ -1,5 +1,5 @@
1
- // @exabugs/dynamodb-client v1.26.0
2
- // Built: 2026-11-14T13:53:42.297Z
1
+ // @exabugs/dynamodb-client v1.27.1
2
+ // Built: 2026-11-15T11:40:11.703Z
3
3
  "use strict";
4
4
  var __create = Object.create;
5
5
  var __defProp = Object.defineProperty;
@@ -2194,10 +2194,10 @@ var init_command = __esm({
2194
2194
  this.middlewareStack.use(mw);
2195
2195
  }
2196
2196
  const stack = clientStack.concat(this.middlewareStack);
2197
- const { logger: logger27 } = configuration;
2197
+ const { logger: logger26 } = configuration;
2198
2198
  const additionalSmithyContext = additionalContext[import_types2.SMITHY_CONTEXT_KEY];
2199
2199
  const handlerExecutionContext = {
2200
- logger: logger27,
2200
+ logger: logger26,
2201
2201
  clientName,
2202
2202
  commandName,
2203
2203
  inputFilterSensitiveLog,
@@ -4166,19 +4166,19 @@ var init_ProviderError = __esm({
4166
4166
  name = "ProviderError";
4167
4167
  tryNextLink;
4168
4168
  constructor(message, options = true) {
4169
- let logger27;
4169
+ let logger26;
4170
4170
  let tryNextLink = true;
4171
4171
  if (typeof options === "boolean") {
4172
- logger27 = void 0;
4172
+ logger26 = void 0;
4173
4173
  tryNextLink = options;
4174
4174
  } else if (options != null && typeof options === "object") {
4175
- logger27 = options.logger;
4175
+ logger26 = options.logger;
4176
4176
  tryNextLink = options.tryNextLink ?? true;
4177
4177
  }
4178
4178
  super(message);
4179
4179
  this.tryNextLink = tryNextLink;
4180
4180
  Object.setPrototypeOf(this, _ProviderError.prototype);
4181
- logger27?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`);
4181
+ logger26?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`);
4182
4182
  }
4183
4183
  static from(error2, options = true) {
4184
4184
  return Object.assign(new this(error2.message, options), error2);
@@ -4766,8 +4766,8 @@ var init_configLoader = __esm({
4766
4766
  init_fromSharedConfigFiles();
4767
4767
  init_fromStatic();
4768
4768
  loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => {
4769
- const { signingName, logger: logger27 } = configuration;
4770
- const envOptions = { signingName, logger: logger27 };
4769
+ const { signingName, logger: logger26 } = configuration;
4770
+ const envOptions = { signingName, logger: logger26 };
4771
4771
  return memoize(chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue)));
4772
4772
  }, "loadConfig");
4773
4773
  }
@@ -6490,7 +6490,7 @@ var init_resolveEndpoint = __esm({
6490
6490
  init_types3();
6491
6491
  init_utils();
6492
6492
  resolveEndpoint = /* @__PURE__ */ __name((ruleSetObject, options) => {
6493
- const { endpointParams, logger: logger27 } = options;
6493
+ const { endpointParams, logger: logger26 } = options;
6494
6494
  const { parameters, rules } = ruleSetObject;
6495
6495
  options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);
6496
6496
  for (const paramKey in parameters) {
@@ -6507,7 +6507,7 @@ var init_resolveEndpoint = __esm({
6507
6507
  throw new EndpointError(`Missing required parameter: '${paramKey}'`);
6508
6508
  }
6509
6509
  }
6510
- const endpoint = evaluateRules(rules, { endpointParams, logger: logger27, referenceRecord: {} });
6510
+ const endpoint = evaluateRules(rules, { endpointParams, logger: logger26, referenceRecord: {} });
6511
6511
  options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);
6512
6512
  return endpoint;
6513
6513
  }, "resolveEndpoint");
@@ -6947,7 +6947,7 @@ var init_ByteArrayCollector = __esm({
6947
6947
  });
6948
6948
 
6949
6949
  // node_modules/@smithy/core/dist-es/submodules/serde/util-stream/createBufferedReadable.browser.js
6950
- function createBufferedReadableStream(upstream, size, logger27) {
6950
+ function createBufferedReadableStream(upstream, size, logger26) {
6951
6951
  const reader = upstream.getReader();
6952
6952
  let streamBufferingLoggedWarning = false;
6953
6953
  let bytesSeen = 0;
@@ -6985,7 +6985,7 @@ function createBufferedReadableStream(upstream, size, logger27) {
6985
6985
  const newSize = merge(buffers, mode, chunk);
6986
6986
  if (!streamBufferingLoggedWarning && bytesSeen > size * 2) {
6987
6987
  streamBufferingLoggedWarning = true;
6988
- logger27?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`);
6988
+ logger26?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`);
6989
6989
  }
6990
6990
  if (newSize >= size) {
6991
6991
  controller.enqueue(flush(buffers, mode));
@@ -7049,9 +7049,9 @@ var init_createBufferedReadable_browser = __esm({
7049
7049
  });
7050
7050
 
7051
7051
  // node_modules/@smithy/core/dist-es/submodules/serde/util-stream/createBufferedReadable.js
7052
- function createBufferedReadable(upstream, size, logger27) {
7052
+ function createBufferedReadable(upstream, size, logger26) {
7053
7053
  if (isReadableStream(upstream)) {
7054
- return createBufferedReadableStream(upstream, size, logger27);
7054
+ return createBufferedReadableStream(upstream, size, logger26);
7055
7055
  }
7056
7056
  const downstream = new import_node_stream3.Readable({ read() {
7057
7057
  } });
@@ -7084,7 +7084,7 @@ function createBufferedReadable(upstream, size, logger27) {
7084
7084
  const newSize = merge(buffers, mode, chunk);
7085
7085
  if (!streamBufferingLoggedWarning && bytesSeen > size * 2) {
7086
7086
  streamBufferingLoggedWarning = true;
7087
- logger27?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`);
7087
+ logger26?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`);
7088
7088
  }
7089
7089
  if (newSize >= size) {
7090
7090
  downstream.push(flush(buffers, mode));
@@ -12769,7 +12769,7 @@ var init_constants5 = __esm({
12769
12769
  });
12770
12770
 
12771
12771
  // node_modules/@smithy/core/dist-es/submodules/retry/middleware-retry/parseRetryAfterHeader.js
12772
- function parseRetryAfterHeader(response, logger27) {
12772
+ function parseRetryAfterHeader(response, logger26) {
12773
12773
  if (!HttpResponse.isInstance(response)) {
12774
12774
  return;
12775
12775
  }
@@ -12786,8 +12786,8 @@ function parseRetryAfterHeader(response, logger27) {
12786
12786
  const date2 = parseRfc7231DateTime(retryAfter);
12787
12787
  retryAfterSeconds = (date2.getTime() - Date.now()) / 1e3;
12788
12788
  } catch (e5) {
12789
- logger27?.trace?.("Failed to parse retry-after header");
12790
- logger27?.trace?.(e5);
12789
+ logger26?.trace?.("Failed to parse retry-after header");
12790
+ logger26?.trace?.(e5);
12791
12791
  }
12792
12792
  } else if (retryAfter.match(/ GMT, ((\d+)|(\d+\.\d+))$/)) {
12793
12793
  retryAfterSeconds = Number(retryAfter.match(/ GMT, ([\d.]+)$/)?.[1]);
@@ -12804,15 +12804,15 @@ function parseRetryAfterHeader(response, logger27) {
12804
12804
  const v = response.headers[header];
12805
12805
  const backoffMilliseconds = Number(v);
12806
12806
  if (isNaN(backoffMilliseconds)) {
12807
- logger27?.trace?.(`Failed to parse x-amz-retry-after=${v}`);
12807
+ logger26?.trace?.(`Failed to parse x-amz-retry-after=${v}`);
12808
12808
  return;
12809
12809
  }
12810
12810
  return new Date(Date.now() + backoffMilliseconds);
12811
12811
  }
12812
12812
  }
12813
12813
  }
12814
- function getRetryAfterHint(response, logger27) {
12815
- return parseRetryAfterHeader(response, logger27);
12814
+ function getRetryAfterHint(response, logger26) {
12815
+ return parseRetryAfterHeader(response, logger26);
12816
12816
  }
12817
12817
  var init_parseRetryAfterHeader = __esm({
12818
12818
  "node_modules/@smithy/core/dist-es/submodules/retry/middleware-retry/parseRetryAfterHeader.js"() {
@@ -12924,12 +12924,12 @@ var init_retryMiddleware = __esm({
12924
12924
  __name(bindRetryMiddleware, "bindRetryMiddleware");
12925
12925
  cooldown = /* @__PURE__ */ __name((ms) => new Promise((resolve) => setTimeout(resolve, ms)), "cooldown");
12926
12926
  isRetryStrategyV2 = /* @__PURE__ */ __name((retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined", "isRetryStrategyV2");
12927
- getRetryErrorInfo = /* @__PURE__ */ __name((error2, logger27) => {
12927
+ getRetryErrorInfo = /* @__PURE__ */ __name((error2, logger26) => {
12928
12928
  const errorInfo = {
12929
12929
  error: error2,
12930
12930
  errorType: getRetryErrorType(error2)
12931
12931
  };
12932
- const retryAfterHint = parseRetryAfterHeader(error2.$response, logger27);
12932
+ const retryAfterHint = parseRetryAfterHeader(error2.$response, logger26);
12933
12933
  if (retryAfterHint) {
12934
12934
  errorInfo.retryAfterHint = retryAfterHint;
12935
12935
  }
@@ -13804,12 +13804,12 @@ var init_loggerMiddleware = __esm({
13804
13804
  loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => {
13805
13805
  try {
13806
13806
  const response = await next(args);
13807
- const { clientName, commandName, logger: logger27, dynamoDbDocumentClientOptions = {} } = context;
13807
+ const { clientName, commandName, logger: logger26, dynamoDbDocumentClientOptions = {} } = context;
13808
13808
  const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
13809
13809
  const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
13810
13810
  const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog;
13811
13811
  const { $metadata, ...outputWithoutMetadata } = response.output;
13812
- logger27?.info?.({
13812
+ logger26?.info?.({
13813
13813
  clientName,
13814
13814
  commandName,
13815
13815
  input: inputFilterSensitiveLog(args.input),
@@ -13818,10 +13818,10 @@ var init_loggerMiddleware = __esm({
13818
13818
  });
13819
13819
  return response;
13820
13820
  } catch (error2) {
13821
- const { clientName, commandName, logger: logger27, dynamoDbDocumentClientOptions = {} } = context;
13821
+ const { clientName, commandName, logger: logger26, dynamoDbDocumentClientOptions = {} } = context;
13822
13822
  const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
13823
13823
  const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
13824
- logger27?.error?.({
13824
+ logger26?.error?.({
13825
13825
  clientName,
13826
13826
  commandName,
13827
13827
  input: inputFilterSensitiveLog(args.input),
@@ -14583,11 +14583,11 @@ function resolveUserAgentConfig(input) {
14583
14583
  userAgentAppId: /* @__PURE__ */ __name(async () => {
14584
14584
  const appId = await normalizedAppIdProvider();
14585
14585
  if (!isValidUserAgentAppId(appId)) {
14586
- const logger27 = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger;
14586
+ const logger26 = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger;
14587
14587
  if (typeof appId !== "string") {
14588
- logger27?.warn("userAgentAppId must be a string or undefined.");
14588
+ logger26?.warn("userAgentAppId must be a string or undefined.");
14589
14589
  } else if (appId.length > 50) {
14590
- logger27?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.");
14590
+ logger26?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.");
14591
14591
  }
14592
14592
  }
14593
14593
  return appId;
@@ -19526,7 +19526,7 @@ var require_dist_cjs6 = __commonJS({
19526
19526
  var CMDS_IP = "169.254.170.2";
19527
19527
  var GREENGRASS_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1"]);
19528
19528
  var GREENGRASS_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
19529
- var getCmdsUri = /* @__PURE__ */ __name(async ({ logger: logger27 }) => {
19529
+ var getCmdsUri = /* @__PURE__ */ __name(async ({ logger: logger26 }) => {
19530
19530
  if (process.env[ENV_CMDS_RELATIVE_URI]) {
19531
19531
  return {
19532
19532
  hostname: CMDS_IP,
@@ -19538,18 +19538,18 @@ var require_dist_cjs6 = __commonJS({
19538
19538
  try {
19539
19539
  parsed = new URL(process.env[ENV_CMDS_FULL_URI]);
19540
19540
  } catch {
19541
- throw new CredentialsProviderError2(`${process.env[ENV_CMDS_FULL_URI]} is not a valid container metadata service URL`, { tryNextLink: false, logger: logger27 });
19541
+ throw new CredentialsProviderError2(`${process.env[ENV_CMDS_FULL_URI]} is not a valid container metadata service URL`, { tryNextLink: false, logger: logger26 });
19542
19542
  }
19543
19543
  if (!parsed.hostname || !GREENGRASS_HOSTS.has(parsed.hostname)) {
19544
19544
  throw new CredentialsProviderError2(`${parsed.hostname} is not a valid container metadata service hostname`, {
19545
19545
  tryNextLink: false,
19546
- logger: logger27
19546
+ logger: logger26
19547
19547
  });
19548
19548
  }
19549
19549
  if (!parsed.protocol || !GREENGRASS_PROTOCOLS.has(parsed.protocol)) {
19550
19550
  throw new CredentialsProviderError2(`${parsed.protocol} is not a valid container metadata service protocol`, {
19551
19551
  tryNextLink: false,
19552
- logger: logger27
19552
+ logger: logger26
19553
19553
  });
19554
19554
  }
19555
19555
  return {
@@ -19561,7 +19561,7 @@ var require_dist_cjs6 = __commonJS({
19561
19561
  }
19562
19562
  throw new CredentialsProviderError2(`The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`, {
19563
19563
  tryNextLink: false,
19564
- logger: logger27
19564
+ logger: logger26
19565
19565
  });
19566
19566
  }, "getCmdsUri");
19567
19567
  var InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError extends CredentialsProviderError2 {
@@ -19616,10 +19616,10 @@ var require_dist_cjs6 = __commonJS({
19616
19616
  var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60;
19617
19617
  var STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60;
19618
19618
  var STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html";
19619
- var getExtendedInstanceMetadataCredentials = /* @__PURE__ */ __name((credentials, logger27) => {
19619
+ var getExtendedInstanceMetadataCredentials = /* @__PURE__ */ __name((credentials, logger26) => {
19620
19620
  const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS);
19621
19621
  const newExpiration = new Date(Date.now() + refreshInterval * 1e3);
19622
- logger27.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}.
19622
+ logger26.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}.
19623
19623
  For more information, please visit: ` + STATIC_STABILITY_DOC_URL);
19624
19624
  const originalExpiration = credentials.originalExpiration ?? credentials.expiration;
19625
19625
  return {
@@ -19629,19 +19629,19 @@ For more information, please visit: ` + STATIC_STABILITY_DOC_URL);
19629
19629
  };
19630
19630
  }, "getExtendedInstanceMetadataCredentials");
19631
19631
  var staticStabilityProvider = /* @__PURE__ */ __name((provider, options = {}) => {
19632
- const logger27 = options?.logger || console;
19632
+ const logger26 = options?.logger || console;
19633
19633
  let pastCredentials;
19634
19634
  return async () => {
19635
19635
  let credentials;
19636
19636
  try {
19637
19637
  credentials = await provider();
19638
19638
  if (credentials.expiration && credentials.expiration.getTime() < Date.now()) {
19639
- credentials = getExtendedInstanceMetadataCredentials(credentials, logger27);
19639
+ credentials = getExtendedInstanceMetadataCredentials(credentials, logger26);
19640
19640
  }
19641
19641
  } catch (e5) {
19642
19642
  if (pastCredentials) {
19643
- logger27.warn("Credential renew failed: ", e5);
19644
- credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger27);
19643
+ logger26.warn("Credential renew failed: ", e5);
19644
+ credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger26);
19645
19645
  } else {
19646
19646
  throw e5;
19647
19647
  }
@@ -19658,7 +19658,7 @@ For more information, please visit: ` + STATIC_STABILITY_DOC_URL);
19658
19658
  var fromInstanceMetadata = /* @__PURE__ */ __name((init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger }), "fromInstanceMetadata");
19659
19659
  var getInstanceMetadataProvider = /* @__PURE__ */ __name((init = {}) => {
19660
19660
  let disableFetchToken = false;
19661
- const { logger: logger27, profile } = init;
19661
+ const { logger: logger26, profile } = init;
19662
19662
  const { timeout, maxRetries } = providerConfigFromInit(init);
19663
19663
  const getCredentials = /* @__PURE__ */ __name(async (maxRetries2, options) => {
19664
19664
  const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN2] == null;
@@ -19722,7 +19722,7 @@ For more information, please visit: ` + STATIC_STABILITY_DOC_URL);
19722
19722
  return async () => {
19723
19723
  const endpoint = await getInstanceMetadataEndpoint();
19724
19724
  if (disableFetchToken) {
19725
- logger27?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)");
19725
+ logger26?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)");
19726
19726
  return getCredentials(maxRetries, { ...endpoint, timeout });
19727
19727
  } else {
19728
19728
  let token;
@@ -19736,7 +19736,7 @@ For more information, please visit: ` + STATIC_STABILITY_DOC_URL);
19736
19736
  } else if (error2.message === "TimeoutError" || [403, 404, 405].includes(error2.statusCode)) {
19737
19737
  disableFetchToken = true;
19738
19738
  }
19739
- logger27?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)");
19739
+ logger26?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)");
19740
19740
  return getCredentials(maxRetries, { ...endpoint, timeout });
19741
19741
  }
19742
19742
  return getCredentials(maxRetries, {
@@ -19861,7 +19861,7 @@ var require_dist_cjs7 = __commonJS({
19861
19861
  }
19862
19862
  return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2);
19863
19863
  }, "setConnectionTimeout");
19864
- var setRequestTimeout = /* @__PURE__ */ __name((req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger27) => {
19864
+ var setRequestTimeout = /* @__PURE__ */ __name((req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger26) => {
19865
19865
  if (timeoutInMs) {
19866
19866
  return timing.setTimeout(() => {
19867
19867
  let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? "ERROR" : "WARN"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`;
@@ -19874,7 +19874,7 @@ var require_dist_cjs7 = __commonJS({
19874
19874
  reject(error2);
19875
19875
  } else {
19876
19876
  msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`;
19877
- logger27?.warn?.(msg);
19877
+ logger26?.warn?.(msg);
19878
19878
  }
19879
19879
  }, timeoutInMs);
19880
19880
  }
@@ -20015,7 +20015,7 @@ var require_dist_cjs7 = __commonJS({
20015
20015
  }
20016
20016
  return new _NodeHttpHandler(instanceOrOptions);
20017
20017
  }
20018
- static checkSocketUsage(agent, socketWarningTimestamp, logger27 = console) {
20018
+ static checkSocketUsage(agent, socketWarningTimestamp, logger26 = console) {
20019
20019
  const { sockets, requests, maxSockets } = agent;
20020
20020
  if (typeof maxSockets !== "number" || maxSockets === Infinity) {
20021
20021
  return socketWarningTimestamp;
@@ -20032,7 +20032,7 @@ var require_dist_cjs7 = __commonJS({
20032
20032
  const socketsInUse = sockets[origin]?.length ?? 0;
20033
20033
  const requestsEnqueued = requests[origin]?.length ?? 0;
20034
20034
  if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {
20035
- logger27?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.
20035
+ logger26?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.
20036
20036
  See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
20037
20037
  or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`);
20038
20038
  return Date.now();
@@ -20061,7 +20061,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
20061
20061
  this.config = await this.configProvider;
20062
20062
  }
20063
20063
  const config = this.config;
20064
- const logger27 = config.logger;
20064
+ const logger26 = config.logger;
20065
20065
  const isSSL = request2.protocol === "https:";
20066
20066
  if (!isSSL && !this.config.httpAgent) {
20067
20067
  this.config.httpAgent = await this.config.httpAgentProvider();
@@ -20105,7 +20105,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
20105
20105
  });
20106
20106
  }
20107
20107
  socketWarningTimeoutId = timing.setTimeout(() => {
20108
- this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, logger27);
20108
+ this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, logger26);
20109
20109
  }, config.socketAcquisitionWarningTimeout ?? (config.requestTimeout ?? 2e3) + (config.connectionTimeout ?? 1e3));
20110
20110
  const queryString = request2.query ? buildQueryString2(request2.query) : "";
20111
20111
  let auth = void 0;
@@ -20169,7 +20169,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
20169
20169
  }
20170
20170
  const effectiveRequestTimeout = requestTimeout ?? config.requestTimeout;
20171
20171
  connectionTimeoutId = setConnectionTimeout(req, reject, config.connectionTimeout);
20172
- requestTimeoutId = setRequestTimeout(req, reject, effectiveRequestTimeout, config.throwOnRequestTimeout, logger27 ?? console);
20172
+ requestTimeoutId = setRequestTimeout(req, reject, effectiveRequestTimeout, config.throwOnRequestTimeout, logger26 ?? console);
20173
20173
  const defaultSocketTimeout = config.socketTimeout === void 0 ? resolveDefaultSocketTimeout(config) : void 0;
20174
20174
  if (defaultSocketTimeout) {
20175
20175
  socketTimeoutId = setSocketTimeout(req, reject, defaultSocketTimeout, true);
@@ -20212,7 +20212,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
20212
20212
  return this.config ?? {};
20213
20213
  }
20214
20214
  resolveDefaultConfig(options) {
20215
- const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, logger: logger27 } = options || {};
20215
+ const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, logger: logger26 } = options || {};
20216
20216
  const keepAlive = true;
20217
20217
  const maxSockets = 50;
20218
20218
  let httpAgentPromise;
@@ -20241,7 +20241,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
20241
20241
  }
20242
20242
  return new node_https.Agent({ keepAlive, maxSockets, ...httpsAgent });
20243
20243
  })(),
20244
- logger: logger27
20244
+ logger: logger26
20245
20245
  };
20246
20246
  }
20247
20247
  };
@@ -20687,7 +20687,7 @@ var require_dist_cjs8 = __commonJS({
20687
20687
  var ECS_CONTAINER_HOST = "169.254.170.2";
20688
20688
  var EKS_CONTAINER_HOST_IPv4 = "169.254.170.23";
20689
20689
  var EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]";
20690
- var checkUrl = /* @__PURE__ */ __name((url, logger27) => {
20690
+ var checkUrl = /* @__PURE__ */ __name((url, logger26) => {
20691
20691
  if (url.protocol === "https:") {
20692
20692
  return;
20693
20693
  }
@@ -20714,7 +20714,7 @@ var require_dist_cjs8 = __commonJS({
20714
20714
  throw new CredentialsProviderError2(`URL not accepted. It must either be HTTPS or match one of the following:
20715
20715
  - loopback CIDR 127.0.0.0/8 or [::1/128]
20716
20716
  - ECS container host 169.254.170.2
20717
- - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger: logger27 });
20717
+ - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger: logger26 });
20718
20718
  }, "checkUrl");
20719
20719
  function createGetRequest(url) {
20720
20720
  return new HttpRequest2({
@@ -20730,13 +20730,13 @@ var require_dist_cjs8 = __commonJS({
20730
20730
  });
20731
20731
  }
20732
20732
  __name(createGetRequest, "createGetRequest");
20733
- async function getCredentials(response, logger27) {
20733
+ async function getCredentials(response, logger26) {
20734
20734
  const stream = sdkStreamMixin3(response.body);
20735
20735
  const str = await stream.transformToString();
20736
20736
  if (response.statusCode === 200) {
20737
20737
  const parsed = JSON.parse(str);
20738
20738
  if (typeof parsed.AccessKeyId !== "string" || typeof parsed.SecretAccessKey !== "string" || typeof parsed.Token !== "string" || typeof parsed.Expiration !== "string") {
20739
- throw new CredentialsProviderError2("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger: logger27 });
20739
+ throw new CredentialsProviderError2("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger: logger26 });
20740
20740
  }
20741
20741
  return {
20742
20742
  accessKeyId: parsed.AccessKeyId,
@@ -20751,12 +20751,12 @@ var require_dist_cjs8 = __commonJS({
20751
20751
  parsedBody = JSON.parse(str);
20752
20752
  } catch (e5) {
20753
20753
  }
20754
- throw Object.assign(new CredentialsProviderError2(`Server responded with status: ${response.statusCode}`, { logger: logger27 }), {
20754
+ throw Object.assign(new CredentialsProviderError2(`Server responded with status: ${response.statusCode}`, { logger: logger26 }), {
20755
20755
  Code: parsedBody.Code,
20756
20756
  Message: parsedBody.Message
20757
20757
  });
20758
20758
  }
20759
- throw new CredentialsProviderError2(`Server responded with status: ${response.statusCode}`, { logger: logger27 });
20759
+ throw new CredentialsProviderError2(`Server responded with status: ${response.statusCode}`, { logger: logger26 });
20760
20760
  }
20761
20761
  __name(getCredentials, "getCredentials");
20762
20762
  var retryWrapper = /* @__PURE__ */ __name((toRetry, maxRetries, delayMs) => {
@@ -25470,14 +25470,14 @@ var require_dist_cjs10 = __commonJS({
25470
25470
  var { getBearerTokenEnvKey: getBearerTokenEnvKey2 } = (init_httpAuthSchemes2(), __toCommonJS(httpAuthSchemes_exports));
25471
25471
  var { TokenProviderError: TokenProviderError2, getSSOTokenFilepath: getSSOTokenFilepath2, parseKnownFiles: parseKnownFiles2, getProfileName: getProfileName2, loadSsoSessionData: loadSsoSessionData2, getSSOTokenFromFile: getSSOTokenFromFile2, memoize: memoize2, chain: chain2 } = (init_config2(), __toCommonJS(config_exports));
25472
25472
  var { promises } = require("node:fs");
25473
- var fromEnvSigningName = /* @__PURE__ */ __name(({ logger: logger27, signingName } = {}) => async () => {
25474
- logger27?.debug?.("@aws-sdk/token-providers - fromEnvSigningName");
25473
+ var fromEnvSigningName = /* @__PURE__ */ __name(({ logger: logger26, signingName } = {}) => async () => {
25474
+ logger26?.debug?.("@aws-sdk/token-providers - fromEnvSigningName");
25475
25475
  if (!signingName) {
25476
- throw new TokenProviderError2("Please pass 'signingName' to compute environment variable key", { logger: logger27 });
25476
+ throw new TokenProviderError2("Please pass 'signingName' to compute environment variable key", { logger: logger26 });
25477
25477
  }
25478
25478
  const bearerTokenKey = getBearerTokenEnvKey2(signingName);
25479
25479
  if (!(bearerTokenKey in process.env)) {
25480
- throw new TokenProviderError2(`Token not present in '${bearerTokenKey}' environment variable`, { logger: logger27 });
25480
+ throw new TokenProviderError2(`Token not present in '${bearerTokenKey}' environment variable`, { logger: logger26 });
25481
25481
  }
25482
25482
  const token = { token: process.env[bearerTokenKey] };
25483
25483
  setTokenFeature2(token, "BEARER_SERVICE_ENV_VARS", "3");
@@ -25612,8 +25612,8 @@ var require_dist_cjs10 = __commonJS({
25612
25612
  inFlightRefreshes.delete(ssoSessionName);
25613
25613
  }
25614
25614
  }, "fromSso");
25615
- var fromStatic2 = /* @__PURE__ */ __name(({ token, logger: logger27 }) => async () => {
25616
- logger27?.debug("@aws-sdk/token-providers - fromStatic");
25615
+ var fromStatic2 = /* @__PURE__ */ __name(({ token, logger: logger26 }) => async () => {
25616
+ logger26?.debug("@aws-sdk/token-providers - fromStatic");
25617
25617
  if (!token || !token.token) {
25618
25618
  throw new TokenProviderError2(`Please pass a valid token to fromStatic`, false);
25619
25619
  }
@@ -26363,7 +26363,7 @@ var require_dist_cjs11 = __commonJS({
26363
26363
  var { fromSso } = require_dist_cjs10();
26364
26364
  var isSsoProfile = /* @__PURE__ */ __name((arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"), "isSsoProfile");
26365
26365
  var SHOULD_FAIL_CREDENTIAL_CHAIN = false;
26366
- var resolveSSOCredentials = /* @__PURE__ */ __name(async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, callerClientConfig, profile, filepath, configFilepath, ignoreCache, logger: logger27 }) => {
26366
+ var resolveSSOCredentials = /* @__PURE__ */ __name(async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, callerClientConfig, profile, filepath, configFilepath, ignoreCache, logger: logger26 }) => {
26367
26367
  let token;
26368
26368
  const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;
26369
26369
  if (ssoSession) {
@@ -26375,7 +26375,7 @@ var require_dist_cjs11 = __commonJS({
26375
26375
  ignoreCache,
26376
26376
  clientConfig,
26377
26377
  parentClientConfig,
26378
- logger: logger27
26378
+ logger: logger26
26379
26379
  })({ callerClientConfig });
26380
26380
  token = {
26381
26381
  accessToken: _token.token,
@@ -26384,7 +26384,7 @@ var require_dist_cjs11 = __commonJS({
26384
26384
  } catch (e5) {
26385
26385
  throw new CredentialsProviderError2(e5.message, {
26386
26386
  tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
26387
- logger: logger27
26387
+ logger: logger26
26388
26388
  });
26389
26389
  }
26390
26390
  } else {
@@ -26393,14 +26393,14 @@ var require_dist_cjs11 = __commonJS({
26393
26393
  } catch (e5) {
26394
26394
  throw new CredentialsProviderError2(`The SSO session associated with this profile is invalid. ${refreshMessage}`, {
26395
26395
  tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
26396
- logger: logger27
26396
+ logger: logger26
26397
26397
  });
26398
26398
  }
26399
26399
  }
26400
26400
  if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {
26401
26401
  throw new CredentialsProviderError2(`The SSO session associated with this profile has expired. ${refreshMessage}`, {
26402
26402
  tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
26403
- logger: logger27
26403
+ logger: logger26
26404
26404
  });
26405
26405
  }
26406
26406
  const { accessToken } = token;
@@ -26420,14 +26420,14 @@ var require_dist_cjs11 = __commonJS({
26420
26420
  } catch (e5) {
26421
26421
  throw new CredentialsProviderError2(e5, {
26422
26422
  tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
26423
- logger: logger27
26423
+ logger: logger26
26424
26424
  });
26425
26425
  }
26426
26426
  const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} } = ssoResp;
26427
26427
  if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {
26428
26428
  throw new CredentialsProviderError2("SSO returns an invalid temporary credential.", {
26429
26429
  tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
26430
- logger: logger27
26430
+ logger: logger26
26431
26431
  });
26432
26432
  }
26433
26433
  const credentials = {
@@ -26445,11 +26445,11 @@ var require_dist_cjs11 = __commonJS({
26445
26445
  }
26446
26446
  return credentials;
26447
26447
  }, "resolveSSOCredentials");
26448
- var validateSsoProfile = /* @__PURE__ */ __name((profile, logger27) => {
26448
+ var validateSsoProfile = /* @__PURE__ */ __name((profile, logger26) => {
26449
26449
  const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile;
26450
26450
  if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {
26451
26451
  throw new CredentialsProviderError2(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join(", ")}
26452
- Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger: logger27 });
26452
+ Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger: logger26 });
26453
26453
  }
26454
26454
  return profile;
26455
26455
  }, "validateSsoProfile");
@@ -28348,9 +28348,9 @@ var init_defaultStsRoleAssumers = __esm({
28348
28348
  return async (sourceCreds, params) => {
28349
28349
  closureSourceCreds = sourceCreds;
28350
28350
  if (!stsClient) {
28351
- const { logger: logger27 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions;
28351
+ const { logger: logger26 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions;
28352
28352
  const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, {
28353
- logger: logger27,
28353
+ logger: logger26,
28354
28354
  profile
28355
28355
  });
28356
28356
  const isCompatibleRequestHandler = !isH2(requestHandler);
@@ -28361,7 +28361,7 @@ var init_defaultStsRoleAssumers = __esm({
28361
28361
  credentialDefaultProvider: /* @__PURE__ */ __name(() => async () => closureSourceCreds, "credentialDefaultProvider"),
28362
28362
  region: resolvedRegion,
28363
28363
  requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
28364
- logger: logger27
28364
+ logger: logger26
28365
28365
  });
28366
28366
  }
28367
28367
  const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params));
@@ -28385,9 +28385,9 @@ var init_defaultStsRoleAssumers = __esm({
28385
28385
  let stsClient;
28386
28386
  return async (params) => {
28387
28387
  if (!stsClient) {
28388
- const { logger: logger27 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions;
28388
+ const { logger: logger26 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions;
28389
28389
  const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, {
28390
- logger: logger27,
28390
+ logger: logger26,
28391
28391
  profile
28392
28392
  });
28393
28393
  const isCompatibleRequestHandler = !isH2(requestHandler);
@@ -28397,7 +28397,7 @@ var init_defaultStsRoleAssumers = __esm({
28397
28397
  profile,
28398
28398
  region: resolvedRegion,
28399
28399
  requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
28400
- logger: logger27
28400
+ logger: logger26
28401
28401
  });
28402
28402
  }
28403
28403
  const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params));
@@ -29528,7 +29528,7 @@ var require_dist_cjs14 = __commonJS({
29528
29528
  return this.toCredentials(freshToken.accessToken);
29529
29529
  }
29530
29530
  const { SigninClient: SigninClient2, CreateOAuth2TokenCommand: CreateOAuth2TokenCommand2 } = (init_signin(), __toCommonJS(signin_exports));
29531
- const { logger: logger27, userAgentAppId } = this.callerClientConfig ?? {};
29531
+ const { logger: logger26, userAgentAppId } = this.callerClientConfig ?? {};
29532
29532
  const isH22 = /* @__PURE__ */ __name((requestHandler2) => {
29533
29533
  return requestHandler2?.metadata?.handlerProtocol === "h2";
29534
29534
  }, "isH2");
@@ -29541,7 +29541,7 @@ var require_dist_cjs14 = __commonJS({
29541
29541
  },
29542
29542
  region,
29543
29543
  requestHandler,
29544
- logger: logger27,
29544
+ logger: logger26,
29545
29545
  userAgentAppId,
29546
29546
  ...this.init?.clientConfig
29547
29547
  });
@@ -29789,7 +29789,7 @@ var require_dist_cjs15 = __commonJS({
29789
29789
  setCredentialFeature2(credentials, "CREDENTIALS_PROCESS", "w");
29790
29790
  return credentials;
29791
29791
  }, "getValidatedProcessCredentials");
29792
- var resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles, logger27) => {
29792
+ var resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles, logger26) => {
29793
29793
  const profile = profiles[profileName];
29794
29794
  if (profiles[profileName]) {
29795
29795
  const credentialProcess = profile["credential_process"];
@@ -29805,14 +29805,14 @@ var require_dist_cjs15 = __commonJS({
29805
29805
  }
29806
29806
  return getValidatedProcessCredentials(profileName, data, profiles);
29807
29807
  } catch (error2) {
29808
- throw new CredentialsProviderError2(error2.message, { logger: logger27 });
29808
+ throw new CredentialsProviderError2(error2.message, { logger: logger26 });
29809
29809
  }
29810
29810
  } else {
29811
- throw new CredentialsProviderError2(`Profile ${profileName} did not contain credential_process.`, { logger: logger27 });
29811
+ throw new CredentialsProviderError2(`Profile ${profileName} did not contain credential_process.`, { logger: logger26 });
29812
29812
  }
29813
29813
  } else {
29814
29814
  throw new CredentialsProviderError2(`Profile ${profileName} could not be found in shared credentials file.`, {
29815
- logger: logger27
29815
+ logger: logger26
29816
29816
  });
29817
29817
  }
29818
29818
  }, "resolveProcessCredentials");
@@ -29892,21 +29892,21 @@ var require_dist_cjs17 = __commonJS({
29892
29892
  "node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js"(exports2) {
29893
29893
  var { CredentialsProviderError: CredentialsProviderError2, chain: chain2, getProfileName: getProfileName2, parseKnownFiles: parseKnownFiles2 } = (init_config2(), __toCommonJS(config_exports));
29894
29894
  var { setCredentialFeature: setCredentialFeature2 } = (init_client3(), __toCommonJS(client_exports2));
29895
- var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName, logger27) => {
29895
+ var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName, logger26) => {
29896
29896
  const sourceProvidersMap = {
29897
29897
  EcsContainer: /* @__PURE__ */ __name(async (options) => {
29898
29898
  const { fromHttp } = require_dist_cjs8();
29899
29899
  const { fromContainerMetadata } = require_dist_cjs6();
29900
- logger27?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer");
29900
+ logger26?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer");
29901
29901
  return async () => chain2(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider);
29902
29902
  }, "EcsContainer"),
29903
29903
  Ec2InstanceMetadata: /* @__PURE__ */ __name(async (options) => {
29904
- logger27?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");
29904
+ logger26?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");
29905
29905
  const { fromInstanceMetadata } = require_dist_cjs6();
29906
29906
  return async () => fromInstanceMetadata(options)().then(setNamedProvider);
29907
29907
  }, "Ec2InstanceMetadata"),
29908
29908
  Environment: /* @__PURE__ */ __name(async (options) => {
29909
- logger27?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");
29909
+ logger26?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");
29910
29910
  const { fromEnv: fromEnv2 } = require_dist_cjs5();
29911
29911
  return async () => fromEnv2(options)().then(setNamedProvider);
29912
29912
  }, "Environment")
@@ -29914,24 +29914,24 @@ var require_dist_cjs17 = __commonJS({
29914
29914
  if (credentialSource in sourceProvidersMap) {
29915
29915
  return sourceProvidersMap[credentialSource];
29916
29916
  } else {
29917
- throw new CredentialsProviderError2(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger: logger27 });
29917
+ throw new CredentialsProviderError2(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger: logger26 });
29918
29918
  }
29919
29919
  }, "resolveCredentialSource");
29920
29920
  var setNamedProvider = /* @__PURE__ */ __name((creds) => setCredentialFeature2(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"), "setNamedProvider");
29921
- var isAssumeRoleProfile = /* @__PURE__ */ __name((arg, { profile = "default", logger: logger27 } = {}) => {
29922
- return Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg, { profile, logger: logger27 }) || isCredentialSourceProfile(arg, { profile, logger: logger27 }));
29921
+ var isAssumeRoleProfile = /* @__PURE__ */ __name((arg, { profile = "default", logger: logger26 } = {}) => {
29922
+ return Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg, { profile, logger: logger26 }) || isCredentialSourceProfile(arg, { profile, logger: logger26 }));
29923
29923
  }, "isAssumeRoleProfile");
29924
- var isAssumeRoleWithSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger: logger27 }) => {
29924
+ var isAssumeRoleWithSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger: logger26 }) => {
29925
29925
  const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined";
29926
29926
  if (withSourceProfile) {
29927
- logger27?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`);
29927
+ logger26?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`);
29928
29928
  }
29929
29929
  return withSourceProfile;
29930
29930
  }, "isAssumeRoleWithSourceProfile");
29931
- var isCredentialSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger: logger27 }) => {
29931
+ var isCredentialSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger: logger26 }) => {
29932
29932
  const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined";
29933
29933
  if (withProviderProfile) {
29934
- logger27?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`);
29934
+ logger26?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`);
29935
29935
  }
29936
29936
  return withProviderProfile;
29937
29937
  }, "isCredentialSourceProfile");
@@ -36066,7 +36066,7 @@ var require_dist_cjs20 = __commonJS({
36066
36066
  __name(this, "PutResourcePolicyCommand");
36067
36067
  }
36068
36068
  };
36069
- var QueryCommand5 = class extends command5(_ep2, _mw05, "Query", Query$) {
36069
+ var QueryCommand6 = class extends command5(_ep2, _mw05, "Query", Query$) {
36070
36070
  static {
36071
36071
  __name(this, "QueryCommand");
36072
36072
  }
@@ -36160,7 +36160,7 @@ var require_dist_cjs20 = __commonJS({
36160
36160
  var paginateListExports = createPaginator2(DynamoDBClient2, ListExportsCommand, "NextToken", "NextToken", "MaxResults");
36161
36161
  var paginateListImports = createPaginator2(DynamoDBClient2, ListImportsCommand, "NextToken", "NextToken", "PageSize");
36162
36162
  var paginateListTables = createPaginator2(DynamoDBClient2, ListTablesCommand, "ExclusiveStartTableName", "LastEvaluatedTableName", "Limit");
36163
- var paginateQuery = createPaginator2(DynamoDBClient2, QueryCommand5, "ExclusiveStartKey", "LastEvaluatedKey", "Limit");
36163
+ var paginateQuery = createPaginator2(DynamoDBClient2, QueryCommand6, "ExclusiveStartKey", "LastEvaluatedKey", "Limit");
36164
36164
  var paginateScan = createPaginator2(DynamoDBClient2, ScanCommand, "ExclusiveStartKey", "LastEvaluatedKey", "Limit");
36165
36165
  var checkState$5 = /* @__PURE__ */ __name(async (client, input) => {
36166
36166
  let reason;
@@ -36422,7 +36422,7 @@ var require_dist_cjs20 = __commonJS({
36422
36422
  ListTagsOfResourceCommand,
36423
36423
  PutItemCommand,
36424
36424
  PutResourcePolicyCommand,
36425
- QueryCommand: QueryCommand5,
36425
+ QueryCommand: QueryCommand6,
36426
36426
  RestoreTableFromBackupCommand,
36427
36427
  RestoreTableToPointInTimeCommand,
36428
36428
  ScanCommand,
@@ -37036,7 +37036,7 @@ var require_dist_cjs20 = __commonJS({
37036
37036
  exports2.PutResourcePolicyInput$ = PutResourcePolicyInput$;
37037
37037
  exports2.PutResourcePolicyOutput$ = PutResourcePolicyOutput$;
37038
37038
  exports2.Query$ = Query$;
37039
- exports2.QueryCommand = QueryCommand5;
37039
+ exports2.QueryCommand = QueryCommand6;
37040
37040
  exports2.QueryInput$ = QueryInput$;
37041
37041
  exports2.QueryOutput$ = QueryOutput$;
37042
37042
  exports2.Replica$ = Replica$;
@@ -37964,7 +37964,7 @@ var require_dist_cjs22 = __commonJS({
37964
37964
  return async () => handler2(this.clientCommand);
37965
37965
  }
37966
37966
  };
37967
- var QueryCommand5 = class extends DynamoDBDocumentClientCommand {
37967
+ var QueryCommand6 = class extends DynamoDBDocumentClientCommand {
37968
37968
  static {
37969
37969
  __name(this, "QueryCommand");
37970
37970
  }
@@ -38215,7 +38215,7 @@ var require_dist_cjs22 = __commonJS({
38215
38215
  const hasSerializer = middlewares.some((m3) => m3.includes?.("serializerMiddleware"));
38216
38216
  if (!hasSerializer) {
38217
38217
  const configuredLogger = this.config.logger;
38218
- const logger27 = configuredLogger && !configuredLogger.constructor?.name.includes("NoOp") ? configuredLogger : console;
38218
+ const logger26 = configuredLogger && !configuredLogger.constructor?.name.includes("NoOp") ? configuredLogger : console;
38219
38219
  const substituteClient = new DynamoDBClient2(Object.assign({}, this.config, {
38220
38220
  defaultUserAgentProvider: void 0,
38221
38221
  retryStrategy: void 0,
@@ -38228,7 +38228,7 @@ var require_dist_cjs22 = __commonJS({
38228
38228
  this.middlewareStack = substituteClient.middlewareStack;
38229
38229
  this.config = substituteClient.config;
38230
38230
  this.config.translateConfig = translateConfig;
38231
- logger27.warn("@aws-sdk/lib-dynamodb - WARN: incompatible version of DynamoDBClient given to DynamoDBDocumentClient. We have forwarded your client's configuration to a newer version of DynamoDBClient in the dependency closure to instantiate DynamoDBDocumentClient.");
38231
+ logger26.warn("@aws-sdk/lib-dynamodb - WARN: incompatible version of DynamoDBClient given to DynamoDBDocumentClient. We have forwarded your client's configuration to a newer version of DynamoDBClient in the dependency closure to instantiate DynamoDBDocumentClient.");
38232
38232
  }
38233
38233
  }
38234
38234
  }
@@ -38238,7 +38238,7 @@ var require_dist_cjs22 = __commonJS({
38238
38238
  destroy() {
38239
38239
  }
38240
38240
  };
38241
- var paginateQuery = createPaginator2(DynamoDBDocumentClient2, QueryCommand5, "ExclusiveStartKey", "LastEvaluatedKey", "Limit");
38241
+ var paginateQuery = createPaginator2(DynamoDBDocumentClient2, QueryCommand6, "ExclusiveStartKey", "LastEvaluatedKey", "Limit");
38242
38242
  var paginateScan = createPaginator2(DynamoDBDocumentClient2, ScanCommand, "ExclusiveStartKey", "LastEvaluatedKey", "Limit");
38243
38243
  async function* paginatedBatchGet(config, input) {
38244
38244
  let requestItems = input.RequestItems;
@@ -38390,7 +38390,7 @@ var require_dist_cjs22 = __commonJS({
38390
38390
  }
38391
38391
  }
38392
38392
  query(args, optionsOrCb, cb) {
38393
- const command5 = new QueryCommand5(args);
38393
+ const command5 = new QueryCommand6(args);
38394
38394
  if (typeof optionsOrCb === "function") {
38395
38395
  this.send(command5, optionsOrCb);
38396
38396
  } else if (typeof cb === "function") {
@@ -38481,7 +38481,7 @@ var require_dist_cjs22 = __commonJS({
38481
38481
  exports2.ExportTableToPointInTimeCommand = ExportTableToPointInTimeCommand;
38482
38482
  exports2.GetCommand = GetCommand;
38483
38483
  exports2.PutCommand = PutCommand;
38484
- exports2.QueryCommand = QueryCommand5;
38484
+ exports2.QueryCommand = QueryCommand6;
38485
38485
  exports2.ScanCommand = ScanCommand;
38486
38486
  exports2.SearchVectorsCommand = SearchVectorsCommand;
38487
38487
  exports2.TransactGetCommand = TransactGetCommand;
@@ -38934,6 +38934,9 @@ function isGeoCoordinates(value) {
38934
38934
  function encodeGeoHash(latitude, longitude, precision = 6) {
38935
38935
  return import_ngeohash.default.encode(latitude, longitude, precision);
38936
38936
  }
38937
+ function decodeGeoHash(geohash) {
38938
+ return import_ngeohash.default.decode(geohash);
38939
+ }
38937
38940
  function getNeighborGeoHashes(geohash) {
38938
38941
  const neighbors = [
38939
38942
  geohash,
@@ -39004,6 +39007,7 @@ var init_utils5 = __esm({
39004
39007
  import_ngeohash = __toESM(require_main(), 1);
39005
39008
  __name(isGeoCoordinates, "isGeoCoordinates");
39006
39009
  __name(encodeGeoHash, "encodeGeoHash");
39010
+ __name(decodeGeoHash, "decodeGeoHash");
39007
39011
  __name(getNeighborGeoHashes, "getNeighborGeoHashes");
39008
39012
  __name(calculateDistance, "calculateDistance");
39009
39013
  __name(isNearQueryGeoJSON, "isNearQueryGeoJSON");
@@ -39034,6 +39038,128 @@ var init_shared = __esm({
39034
39038
  }
39035
39039
  });
39036
39040
 
39041
+ // src/server/utils/cost-tracker.ts
39042
+ var CostTracker;
39043
+ var init_cost_tracker = __esm({
39044
+ "src/server/utils/cost-tracker.ts"() {
39045
+ "use strict";
39046
+ CostTracker = class {
39047
+ static {
39048
+ __name(this, "CostTracker");
39049
+ }
39050
+ totalRCU = 0;
39051
+ totalWCU = 0;
39052
+ operationCount = 0;
39053
+ /**
39054
+ * ConsumedCapacityを追加
39055
+ *
39056
+ * DynamoDB操作のConsumedCapacityを累積します。
39057
+ * undefinedが渡された場合は何もしません(エラーにしない)。
39058
+ *
39059
+ * AWS SDKのConsumedCapacityは以下のフィールドを持ちます:
39060
+ * - CapacityUnits: 総キャパシティユニット(RCU + WCU)
39061
+ * - ReadCapacityUnits: 読み取りキャパシティユニット
39062
+ * - WriteCapacityUnits: 書き込みキャパシティユニット
39063
+ *
39064
+ * このメソッドはReadCapacityUnitsとWriteCapacityUnitsを優先的に使用し、
39065
+ * 存在しない場合はCapacityUnitsを読み取りとして扱います。
39066
+ *
39067
+ * @param consumedCapacity - DynamoDB操作のConsumedCapacity
39068
+ */
39069
+ add(consumedCapacity) {
39070
+ if (!consumedCapacity) {
39071
+ return;
39072
+ }
39073
+ const rcu = consumedCapacity.ReadCapacityUnits ?? 0;
39074
+ const wcu = consumedCapacity.WriteCapacityUnits ?? 0;
39075
+ this.totalRCU += rcu;
39076
+ this.totalWCU += wcu;
39077
+ this.operationCount += 1;
39078
+ }
39079
+ /**
39080
+ * 集計結果を取得
39081
+ *
39082
+ * これまでに追加されたConsumedCapacityの集計結果を返します。
39083
+ *
39084
+ * @returns 集計されたコスト情報
39085
+ */
39086
+ getAggregated() {
39087
+ return {
39088
+ totalRCU: this.totalRCU,
39089
+ totalWCU: this.totalWCU,
39090
+ operationCount: this.operationCount
39091
+ };
39092
+ }
39093
+ /**
39094
+ * リセット
39095
+ *
39096
+ * 累積されたコスト情報をクリアします。
39097
+ */
39098
+ reset() {
39099
+ this.totalRCU = 0;
39100
+ this.totalWCU = 0;
39101
+ this.operationCount = 0;
39102
+ }
39103
+ };
39104
+ }
39105
+ });
39106
+
39107
+ // src/server/utils/dynamodb.ts
39108
+ function getDBClient() {
39109
+ if (!dbClient) {
39110
+ dbClient = createDynamoDBClient({
39111
+ region: process.env.AWS_REGION || process.env.REGION
39112
+ });
39113
+ }
39114
+ return dbClient;
39115
+ }
39116
+ function getTableName() {
39117
+ const tableName = process.env.TABLE_NAME;
39118
+ if (!tableName) {
39119
+ throw new ConfigError("TABLE_NAME environment variable is not set");
39120
+ }
39121
+ return tableName;
39122
+ }
39123
+ function removeShadowKeys(record) {
39124
+ const { __shadowKeys, ...rest } = record;
39125
+ return rest;
39126
+ }
39127
+ function extractCleanRecord(item) {
39128
+ const data = item.data || item;
39129
+ return removeShadowKeys(data);
39130
+ }
39131
+ async function executeDynamoDBOperation(operation2, operationName) {
39132
+ try {
39133
+ return await operation2();
39134
+ } catch (error2) {
39135
+ if (error2 instanceof Error && error2.name === "AccessDeniedException") {
39136
+ logger2.error("DynamoDB access denied", {
39137
+ errorName: error2.name,
39138
+ errorMessage: error2.message,
39139
+ operation: operationName,
39140
+ tableName: process.env.TABLE_NAME,
39141
+ region: process.env.AWS_REGION || process.env.REGION
39142
+ });
39143
+ throw new Error(`Insufficient permissions to access DynamoDB: ${operationName}`);
39144
+ }
39145
+ throw error2;
39146
+ }
39147
+ }
39148
+ var logger2, dbClient;
39149
+ var init_dynamodb3 = __esm({
39150
+ "src/server/utils/dynamodb.ts"() {
39151
+ "use strict";
39152
+ init_shared();
39153
+ logger2 = createLogger({ service: "records-lambda" });
39154
+ dbClient = null;
39155
+ __name(getDBClient, "getDBClient");
39156
+ __name(getTableName, "getTableName");
39157
+ __name(removeShadowKeys, "removeShadowKeys");
39158
+ __name(extractCleanRecord, "extractCleanRecord");
39159
+ __name(executeDynamoDBOperation, "executeDynamoDBOperation");
39160
+ }
39161
+ });
39162
+
39037
39163
  // src/shared/constants/formatting.ts
39038
39164
  var init_formatting = __esm({
39039
39165
  "src/shared/constants/formatting.ts"() {
@@ -39318,435 +39444,153 @@ var init_shadow = __esm({
39318
39444
  }
39319
39445
  });
39320
39446
 
39321
- // src/server/utils/dynamodb.ts
39322
- function getDBClient() {
39323
- if (!dbClient) {
39324
- dbClient = createDynamoDBClient({
39325
- region: process.env.AWS_REGION || process.env.REGION
39326
- });
39327
- }
39328
- return dbClient;
39329
- }
39330
- function getTableName() {
39331
- const tableName = process.env.TABLE_NAME;
39332
- if (!tableName) {
39333
- throw new ConfigError("TABLE_NAME environment variable is not set");
39447
+ // src/server/operations/find/keyCondition.ts
39448
+ function buildKeyCondition(resource, sortField, optimizableFilter, secondFilter) {
39449
+ const expressionAttributeValues = {
39450
+ ":pk": resource
39451
+ };
39452
+ if (!optimizableFilter) {
39453
+ return {
39454
+ keyConditionExpression: "PK = :pk AND begins_with(SK, :skPrefix)",
39455
+ expressionAttributeValues: {
39456
+ ...expressionAttributeValues,
39457
+ ":skPrefix": `${sortField}#`
39458
+ }
39459
+ };
39334
39460
  }
39335
- return tableName;
39336
- }
39337
- function removeShadowKeys(record) {
39338
- const { __shadowKeys, ...rest } = record;
39339
- return rest;
39340
- }
39341
- function extractCleanRecord(item) {
39342
- const data = item.data || item;
39343
- return removeShadowKeys(data);
39344
- }
39345
- async function executeDynamoDBOperation(operation2, operationName) {
39346
- try {
39347
- return await operation2();
39348
- } catch (error2) {
39349
- if (error2 instanceof Error && error2.name === "AccessDeniedException") {
39350
- logger2.error("DynamoDB access denied", {
39351
- errorName: error2.name,
39352
- errorMessage: error2.message,
39353
- operation: operationName,
39354
- tableName: process.env.TABLE_NAME,
39355
- region: process.env.AWS_REGION || process.env.REGION
39356
- });
39357
- throw new Error(`Insufficient permissions to access DynamoDB: ${operationName}`);
39461
+ if (secondFilter) {
39462
+ const first = rangeBounds(sortField, optimizableFilter);
39463
+ const second = rangeBounds(sortField, secondFilter);
39464
+ const low = first.low ?? second.low;
39465
+ const high = first.high ?? second.high;
39466
+ if (low !== void 0 && high !== void 0) {
39467
+ return rangeCondition(expressionAttributeValues, low, high);
39358
39468
  }
39359
- throw error2;
39360
- }
39361
- }
39362
- var logger2, dbClient;
39363
- var init_dynamodb3 = __esm({
39364
- "src/server/utils/dynamodb.ts"() {
39365
- "use strict";
39366
- init_shared();
39367
- logger2 = createLogger({ service: "records-lambda" });
39368
- dbClient = null;
39369
- __name(getDBClient, "getDBClient");
39370
- __name(getTableName, "getTableName");
39371
- __name(removeShadowKeys, "removeShadowKeys");
39372
- __name(extractCleanRecord, "extractCleanRecord");
39373
- __name(executeDynamoDBOperation, "executeDynamoDBOperation");
39374
- }
39375
- });
39376
-
39377
- // src/server/utils/batchGet.ts
39378
- function sleep2(ms) {
39379
- return new Promise((resolve) => setTimeout(resolve, ms));
39380
- }
39381
- async function batchGetAll(keys, { consistentRead, costTracker, requestId, baseDelayMs = 50 }) {
39382
- const unique = Array.from(new Map(keys.map((k5) => [`${k5.PK}\0${k5.SK}`, k5])).values());
39383
- if (unique.length === 0) {
39384
- return [];
39385
39469
  }
39386
- const dbClient2 = getDBClient();
39387
- const tableName = getTableName();
39388
- const records = [];
39389
- for (let i5 = 0; i5 < unique.length; i5 += BATCH_GET_MAX_KEYS) {
39390
- let pending = unique.slice(i5, i5 + BATCH_GET_MAX_KEYS);
39391
- for (let attempt = 0; pending.length > 0; attempt++) {
39392
- if (attempt > BATCH_GET_MAX_RETRIES) {
39393
- logger3.error("BatchGetItem \u306E UnprocessedKeys \u304C\u89E3\u6D88\u3057\u306A\u304B\u3063\u305F", {
39394
- requestId,
39395
- unprocessed: pending.length,
39396
- attempts: attempt
39397
- });
39398
- throw new AppError(
39399
- "INTERNAL_ERROR" /* INTERNAL_ERROR */,
39400
- "BatchGetItem still has unprocessed keys after retries",
39401
- 503,
39402
- { unprocessed: pending.length }
39403
- );
39404
- }
39405
- if (attempt > 0) {
39406
- await sleep2(baseDelayMs * 2 ** (attempt - 1) * (0.5 + Math.random() / 2));
39407
- }
39408
- const keysToGet = pending;
39409
- const result = await executeDynamoDBOperation(
39410
- () => dbClient2.send(
39411
- new import_lib_dynamodb2.BatchGetCommand({
39412
- RequestItems: {
39413
- [tableName]: {
39414
- Keys: keysToGet,
39415
- ConsistentRead: consistentRead
39416
- }
39417
- },
39418
- ReturnConsumedCapacity: "TOTAL"
39419
- })
39420
- ),
39421
- "BatchGetItem"
39470
+ const { operator, type } = optimizableFilter.parsed;
39471
+ const value = optimizableFilter.value;
39472
+ const { encoded, exact } = encodeValueForShadowSK(value, type, operator);
39473
+ const skValue = `${sortField}#${encoded}`;
39474
+ const afterValue = `${skValue}#id#~`;
39475
+ const beforeValue = `${skValue}#id#`;
39476
+ switch (operator) {
39477
+ case "$eq":
39478
+ return {
39479
+ keyConditionExpression: "PK = :pk AND begins_with(SK, :skValue)",
39480
+ expressionAttributeValues: {
39481
+ ...expressionAttributeValues,
39482
+ ":skValue": beforeValue
39483
+ }
39484
+ };
39485
+ // 範囲検索は SK BETWEEN の 1 条件にする。
39486
+ // - DynamoDB はソートキーに 1 つの条件しか許さない(begins_with と比較を並べると ValidationException)
39487
+ // - 上限・下限を sortField の範囲に閉じないと、他の項目のシャドー(や本体 id#…)まで読む
39488
+ // BETWEEN は両端を含むが、端の値(`…#id#`、`…#id#~`、`{sortField}$`)と一致する SK は実在しない
39489
+ case "$gt":
39490
+ return rangeCondition(
39491
+ expressionAttributeValues,
39492
+ exact ? afterValue : beforeValue,
39493
+ fieldUpperBound(sortField)
39422
39494
  );
39423
- if (costTracker) {
39424
- const capacity = result.ConsumedCapacity;
39425
- if (Array.isArray(capacity)) {
39426
- capacity.forEach((c5) => costTracker.add(c5));
39427
- } else {
39428
- costTracker.add(capacity);
39495
+ case "$gte":
39496
+ return rangeCondition(expressionAttributeValues, beforeValue, fieldUpperBound(sortField));
39497
+ case "$lt":
39498
+ return rangeCondition(
39499
+ expressionAttributeValues,
39500
+ `${sortField}#`,
39501
+ exact ? beforeValue : afterValue
39502
+ );
39503
+ case "$lte":
39504
+ return rangeCondition(expressionAttributeValues, `${sortField}#`, afterValue);
39505
+ case "$starts":
39506
+ return {
39507
+ keyConditionExpression: "PK = :pk AND begins_with(SK, :skValue)",
39508
+ expressionAttributeValues: {
39509
+ ...expressionAttributeValues,
39510
+ ":skValue": skValue
39429
39511
  }
39430
- }
39431
- records.push(...result.Responses?.[tableName] ?? []);
39432
- pending = result.UnprocessedKeys?.[tableName]?.Keys ?? [];
39433
- }
39512
+ };
39513
+ default:
39514
+ return {
39515
+ keyConditionExpression: "PK = :pk AND begins_with(SK, :skPrefix)",
39516
+ expressionAttributeValues: {
39517
+ ...expressionAttributeValues,
39518
+ ":skPrefix": `${sortField}#`
39519
+ }
39520
+ };
39434
39521
  }
39435
- return records;
39436
39522
  }
39437
- var import_lib_dynamodb2, logger3, BATCH_GET_MAX_KEYS, BATCH_GET_MAX_RETRIES;
39438
- var init_batchGet = __esm({
39439
- "src/server/utils/batchGet.ts"() {
39440
- "use strict";
39441
- import_lib_dynamodb2 = __toESM(require_dist_cjs22(), 1);
39442
- init_shared();
39443
- init_dynamodb3();
39444
- logger3 = createLogger({
39445
- service: "batch-get",
39446
- level: process.env.LOG_LEVEL || "info"
39447
- });
39448
- BATCH_GET_MAX_KEYS = 100;
39449
- BATCH_GET_MAX_RETRIES = 8;
39450
- __name(sleep2, "sleep");
39451
- __name(batchGetAll, "batchGetAll");
39452
- }
39453
- });
39454
-
39455
- // src/server/utils/bulkOperations.ts
39456
- function logLargeBatchWarning(operation2, recordCount, requestId, resource) {
39457
- if (recordCount > LARGE_BATCH_WARNING_THRESHOLD) {
39458
- logger4.warn(`Large batch ${operation2} operation detected`, {
39459
- requestId,
39460
- resource,
39461
- recordCount,
39462
- warningThreshold: LARGE_BATCH_WARNING_THRESHOLD,
39463
- estimatedTimeoutRisk: "high",
39464
- recommendation: "Consider splitting the batch into smaller requests to avoid Lambda timeout (15 min limit)"
39465
- });
39523
+ function rangeBounds(sortField, filter) {
39524
+ const { operator, type } = filter.parsed;
39525
+ const { encoded, exact } = encodeValueForShadowSK(filter.value, type, operator);
39526
+ const skValue = `${sortField}#${encoded}`;
39527
+ const afterValue = `${skValue}#id#~`;
39528
+ const beforeValue = `${skValue}#id#`;
39529
+ switch (operator) {
39530
+ case "$gt":
39531
+ return { low: exact ? afterValue : beforeValue };
39532
+ case "$gte":
39533
+ return { low: beforeValue };
39534
+ case "$lt":
39535
+ return { high: exact ? beforeValue : afterValue };
39536
+ case "$lte":
39537
+ return { high: afterValue };
39538
+ default:
39539
+ return {};
39466
39540
  }
39467
39541
  }
39468
- function calculateTimeoutRisk(startTime) {
39469
- const elapsedMs = Date.now() - startTime;
39470
- const remainingMs = LAMBDA_TIMEOUT_MS - elapsedMs;
39471
- const utilizationPercent = Math.round(elapsedMs / LAMBDA_TIMEOUT_MS * 100);
39472
- const risk = remainingMs < LAMBDA_TIMEOUT_MS * TIMEOUT_RISK_THRESHOLD ? "high" : "low";
39473
- return {
39474
- elapsedMs,
39475
- remainingMs,
39476
- risk,
39477
- utilizationPercent
39478
- };
39479
- }
39480
- function logPreparationTimeoutRisk(requestId, resource, totalRecords, chunkCount, riskInfo) {
39481
- logger4.info("Records prepared for chunk execution", {
39482
- requestId,
39483
- resource,
39484
- totalRecords,
39485
- chunkCount,
39486
- preparationTimeMs: riskInfo.elapsedMs,
39487
- remainingTimeMs: riskInfo.remainingMs,
39488
- timeoutRisk: riskInfo.risk
39489
- });
39490
- if (riskInfo.risk === "high") {
39491
- logger4.warn("High timeout risk detected during preparation phase", {
39492
- requestId,
39493
- resource,
39494
- preparationElapsedMs: riskInfo.elapsedMs,
39495
- remainingTimeMs: riskInfo.remainingMs,
39496
- lambdaTimeoutMs: LAMBDA_TIMEOUT_MS,
39497
- recommendation: "Consider reducing batch size or optimizing preparation logic"
39498
- });
39499
- }
39542
+ function findComplementaryBound(primary, parsedFilters) {
39543
+ const op2 = primary.parsed.operator;
39544
+ const wanted = LOWER_BOUND_OPERATORS.has(op2) ? UPPER_BOUND_OPERATORS : UPPER_BOUND_OPERATORS.has(op2) ? LOWER_BOUND_OPERATORS : void 0;
39545
+ if (!wanted) return void 0;
39546
+ return parsedFilters.find(
39547
+ (f5) => f5 !== primary && f5.parsed.field === primary.parsed.field && wanted.has(f5.parsed.operator)
39548
+ );
39500
39549
  }
39501
- function logBulkOperationComplete(operation2, requestId, resource, requested, succeeded, failed, riskInfo, additionalInfo) {
39502
- const totalElapsedSeconds = Math.round(riskInfo.elapsedMs / 1e3);
39503
- logger4.info(`${operation2} completed`, {
39504
- requestId,
39505
- resource,
39506
- requested,
39507
- succeeded,
39508
- totalFailed: failed,
39509
- totalExecutionTimeMs: riskInfo.elapsedMs,
39510
- totalExecutionTimeSeconds: totalElapsedSeconds,
39511
- lambdaTimeoutMs: LAMBDA_TIMEOUT_MS,
39512
- timeoutUtilization: `${riskInfo.utilizationPercent}%`,
39513
- ...additionalInfo
39514
- });
39550
+ function fieldUpperBound(sortField) {
39551
+ return `${sortField}$`;
39515
39552
  }
39516
- function logPartialFailure(operation2, requestId, resource, requested, succeeded, failed, errorCodes, additionalInfo) {
39517
- const failureRate = Math.round(failed / requested * 100);
39518
- logger4.warn(`Partial failure in ${operation2} operation`, {
39519
- requestId,
39520
- resource,
39521
- totalRequested: requested,
39522
- successCount: succeeded,
39523
- failedCount: failed,
39524
- failureRate: `${failureRate}%`,
39525
- errorCodes: [...new Set(errorCodes)],
39526
- ...additionalInfo
39527
- });
39553
+ function rangeCondition(base, low, high) {
39554
+ return {
39555
+ keyConditionExpression: "PK = :pk AND SK BETWEEN :skLow AND :skHigh",
39556
+ expressionAttributeValues: { ...base, ":skLow": low, ":skHigh": high }
39557
+ };
39528
39558
  }
39529
- var logger4;
39530
- var init_bulkOperations = __esm({
39531
- "src/server/utils/bulkOperations.ts"() {
39532
- "use strict";
39533
- init_shared();
39534
- logger4 = createLogger({ service: "records-lambda" });
39535
- __name(logLargeBatchWarning, "logLargeBatchWarning");
39536
- __name(calculateTimeoutRisk, "calculateTimeoutRisk");
39537
- __name(logPreparationTimeoutRisk, "logPreparationTimeoutRisk");
39538
- __name(logBulkOperationComplete, "logBulkOperationComplete");
39539
- __name(logPartialFailure, "logPartialFailure");
39540
- }
39541
- });
39542
-
39543
- // src/server/utils/chunking.ts
39544
- function calculateChunks(records, getItemCount) {
39545
- const chunks = [];
39546
- const itemCounts = [];
39547
- let currentChunk = [];
39548
- let currentItemCount = 0;
39549
- for (const record of records) {
39550
- const itemCount = getItemCount(record);
39551
- if (itemCount > DYNAMODB_TRANSACT_WRITE_MAX_ITEMS) {
39552
- const errorMsg = `Single record exceeds ${DYNAMODB_TRANSACT_WRITE_MAX_ITEMS} items limit: ${itemCount} items`;
39553
- logger5.error("Chunk validation failed", {
39554
- itemCount,
39555
- limit: DYNAMODB_TRANSACT_WRITE_MAX_ITEMS
39556
- });
39557
- throw new Error(errorMsg);
39558
- }
39559
- if (currentItemCount + itemCount > DYNAMODB_TRANSACT_WRITE_MAX_ITEMS) {
39560
- if (currentChunk.length > 0) {
39561
- chunks.push(currentChunk);
39562
- itemCounts.push(currentItemCount);
39563
- }
39564
- currentChunk = [record];
39565
- currentItemCount = itemCount;
39566
- } else {
39567
- currentChunk.push(record);
39568
- currentItemCount += itemCount;
39569
- }
39570
- }
39571
- if (currentChunk.length > 0) {
39572
- chunks.push(currentChunk);
39573
- itemCounts.push(currentItemCount);
39559
+ function encodeValueForShadowSK(value, type, operator) {
39560
+ const config = getShadowConfig();
39561
+ if (type === "number" || typeof value === "number") {
39562
+ const num = Number(value);
39563
+ return { encoded: formatFieldValue2("number", num, config), exact: false };
39574
39564
  }
39575
- logger5.info("Chunk calculation completed", {
39576
- totalRecords: records.length,
39577
- chunkCount: chunks.length,
39578
- itemCounts,
39579
- minItemsPerChunk: itemCounts.length > 0 ? Math.min(...itemCounts) : 0,
39580
- maxItemsPerChunk: itemCounts.length > 0 ? Math.max(...itemCounts) : 0,
39581
- avgItemsPerChunk: itemCounts.length > 0 ? Math.round(itemCounts.reduce((sum, count) => sum + count, 0) / itemCounts.length) : 0
39582
- });
39583
- return { chunks, itemCounts };
39584
- }
39585
- async function executeChunks(chunks, executeChunk, getRecordId) {
39586
- const successRecords = [];
39587
- const failedIds = [];
39588
- const errors = [];
39589
- const totalRecords = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
39590
- const executionStartTime = Date.now();
39591
- logger5.info("Starting chunk execution", {
39592
- totalChunks: chunks.length,
39593
- totalRecords
39594
- });
39595
- for (let i5 = 0; i5 < chunks.length; i5++) {
39596
- const chunk = chunks[i5];
39597
- const chunkStartTime = Date.now();
39598
- try {
39599
- logger5.debug(`Executing chunk ${i5 + 1}/${chunks.length}`, {
39600
- chunkIndex: i5,
39601
- recordCount: chunk.length
39602
- });
39603
- const successfulRecords = await executeChunk(chunk);
39604
- successRecords.push(...successfulRecords);
39605
- const chunkDuration = Date.now() - chunkStartTime;
39606
- logger5.info(`Chunk ${i5 + 1}/${chunks.length} succeeded`, {
39607
- chunkIndex: i5,
39608
- recordCount: chunk.length,
39609
- durationMs: chunkDuration
39610
- });
39611
- } catch (error2) {
39612
- const chunkDuration = Date.now() - chunkStartTime;
39613
- const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
39614
- const errorCode = getErrorCode(error2);
39615
- logger5.error(`Chunk ${i5 + 1}/${chunks.length} failed`, {
39616
- chunkIndex: i5,
39617
- recordCount: chunk.length,
39618
- durationMs: chunkDuration,
39619
- error: errorMessage,
39620
- errorCode
39621
- });
39622
- for (const record of chunk) {
39623
- const recordId = getRecordId(record);
39624
- failedIds.push(recordId);
39625
- errors.push({
39626
- id: recordId,
39627
- code: errorCode,
39628
- message: errorMessage
39629
- });
39630
- }
39631
- }
39565
+ if (type === "boolean" || typeof value === "boolean") {
39566
+ const bool = typeof value === "boolean" ? value : String(value).toLowerCase() === "true";
39567
+ return { encoded: formatFieldValue2("boolean", bool, config), exact: true };
39632
39568
  }
39633
- const totalExecutionTime = Date.now() - executionStartTime;
39634
- logger5.info("Chunk execution completed", {
39635
- totalChunks: chunks.length,
39636
- totalRecords,
39637
- successCount: successRecords.length,
39638
- failedCount: failedIds.length,
39639
- totalExecutionTimeMs: totalExecutionTime,
39640
- avgTimePerChunkMs: chunks.length > 0 ? Math.round(totalExecutionTime / chunks.length) : 0
39641
- });
39642
- if (failedIds.length > 0) {
39643
- logger5.warn("Partial failure detected in chunk execution", {
39644
- totalRecords,
39645
- successCount: successRecords.length,
39646
- failedCount: failedIds.length,
39647
- failureRate: `${Math.round(failedIds.length / totalRecords * 100)}%`,
39648
- failedIds: failedIds.slice(0, 10),
39649
- // 最初の10件のみログ出力
39650
- errorSummary: errors.slice(0, 5).map((e5) => ({
39651
- id: e5.id,
39652
- code: e5.code,
39653
- message: e5.message.substring(0, 100)
39654
- // メッセージを100文字に制限
39655
- }))
39656
- });
39569
+ const str = String(value);
39570
+ if (operator !== "$starts" && (type === "date" || inferFieldType(str) === "datetime")) {
39571
+ return { encoded: formatFieldValue2("datetime", str, config), exact: true };
39657
39572
  }
39573
+ const encoded = formatFieldValue2("string", str, config);
39574
+ const bytes = new TextEncoder().encode(str).length;
39658
39575
  return {
39659
- successRecords,
39660
- failedIds,
39661
- errors
39576
+ encoded,
39577
+ exact: encoded === escapeString2(str) && bytes < config.stringMaxBytes - 3
39662
39578
  };
39663
39579
  }
39664
- function getErrorCode(error2) {
39665
- if (error2 && typeof error2 === "object") {
39666
- if ("name" in error2 && typeof error2.name === "string") {
39667
- return error2.name;
39668
- }
39669
- if ("code" in error2 && typeof error2.code === "string") {
39670
- return error2.code;
39671
- }
39672
- }
39673
- return "TRANSACTION_FAILED";
39674
- }
39675
- var logger5;
39676
- var init_chunking = __esm({
39677
- "src/server/utils/chunking.ts"() {
39678
- "use strict";
39679
- init_shared();
39680
- logger5 = createLogger({ service: "records-lambda" });
39681
- __name(calculateChunks, "calculateChunks");
39682
- __name(executeChunks, "executeChunks");
39683
- __name(getErrorCode, "getErrorCode");
39684
- }
39685
- });
39686
-
39687
- // src/server/utils/cost-tracker.ts
39688
- var CostTracker;
39689
- var init_cost_tracker = __esm({
39690
- "src/server/utils/cost-tracker.ts"() {
39580
+ var KEY_CONDITION_OPERATORS, LOWER_BOUND_OPERATORS, UPPER_BOUND_OPERATORS;
39581
+ var init_keyCondition = __esm({
39582
+ "src/server/operations/find/keyCondition.ts"() {
39691
39583
  "use strict";
39692
- CostTracker = class {
39693
- static {
39694
- __name(this, "CostTracker");
39695
- }
39696
- totalRCU = 0;
39697
- totalWCU = 0;
39698
- operationCount = 0;
39699
- /**
39700
- * ConsumedCapacityを追加
39701
- *
39702
- * DynamoDB操作のConsumedCapacityを累積します。
39703
- * undefinedが渡された場合は何もしません(エラーにしない)。
39704
- *
39705
- * AWS SDKのConsumedCapacityは以下のフィールドを持ちます:
39706
- * - CapacityUnits: 総キャパシティユニット(RCU + WCU)
39707
- * - ReadCapacityUnits: 読み取りキャパシティユニット
39708
- * - WriteCapacityUnits: 書き込みキャパシティユニット
39709
- *
39710
- * このメソッドはReadCapacityUnitsとWriteCapacityUnitsを優先的に使用し、
39711
- * 存在しない場合はCapacityUnitsを読み取りとして扱います。
39712
- *
39713
- * @param consumedCapacity - DynamoDB操作のConsumedCapacity
39714
- */
39715
- add(consumedCapacity) {
39716
- if (!consumedCapacity) {
39717
- return;
39718
- }
39719
- const rcu = consumedCapacity.ReadCapacityUnits ?? 0;
39720
- const wcu = consumedCapacity.WriteCapacityUnits ?? 0;
39721
- this.totalRCU += rcu;
39722
- this.totalWCU += wcu;
39723
- this.operationCount += 1;
39724
- }
39725
- /**
39726
- * 集計結果を取得
39727
- *
39728
- * これまでに追加されたConsumedCapacityの集計結果を返します。
39729
- *
39730
- * @returns 集計されたコスト情報
39731
- */
39732
- getAggregated() {
39733
- return {
39734
- totalRCU: this.totalRCU,
39735
- totalWCU: this.totalWCU,
39736
- operationCount: this.operationCount
39737
- };
39738
- }
39739
- /**
39740
- * リセット
39741
- *
39742
- * 累積されたコスト情報をクリアします。
39743
- */
39744
- reset() {
39745
- this.totalRCU = 0;
39746
- this.totalWCU = 0;
39747
- this.operationCount = 0;
39748
- }
39749
- };
39584
+ init_shadow();
39585
+ KEY_CONDITION_OPERATORS = /* @__PURE__ */ new Set(["$eq", "$gt", "$gte", "$lt", "$lte", "$starts"]);
39586
+ __name(buildKeyCondition, "buildKeyCondition");
39587
+ LOWER_BOUND_OPERATORS = /* @__PURE__ */ new Set(["$gt", "$gte"]);
39588
+ UPPER_BOUND_OPERATORS = /* @__PURE__ */ new Set(["$lt", "$lte"]);
39589
+ __name(rangeBounds, "rangeBounds");
39590
+ __name(findComplementaryBound, "findComplementaryBound");
39591
+ __name(fieldUpperBound, "fieldUpperBound");
39592
+ __name(rangeCondition, "rangeCondition");
39593
+ __name(encodeValueForShadowSK, "encodeValueForShadowSK");
39750
39594
  }
39751
39595
  });
39752
39596
 
@@ -39757,18 +39601,14 @@ function parseFilterField(fieldKey) {
39757
39601
  return { field: parts[0], operator: "$eq", type: "string" };
39758
39602
  }
39759
39603
  if (parts.length === 2) {
39604
+ assertSupportedOperator(parts[1]);
39760
39605
  const operator = parts[1];
39761
- if (!isValidOperator(operator)) {
39762
- throw new Error(`Invalid filter operator: ${parts[1]}`);
39763
- }
39764
39606
  return { field: parts[0], operator, type: "string" };
39765
39607
  }
39766
39608
  if (parts.length === 3) {
39609
+ assertSupportedOperator(parts[1]);
39767
39610
  const operator = parts[1];
39768
39611
  const type = parts[2];
39769
- if (!isValidOperator(operator)) {
39770
- throw new Error(`Invalid filter operator: ${parts[1]}`);
39771
- }
39772
39612
  if (!isValidType(type)) {
39773
39613
  throw new Error(`Invalid filter type: ${parts[2]}`);
39774
39614
  }
@@ -39789,11 +39629,18 @@ function isValidOperator(operator) {
39789
39629
  "$starts",
39790
39630
  "$ends",
39791
39631
  "$contains",
39792
- "$regex",
39793
39632
  "$exists",
39794
39633
  "$near"
39795
39634
  ].includes(operator);
39796
39635
  }
39636
+ function assertSupportedOperator(operator) {
39637
+ if (operator === "$regex") {
39638
+ throw new Error("Invalid filter operator: $regex is not supported (use $contains or $starts)");
39639
+ }
39640
+ if (!isValidOperator(operator)) {
39641
+ throw new Error(`Invalid filter operator: ${operator}`);
39642
+ }
39643
+ }
39797
39644
  function isValidType(type) {
39798
39645
  return ["string", "number", "date", "boolean"].includes(type);
39799
39646
  }
@@ -39802,6 +39649,7 @@ var init_filter = __esm({
39802
39649
  "use strict";
39803
39650
  __name(parseFilterField, "parseFilterField");
39804
39651
  __name(isValidOperator, "isValidOperator");
39652
+ __name(assertSupportedOperator, "assertSupportedOperator");
39805
39653
  __name(isValidType, "isValidType");
39806
39654
  }
39807
39655
  });
@@ -39874,7 +39722,7 @@ function parseFilters(filter) {
39874
39722
  parsedFilters.push({ parsed: withInferredType(parsed, fieldKey, value), value });
39875
39723
  }
39876
39724
  } catch (error2) {
39877
- logger6.error("Invalid filter field syntax", {
39725
+ logger3.error("Invalid filter field syntax", {
39878
39726
  fieldKey,
39879
39727
  error: error2 instanceof Error ? error2.message : String(error2)
39880
39728
  });
@@ -39917,8 +39765,6 @@ function matchesAllFilters(record, parsedFilters) {
39917
39765
  return typeof recordValue === "string" && typeof filterValue === "string" && recordValue.endsWith(filterValue);
39918
39766
  case "$contains":
39919
39767
  return typeof recordValue === "string" && typeof filterValue === "string" && recordValue.includes(filterValue);
39920
- case "$regex":
39921
- return typeof recordValue === "string" && typeof filterValue === "string" && recordValue.includes(filterValue);
39922
39768
  case "$exists":
39923
39769
  return filterValue ? recordValue !== void 0 && recordValue !== null : recordValue === void 0 || recordValue === null;
39924
39770
  default:
@@ -39943,7 +39789,7 @@ function detectNearQuery(filter) {
39943
39789
  }
39944
39790
  return null;
39945
39791
  }
39946
- var logger6;
39792
+ var logger3;
39947
39793
  var init_utils6 = __esm({
39948
39794
  "src/server/operations/find/utils.ts"() {
39949
39795
  "use strict";
@@ -39952,7 +39798,7 @@ var init_utils6 = __esm({
39952
39798
  init_shadow();
39953
39799
  init_filter();
39954
39800
  init_validation2();
39955
- logger6 = createLogger({
39801
+ logger3 = createLogger({
39956
39802
  service: "find-utils",
39957
39803
  level: process.env.LOG_LEVEL || "info"
39958
39804
  });
@@ -39997,68 +39843,81 @@ var init_idFilter = __esm({
39997
39843
  }
39998
39844
  });
39999
39845
 
40000
- // src/server/utils/revision.ts
40001
- function revisionOf(item) {
40002
- const rev = item[REVISION_ATTRIBUTE];
40003
- return typeof rev === "number" ? rev : void 0;
40004
- }
40005
- function nextRevision(current) {
40006
- return (current ?? 0) + 1;
40007
- }
40008
- function notExistsCondition() {
40009
- return { ConditionExpression: "attribute_not_exists(PK)" };
40010
- }
40011
- function unchangedCondition(revision) {
40012
- const names = { "#rev": REVISION_ATTRIBUTE };
40013
- if (revision === void 0) {
40014
- return {
40015
- ConditionExpression: "attribute_exists(PK) AND attribute_not_exists(#rev)",
40016
- ExpressionAttributeNames: names
40017
- };
40018
- }
40019
- return {
40020
- ConditionExpression: "#rev = :rev",
40021
- ExpressionAttributeNames: names,
40022
- ExpressionAttributeValues: { ":rev": revision }
40023
- };
40024
- }
40025
- function isWriteConflict(error2) {
40026
- if (!error2 || typeof error2 !== "object") return false;
40027
- const { name, CancellationReasons } = error2;
40028
- if (name === "TransactionConflictException") return true;
40029
- if (name !== "TransactionCanceledException" || !Array.isArray(CancellationReasons)) return false;
40030
- const codes = CancellationReasons.map((r5) => r5?.Code).filter((c5) => c5 && c5 !== "None");
40031
- return codes.length > 0 && codes.every((c5) => c5 === "ConditionalCheckFailed" || c5 === "TransactionConflict");
40032
- }
40033
- function sleep3(ms) {
39846
+ // src/server/utils/batchGet.ts
39847
+ function sleep2(ms) {
40034
39848
  return new Promise((resolve) => setTimeout(resolve, ms));
40035
39849
  }
40036
- async function writeWithConflictRetry(initial, write, refresh, baseDelayMs = 20) {
40037
- let records = initial;
40038
- for (let attempt = 0; ; attempt++) {
40039
- try {
40040
- if (records.length > 0) await write(records);
40041
- return records;
40042
- } catch (error2) {
40043
- if (!isWriteConflict(error2) || attempt >= MAX_CONFLICT_RETRIES) throw error2;
40044
- await sleep3(baseDelayMs * 2 ** attempt * (0.5 + Math.random() / 2));
40045
- records = await refresh(records);
39850
+ async function batchGetAll(keys, { consistentRead, costTracker, requestId, baseDelayMs = 50 }) {
39851
+ const unique = Array.from(new Map(keys.map((k5) => [`${k5.PK}\0${k5.SK}`, k5])).values());
39852
+ if (unique.length === 0) {
39853
+ return [];
39854
+ }
39855
+ const dbClient2 = getDBClient();
39856
+ const tableName = getTableName();
39857
+ const records = [];
39858
+ for (let i5 = 0; i5 < unique.length; i5 += BATCH_GET_MAX_KEYS) {
39859
+ let pending = unique.slice(i5, i5 + BATCH_GET_MAX_KEYS);
39860
+ for (let attempt = 0; pending.length > 0; attempt++) {
39861
+ if (attempt > BATCH_GET_MAX_RETRIES) {
39862
+ logger4.error("BatchGetItem \u306E UnprocessedKeys \u304C\u89E3\u6D88\u3057\u306A\u304B\u3063\u305F", {
39863
+ requestId,
39864
+ unprocessed: pending.length,
39865
+ attempts: attempt
39866
+ });
39867
+ throw new AppError(
39868
+ "INTERNAL_ERROR" /* INTERNAL_ERROR */,
39869
+ "BatchGetItem still has unprocessed keys after retries",
39870
+ 503,
39871
+ { unprocessed: pending.length }
39872
+ );
39873
+ }
39874
+ if (attempt > 0) {
39875
+ await sleep2(baseDelayMs * 2 ** (attempt - 1) * (0.5 + Math.random() / 2));
39876
+ }
39877
+ const keysToGet = pending;
39878
+ const result = await executeDynamoDBOperation(
39879
+ () => dbClient2.send(
39880
+ new import_lib_dynamodb2.BatchGetCommand({
39881
+ RequestItems: {
39882
+ [tableName]: {
39883
+ Keys: keysToGet,
39884
+ ConsistentRead: consistentRead
39885
+ }
39886
+ },
39887
+ ReturnConsumedCapacity: "TOTAL"
39888
+ })
39889
+ ),
39890
+ "BatchGetItem"
39891
+ );
39892
+ if (costTracker) {
39893
+ const capacity = result.ConsumedCapacity;
39894
+ if (Array.isArray(capacity)) {
39895
+ capacity.forEach((c5) => costTracker.add(c5));
39896
+ } else {
39897
+ costTracker.add(capacity);
39898
+ }
39899
+ }
39900
+ records.push(...result.Responses?.[tableName] ?? []);
39901
+ pending = result.UnprocessedKeys?.[tableName]?.Keys ?? [];
40046
39902
  }
40047
39903
  }
39904
+ return records;
40048
39905
  }
40049
- var REVISION_ATTRIBUTE, MAX_CONFLICT_RETRIES;
40050
- var init_revision = __esm({
40051
- "src/server/utils/revision.ts"() {
39906
+ var import_lib_dynamodb2, logger4, BATCH_GET_MAX_KEYS, BATCH_GET_MAX_RETRIES;
39907
+ var init_batchGet = __esm({
39908
+ "src/server/utils/batchGet.ts"() {
40052
39909
  "use strict";
40053
- REVISION_ATTRIBUTE = "__rev";
40054
- MAX_CONFLICT_RETRIES = 5;
40055
- __name(revisionOf, "revisionOf");
40056
- __name(nextRevision, "nextRevision");
40057
- __name(notExistsCondition, "notExistsCondition");
40058
- __name(unchangedCondition, "unchangedCondition");
40059
- __name(isWriteConflict, "isWriteConflict");
40060
- __name(sleep3, "sleep");
40061
- __name(writeWithConflictRetry, "writeWithConflictRetry");
39910
+ import_lib_dynamodb2 = __toESM(require_dist_cjs22(), 1);
39911
+ init_shared();
39912
+ init_dynamodb3();
39913
+ logger4 = createLogger({
39914
+ service: "batch-get",
39915
+ level: process.env.LOG_LEVEL || "info"
39916
+ });
39917
+ BATCH_GET_MAX_KEYS = 100;
39918
+ BATCH_GET_MAX_RETRIES = 8;
39919
+ __name(sleep2, "sleep");
39920
+ __name(batchGetAll, "batchGetAll");
40062
39921
  }
40063
39922
  });
40064
39923
 
@@ -40105,80 +39964,68 @@ var init_converter = __esm({
40105
39964
  });
40106
39965
 
40107
39966
  // src/server/query/nearSearch.ts
40108
- function coversMaxDistance(precision, maxDistance) {
40109
- const coverage = GEOHASH_COVERAGE[precision];
40110
- if (!coverage) {
40111
- return false;
40112
- }
40113
- return coverage >= maxDistance;
39967
+ function cellSizeMeters(precision, cosLat) {
39968
+ const latBits = Math.floor(5 * precision / 2);
39969
+ const lonBits = Math.ceil(5 * precision / 2);
39970
+ const heightDeg = 180 / 2 ** latBits;
39971
+ return {
39972
+ height: heightDeg * METERS_PER_DEGREE,
39973
+ width: 360 / 2 ** lonBits * METERS_PER_DEGREE * cosLat,
39974
+ heightDeg
39975
+ };
39976
+ }
39977
+ function guaranteedRadius(precision, latitude) {
39978
+ const { heightDeg } = cellSizeMeters(precision, 1);
39979
+ const worstLatitude = Math.min(89.9, Math.abs(latitude) + 2 * heightDeg);
39980
+ const { height, width } = cellSizeMeters(precision, Math.cos(worstLatitude * Math.PI / 180));
39981
+ return Math.min(height, width);
39982
+ }
39983
+ function shadowPositionError(shadowPrecision) {
39984
+ const { height, width } = cellSizeMeters(shadowPrecision, 1);
39985
+ return Math.hypot(height, width) / 2;
40114
39986
  }
40115
- async function executeNearSearch(nearQuery, fieldName, limit, searchFunction, config = DEFAULT_GEOHASH_CONFIG) {
39987
+ function kthOf(sortedAscending, k5) {
39988
+ return sortedAscending.length >= k5 ? sortedAscending[k5 - 1] : void 0;
39989
+ }
39990
+ async function executeNearSearch(nearQuery, fieldName, limit, searchShadows, readBodies, config = DEFAULT_GEOHASH_CONFIG) {
40116
39991
  const { latitude, longitude } = extractCoordinatesFromNearQuery(nearQuery);
40117
39992
  const maxDistance = extractMaxDistanceFromNearQuery(nearQuery);
40118
39993
  const minDistance = extractMinDistanceFromNearQuery(nearQuery);
39994
+ const epsilon = shadowPositionError(config.shadowPrecision);
40119
39995
  let precision = config.searchPrecision;
40120
- let allCandidates = [];
40121
39996
  let iterations = 0;
40122
- while (allCandidates.length < limit * config.candidateMultiplier && precision >= config.minPrecision && iterations < config.maxIterations) {
39997
+ let exhaustive = false;
39998
+ let approx = /* @__PURE__ */ new Map();
39999
+ let kth;
40000
+ while (precision >= config.minPrecision && iterations < config.maxIterations) {
40123
40001
  iterations++;
40124
- const currentGeoHash = encodeGeoHash(latitude, longitude, precision);
40125
- const neighborGeoHashes = getNeighborGeoHashes(currentGeoHash);
40126
- const searchPromises = neighborGeoHashes.map((geohash) => searchFunction(geohash));
40127
- const results = await Promise.all(searchPromises);
40128
- const candidates = results.flat();
40129
- for (const candidate of candidates) {
40130
- if (!allCandidates.some((c5) => c5.id === candidate.id)) {
40131
- allCandidates.push(candidate);
40132
- }
40133
- }
40134
- if (maxDistance !== void 0) {
40135
- let candidatesWithinDistance = 0;
40136
- for (const candidate of allCandidates) {
40137
- const location = candidate[fieldName];
40138
- if (location && typeof location.latitude === "number" && typeof location.longitude === "number") {
40139
- const distance = calculateDistance(
40140
- latitude,
40141
- longitude,
40142
- location.latitude,
40143
- location.longitude
40144
- );
40145
- if (distance <= maxDistance) {
40146
- candidatesWithinDistance++;
40147
- }
40148
- }
40149
- }
40150
- if (candidatesWithinDistance >= limit) {
40151
- console.log("[nearSearch] Early termination: found enough candidates within maxDistance", {
40152
- candidatesWithinDistance,
40153
- limit,
40154
- maxDistance,
40155
- precision,
40156
- iterations
40157
- });
40158
- break;
40159
- }
40160
- if (coversMaxDistance(precision, maxDistance)) {
40161
- console.log("[nearSearch] Early termination: current precision covers maxDistance", {
40162
- precision,
40163
- maxDistance,
40164
- coverage: GEOHASH_COVERAGE[precision],
40165
- candidatesWithinDistance,
40166
- iterations
40167
- });
40168
- break;
40169
- }
40002
+ const radius = guaranteedRadius(precision, latitude);
40003
+ const neighbors = getNeighborGeoHashes(encodeGeoHash(latitude, longitude, precision));
40004
+ const hits = (await Promise.all(neighbors.map((prefix) => searchShadows(prefix)))).flat();
40005
+ approx = /* @__PURE__ */ new Map();
40006
+ for (const hit of hits) {
40007
+ const center = decodeGeoHash(hit.geohash);
40008
+ approx.set(hit.id, calculateDistance(latitude, longitude, center.latitude, center.longitude));
40009
+ }
40010
+ const sure = [...approx.values()].filter(
40011
+ (d5) => (minDistance === void 0 || d5 - epsilon >= minDistance) && (maxDistance === void 0 || d5 + epsilon <= maxDistance)
40012
+ ).sort((a5, b5) => a5 - b5);
40013
+ kth = kthOf(sure, limit);
40014
+ const topKConfirmed = kth !== void 0 && kth + epsilon <= radius;
40015
+ const circleCovered = maxDistance !== void 0 && maxDistance + epsilon <= radius;
40016
+ if (topKConfirmed || circleCovered) {
40017
+ exhaustive = true;
40018
+ break;
40170
40019
  }
40171
40020
  precision--;
40172
40021
  }
40173
- const documentsWithDistance = allCandidates.map((doc) => {
40022
+ const cutoff = kth !== void 0 ? kth + 2 * epsilon : void 0;
40023
+ const wanted = [...approx.entries()].filter(
40024
+ ([, d5]) => (cutoff === void 0 || d5 <= cutoff) && (maxDistance === void 0 || d5 <= maxDistance + epsilon) && (minDistance === void 0 || d5 >= minDistance - epsilon)
40025
+ ).map(([id]) => id);
40026
+ const bodies = wanted.length > 0 ? await readBodies(wanted) : [];
40027
+ const documents = bodies.map((doc) => {
40174
40028
  const location = doc[fieldName];
40175
- if (!location) {
40176
- console.log("[nearSearch] Location field not found:", {
40177
- fieldName,
40178
- docKeys: Object.keys(doc),
40179
- doc: JSON.stringify(doc).substring(0, 200)
40180
- });
40181
- }
40182
40029
  if (!location || typeof location.latitude !== "number" || typeof location.longitude !== "number") {
40183
40030
  return null;
40184
40031
  }
@@ -40188,19 +40035,8 @@ async function executeNearSearch(nearQuery, fieldName, limit, searchFunction, co
40188
40035
  location.latitude,
40189
40036
  location.longitude
40190
40037
  );
40191
- console.log("[nearSearch] Distance calculated:", {
40192
- docId: doc.id,
40193
- distance,
40194
- maxDistance,
40195
- minDistance,
40196
- willBeFiltered: maxDistance !== void 0 && distance > maxDistance || minDistance !== void 0 && distance < minDistance
40197
- });
40198
- if (maxDistance !== void 0 && distance > maxDistance) {
40199
- return null;
40200
- }
40201
- if (minDistance !== void 0 && distance < minDistance) {
40202
- return null;
40203
- }
40038
+ if (maxDistance !== void 0 && distance > maxDistance) return null;
40039
+ if (minDistance !== void 0 && distance < minDistance) return null;
40204
40040
  return {
40205
40041
  ...doc,
40206
40042
  __distance: distance,
@@ -40208,36 +40044,26 @@ async function executeNearSearch(nearQuery, fieldName, limit, searchFunction, co
40208
40044
  };
40209
40045
  }).filter((doc) => doc !== null).sort((a5, b5) => (a5.__distance ?? 0) - (b5.__distance ?? 0)).slice(0, limit);
40210
40046
  return {
40211
- documents: documentsWithDistance,
40047
+ documents,
40212
40048
  metadata: {
40213
40049
  iterations,
40214
- candidatesFound: allCandidates.length,
40215
- requestedLimit: limit
40050
+ candidatesFound: approx.size,
40051
+ bodiesRead: wanted.length,
40052
+ requestedLimit: limit,
40053
+ exhaustive
40216
40054
  }
40217
40055
  };
40218
40056
  }
40219
- var GEOHASH_COVERAGE;
40057
+ var METERS_PER_DEGREE;
40220
40058
  var init_nearSearch = __esm({
40221
40059
  "src/server/query/nearSearch.ts"() {
40222
40060
  "use strict";
40223
40061
  init_geohash();
40224
- GEOHASH_COVERAGE = {
40225
- 8: 19 * 3,
40226
- // ±19m × 3 = 約57m
40227
- 7: 76 * 3,
40228
- // ±76m × 3 = 約228m
40229
- 6: 610 * 3,
40230
- // ±610m × 3 = 約1,830m (1.8km)
40231
- 5: 2400 * 3,
40232
- // ±2.4km × 3 = 約7,200m (7.2km)
40233
- 4: 2e4 * 3,
40234
- // ±20km × 3 = 約60,000m (60km)
40235
- 3: 78e3 * 3,
40236
- // ±78km × 3 = 約234,000m (234km)
40237
- 2: 63e4 * 3
40238
- // ±630km × 3 = 約1,890,000m (1,890km)
40239
- };
40240
- __name(coversMaxDistance, "coversMaxDistance");
40062
+ METERS_PER_DEGREE = 111320;
40063
+ __name(cellSizeMeters, "cellSizeMeters");
40064
+ __name(guaranteedRadius, "guaranteedRadius");
40065
+ __name(shadowPositionError, "shadowPositionError");
40066
+ __name(kthOf, "kthOf");
40241
40067
  __name(executeNearSearch, "executeNearSearch");
40242
40068
  }
40243
40069
  });
@@ -40361,12 +40187,12 @@ function getScanWarnThreshold() {
40361
40187
  const value = Number(raw);
40362
40188
  return Number.isInteger(value) && value >= 1 ? value : DEFAULT_SCAN_WARN_THRESHOLD;
40363
40189
  }
40364
- var logger7, SPARSE_SCAN_EVENT, DEFAULT_SCAN_WARN_THRESHOLD, ScanWatcher;
40190
+ var logger5, SPARSE_SCAN_EVENT, DEFAULT_SCAN_WARN_THRESHOLD, ScanWatcher;
40365
40191
  var init_scanWarning = __esm({
40366
40192
  "src/server/utils/scanWarning.ts"() {
40367
40193
  "use strict";
40368
40194
  init_shared();
40369
- logger7 = createLogger({ service: "scan-warning", level: "warn" });
40195
+ logger5 = createLogger({ service: "scan-warning", level: "warn" });
40370
40196
  SPARSE_SCAN_EVENT = "SPARSE_SCAN";
40371
40197
  DEFAULT_SCAN_WARN_THRESHOLD = 5e3;
40372
40198
  __name(getScanWarnThreshold, "getScanWarnThreshold");
@@ -40386,7 +40212,7 @@ var init_scanWarning = __esm({
40386
40212
  this.scanned += count;
40387
40213
  if (!this.warned && this.scanned >= this.threshold) {
40388
40214
  this.warned = true;
40389
- logger7.warn(
40215
+ logger5.warn(
40390
40216
  `${SPARSE_SCAN_EVENT}: 1\u30EA\u30AF\u30A8\u30B9\u30C8\u3067 ${this.scanned} \u4EF6\u4EE5\u4E0A\u3092\u8AAD\u307F\u307E\u3057\u305F\u3002\u30A4\u30F3\u30C7\u30C3\u30AF\u30B9\u30FB\u30B9\u30AD\u30FC\u30DE\u30FB\u30ED\u30B8\u30C3\u30AF\u306E\u898B\u76F4\u3057\u3092\u691C\u8A0E\u3057\u3066\u304F\u3060\u3055\u3044\uFF08docs/SCAN_WARNING.md\uFF09`,
40391
40217
  {
40392
40218
  event: SPARSE_SCAN_EVENT,
@@ -40410,7 +40236,7 @@ var init_scanWarning = __esm({
40410
40236
  async function executeIdQuery(resource, normalizedParams, requestId) {
40411
40237
  const { sort, pagination, parsedFilters } = normalizedParams;
40412
40238
  const { perPage, nextToken } = pagination;
40413
- logger8.debug("Executing ID optimized query", {
40239
+ logger6.debug("Executing ID optimized query", {
40414
40240
  requestId,
40415
40241
  resource,
40416
40242
  sort,
@@ -40463,7 +40289,7 @@ async function executeSpecificIdQuery(resource, targetId, requestId) {
40463
40289
  costTracker.add(queryResult.ConsumedCapacity);
40464
40290
  const mainRecords = queryResult.Items || [];
40465
40291
  const items = mainRecords.map((item) => extractCleanRecord(item));
40466
- logger8.info("ID specific query succeeded", {
40292
+ logger6.info("ID specific query succeeded", {
40467
40293
  requestId,
40468
40294
  resource,
40469
40295
  targetId,
@@ -40495,7 +40321,7 @@ async function executeInQuery(resource, targetIds, sort, requestId) {
40495
40321
  if (typeof aVal === "number" && typeof bVal === "number") return (aVal - bVal) * direction;
40496
40322
  return String(aVal).localeCompare(String(bVal)) * direction;
40497
40323
  });
40498
- logger8.info("ID $in query succeeded", {
40324
+ logger6.info("ID $in query succeeded", {
40499
40325
  requestId,
40500
40326
  resource,
40501
40327
  requestedCount: targetIds.length,
@@ -40571,7 +40397,7 @@ async function executeAllRecordsQuery(resource, sort, perPage, nextToken, parsed
40571
40397
  queryResult.LastEvaluatedKey.PK,
40572
40398
  queryResult.LastEvaluatedKey.SK
40573
40399
  ) : void 0;
40574
- logger8.info("ID all records query succeeded", {
40400
+ logger6.info("ID all records query succeeded", {
40575
40401
  requestId,
40576
40402
  resource,
40577
40403
  count: items.length,
@@ -40612,7 +40438,7 @@ async function executeAllRecordsQueryFullScan(resource, sort, perPage, nextToken
40612
40438
  });
40613
40439
  scan: while (true) {
40614
40440
  if (++iterations > SCAN_MAX_ITERATIONS) {
40615
- logger8.error("executeAllRecordsQueryFullScan: \u6700\u5927\u53CD\u5FA9\u56DE\u6570\u3092\u8D85\u904E", {
40441
+ logger6.error("executeAllRecordsQueryFullScan: \u6700\u5927\u53CD\u5FA9\u56DE\u6570\u3092\u8D85\u904E", {
40616
40442
  requestId,
40617
40443
  resource,
40618
40444
  iterations
@@ -40660,7 +40486,7 @@ async function executeAllRecordsQueryFullScan(resource, sort, perPage, nextToken
40660
40486
  }
40661
40487
  const nextKeySignature = `${nextKey.PK}#${nextKey.SK}`;
40662
40488
  if (nextKeySignature === previousKeySignature) {
40663
- logger8.error("executeAllRecordsQueryFullScan: \u540C\u4E00\u306ELastEvaluatedKey\u304C\u8FD4\u5374\u3055\u308C\u305F", {
40489
+ logger6.error("executeAllRecordsQueryFullScan: \u540C\u4E00\u306ELastEvaluatedKey\u304C\u8FD4\u5374\u3055\u308C\u305F", {
40664
40490
  requestId,
40665
40491
  resource,
40666
40492
  iterations
@@ -40677,7 +40503,7 @@ async function executeAllRecordsQueryFullScan(resource, sort, perPage, nextToken
40677
40503
  chunkSize = Math.min(chunkSize * 2, SCAN_CHUNK_MAX);
40678
40504
  }
40679
40505
  const nextTokenValue = hasNextPage && lastReturned ? encodeNextToken(lastReturned.PK, lastReturned.SK) : void 0;
40680
- logger8.info("ID filtered scan query succeeded", {
40506
+ logger6.info("ID filtered scan query succeeded", {
40681
40507
  requestId,
40682
40508
  resource,
40683
40509
  scanned,
@@ -40691,7 +40517,7 @@ async function executeAllRecordsQueryFullScan(resource, sort, perPage, nextToken
40691
40517
  consumedCapacity: costTracker.getAggregated()
40692
40518
  };
40693
40519
  }
40694
- var import_lib_dynamodb3, logger8, SCAN_CHUNK_INITIAL, SCAN_CHUNK_MAX, SCAN_MAX_ITERATIONS;
40520
+ var import_lib_dynamodb3, logger6, SCAN_CHUNK_INITIAL, SCAN_CHUNK_MAX, SCAN_MAX_ITERATIONS;
40695
40521
  var init_idQuery = __esm({
40696
40522
  "src/server/operations/find/idQuery.ts"() {
40697
40523
  "use strict";
@@ -40703,7 +40529,7 @@ var init_idQuery = __esm({
40703
40529
  init_pagination();
40704
40530
  init_scanWarning();
40705
40531
  init_utils6();
40706
- logger8 = createLogger({
40532
+ logger6 = createLogger({
40707
40533
  service: "id-query",
40708
40534
  level: process.env.LOG_LEVEL || "info"
40709
40535
  });
@@ -40719,149 +40545,6 @@ var init_idQuery = __esm({
40719
40545
  }
40720
40546
  });
40721
40547
 
40722
- // src/server/operations/find/nearQuery.ts
40723
- async function executeNearQuery(resource, fieldName, nearQuery, limit, requestId) {
40724
- logger9.debug("Executing $near query", {
40725
- requestId,
40726
- resource,
40727
- fieldName,
40728
- nearQuery,
40729
- limit
40730
- });
40731
- const costTracker = new CostTracker();
40732
- const searchFunction = /* @__PURE__ */ __name(async (geohashPrefix) => {
40733
- const dbClient2 = getDBClient();
40734
- const tableName = getTableName();
40735
- logger9.debug("Searching shadow records", {
40736
- requestId,
40737
- resource,
40738
- fieldName,
40739
- geohashPrefix,
40740
- skPrefix: `${fieldName}#${geohashPrefix}`
40741
- });
40742
- const shadowRecords = [];
40743
- const watcher = new ScanWatcher({
40744
- requestId,
40745
- resource,
40746
- path: "near-search",
40747
- sortField: fieldName,
40748
- filters: ["$near"]
40749
- });
40750
- let exclusiveStartKey;
40751
- let previousKeySignature;
40752
- do {
40753
- const queryResult = await executeDynamoDBOperation(
40754
- () => dbClient2.send(
40755
- new import_lib_dynamodb4.QueryCommand({
40756
- TableName: tableName,
40757
- KeyConditionExpression: "PK = :pk AND begins_with(SK, :skPrefix)",
40758
- ExpressionAttributeValues: {
40759
- ":pk": resource,
40760
- ":skPrefix": `${fieldName}#${geohashPrefix}`
40761
- },
40762
- ExclusiveStartKey: exclusiveStartKey,
40763
- ConsistentRead: false,
40764
- // シャドウレコードは結果整合性で十分
40765
- ReturnConsumedCapacity: "TOTAL"
40766
- })
40767
- ),
40768
- "Query"
40769
- );
40770
- costTracker.add(queryResult.ConsumedCapacity);
40771
- shadowRecords.push(...queryResult.Items || []);
40772
- watcher.add((queryResult.Items || []).length);
40773
- const nextKey = queryResult.LastEvaluatedKey;
40774
- const nextKeySignature = nextKey ? `${nextKey.PK}#${nextKey.SK}` : void 0;
40775
- if (nextKeySignature && nextKeySignature === previousKeySignature) {
40776
- throw new AppError(
40777
- "INTERNAL_ERROR" /* INTERNAL_ERROR */,
40778
- "Near search received the same LastEvaluatedKey repeatedly",
40779
- 500,
40780
- { resource, geohashPrefix }
40781
- );
40782
- }
40783
- previousKeySignature = nextKeySignature;
40784
- exclusiveStartKey = nextKey;
40785
- } while (exclusiveStartKey);
40786
- logger9.debug("Shadow records found", {
40787
- requestId,
40788
- resource,
40789
- geohashPrefix,
40790
- count: shadowRecords.length
40791
- });
40792
- const mainRecordIds = shadowRecords.map((item) => {
40793
- const sk = item.SK;
40794
- const parts = sk.split("#id#");
40795
- return parts.length === 2 ? parts[1] : null;
40796
- }).filter((id) => id !== null);
40797
- logger9.debug("Main record IDs extracted", {
40798
- requestId,
40799
- resource,
40800
- geohashPrefix,
40801
- ids: mainRecordIds
40802
- });
40803
- const validRecords = await batchGetAll(
40804
- mainRecordIds.map((id) => ({ PK: resource, SK: `id#${id}` })),
40805
- { consistentRead: false, costTracker, requestId }
40806
- );
40807
- logger9.debug("Main records retrieved", {
40808
- requestId,
40809
- resource,
40810
- geohashPrefix,
40811
- count: validRecords.length
40812
- });
40813
- const cleanRecords = validRecords.map((record) => extractCleanRecord(record));
40814
- logger9.debug("Clean records extracted", {
40815
- requestId,
40816
- resource,
40817
- geohashPrefix,
40818
- count: cleanRecords.length,
40819
- sampleKeys: cleanRecords[0] ? Object.keys(cleanRecords[0]) : []
40820
- });
40821
- return cleanRecords;
40822
- }, "searchFunction");
40823
- const minPrecisionOverride = "minPrecision" in nearQuery ? nearQuery.minPrecision : "$minPrecision" in nearQuery ? nearQuery.$minPrecision : void 0;
40824
- const config = minPrecisionOverride !== void 0 ? { ...DEFAULT_GEOHASH_CONFIG, minPrecision: minPrecisionOverride } : DEFAULT_GEOHASH_CONFIG;
40825
- const result = await executeNearSearch(nearQuery, fieldName, limit, searchFunction, config);
40826
- const items = result.documents;
40827
- logger9.info("$near query succeeded", {
40828
- requestId,
40829
- resource,
40830
- fieldName,
40831
- count: items.length,
40832
- iterations: result.metadata.iterations,
40833
- candidatesFound: result.metadata.candidatesFound
40834
- });
40835
- return {
40836
- items,
40837
- pageInfo: {
40838
- hasNextPage: false,
40839
- // $near検索はページネーション非対応
40840
- hasPreviousPage: false
40841
- },
40842
- consumedCapacity: costTracker.getAggregated()
40843
- };
40844
- }
40845
- var import_lib_dynamodb4, logger9;
40846
- var init_nearQuery = __esm({
40847
- "src/server/operations/find/nearQuery.ts"() {
40848
- "use strict";
40849
- import_lib_dynamodb4 = __toESM(require_dist_cjs22(), 1);
40850
- init_geohash();
40851
- init_shared();
40852
- init_nearSearch();
40853
- init_batchGet();
40854
- init_cost_tracker();
40855
- init_dynamodb3();
40856
- init_scanWarning();
40857
- logger9 = createLogger({
40858
- service: "near-query",
40859
- level: process.env.LOG_LEVEL || "info"
40860
- });
40861
- __name(executeNearQuery, "executeNearQuery");
40862
- }
40863
- });
40864
-
40865
40548
  // src/server/operations/find/shadowQuery.ts
40866
40549
  async function executeShadowQuery(resource, normalizedParams, requestId) {
40867
40550
  const { sort, pagination, parsedFilters } = normalizedParams;
@@ -40885,11 +40568,12 @@ async function executeShadowQuery(resource, normalizedParams, requestId) {
40885
40568
  }
40886
40569
  const optimizableFilter = findOptimizableFilter(sort.field, parsedFilters);
40887
40570
  const isKeyConditionOptimized = optimizableFilter !== void 0 && KEY_CONDITION_OPERATORS.has(optimizableFilter.parsed.operator);
40571
+ const upperFilter = isKeyConditionOptimized ? findComplementaryBound(optimizableFilter, parsedFilters) : void 0;
40888
40572
  const residualFilters = parsedFilters.filter(
40889
- (f5) => !(isKeyConditionOptimized && f5 === optimizableFilter)
40573
+ (f5) => !(isKeyConditionOptimized && (f5 === optimizableFilter || f5 === upperFilter))
40890
40574
  );
40891
40575
  if (residualFilters.length > 0) {
40892
- logger10.debug("Residual filters detected, falling back to full scan", {
40576
+ logger7.debug("Residual filters detected, falling back to full scan", {
40893
40577
  requestId,
40894
40578
  resource,
40895
40579
  sortField: sort.field,
@@ -40897,7 +40581,7 @@ async function executeShadowQuery(resource, normalizedParams, requestId) {
40897
40581
  });
40898
40582
  return executeFullScanQuery(resource, normalizedParams, costTracker, requestId);
40899
40583
  }
40900
- logger10.debug("Executing shadow query", {
40584
+ logger7.debug("Executing shadow query", {
40901
40585
  requestId,
40902
40586
  resource,
40903
40587
  sortField: sort.field,
@@ -40911,7 +40595,8 @@ async function executeShadowQuery(resource, normalizedParams, requestId) {
40911
40595
  nextToken,
40912
40596
  isKeyConditionOptimized ? optimizableFilter : void 0,
40913
40597
  costTracker,
40914
- requestId
40598
+ requestId,
40599
+ upperFilter
40915
40600
  );
40916
40601
  const recordIds = extractRecordIds(shadowRecords.Items || []);
40917
40602
  if (recordIds.length === 0) {
@@ -40945,7 +40630,7 @@ async function executeShadowQuery(resource, normalizedParams, requestId) {
40945
40630
  shadowRecords.LastEvaluatedKey.PK,
40946
40631
  shadowRecords.LastEvaluatedKey.SK
40947
40632
  ) : void 0;
40948
- logger10.info("Shadow query succeeded", {
40633
+ logger7.info("Shadow query succeeded", {
40949
40634
  requestId,
40950
40635
  resource,
40951
40636
  sortField: sort.field,
@@ -40969,8 +40654,8 @@ async function executeFilterFirstQuery(resource, normalizedParams, filterCandida
40969
40654
  const { perPage, nextToken } = pagination;
40970
40655
  const offset = nextToken ? decodeOffsetToken(nextToken) ?? 0 : 0;
40971
40656
  const filterSort = { field: filterCandidate.parsed.field, order: "ASC" };
40972
- const remainingFilters = parsedFilters.filter((f5) => f5 !== filterCandidate);
40973
- logger10.debug("Executing filter-first query", {
40657
+ const remainingFilters = parsedFilters;
40658
+ logger7.debug("Executing filter-first query", {
40974
40659
  requestId,
40975
40660
  resource,
40976
40661
  filterField: filterCandidate.parsed.field,
@@ -40993,7 +40678,7 @@ async function executeFilterFirstQuery(resource, normalizedParams, filterCandida
40993
40678
  const page = items.slice(offset, offset + perPage);
40994
40679
  const hasNextPage = offset + perPage < items.length;
40995
40680
  const nextTokenValue = hasNextPage ? encodeOffsetToken(offset + perPage) : void 0;
40996
- logger10.info("Filter-first query succeeded", {
40681
+ logger7.info("Filter-first query succeeded", {
40997
40682
  requestId,
40998
40683
  resource,
40999
40684
  filterField: filterCandidate.parsed.field,
@@ -41014,7 +40699,7 @@ async function executeFullScanQuery(resource, normalizedParams, costTracker, req
41014
40699
  const { sort, pagination, parsedFilters } = normalizedParams;
41015
40700
  const { perPage, nextToken } = pagination;
41016
40701
  const offset = nextToken ? decodeOffsetToken(nextToken) ?? 0 : 0;
41017
- logger10.debug("Executing full scan query", {
40702
+ logger7.debug("Executing full scan query", {
41018
40703
  requestId,
41019
40704
  resource,
41020
40705
  sortField: sort.field,
@@ -41035,7 +40720,7 @@ async function executeFullScanQuery(resource, normalizedParams, costTracker, req
41035
40720
  const page = items.slice(offset, offset + perPage);
41036
40721
  const hasNextPage = offset + perPage < items.length;
41037
40722
  const nextTokenValue = hasNextPage ? encodeOffsetToken(offset + perPage) : void 0;
41038
- logger10.info("Full scan query succeeded", {
40723
+ logger7.info("Full scan query succeeded", {
41039
40724
  requestId,
41040
40725
  resource,
41041
40726
  sortField: sort.field,
@@ -41066,7 +40751,7 @@ async function fetchAllRecordsViaShadowIndex(resource, indexSort, indexFilter, c
41066
40751
  let iterations = 0;
41067
40752
  do {
41068
40753
  if (++iterations > MAX_ITERATIONS) {
41069
- logger10.error("fetchAllRecordsViaShadowIndex: \u6700\u5927\u53CD\u5FA9\u56DE\u6570\u3092\u8D85\u904E", {
40754
+ logger7.error("fetchAllRecordsViaShadowIndex: \u6700\u5927\u53CD\u5FA9\u56DE\u6570\u3092\u8D85\u904E", {
41070
40755
  requestId,
41071
40756
  resource,
41072
40757
  iterations
@@ -41096,7 +40781,7 @@ async function fetchAllRecordsViaShadowIndex(resource, indexSort, indexFilter, c
41096
40781
  const nextKey = result.LastEvaluatedKey;
41097
40782
  const nextKeySignature = nextKey ? `${nextKey.PK}#${nextKey.SK}` : void 0;
41098
40783
  if (nextKeySignature && nextKeySignature === previousKeySignature) {
41099
- logger10.error("fetchAllRecordsViaShadowIndex: \u540C\u4E00\u306ELastEvaluatedKey\u304C\u8FD4\u5374\u3055\u308C\u305F", {
40784
+ logger7.error("fetchAllRecordsViaShadowIndex: \u540C\u4E00\u306ELastEvaluatedKey\u304C\u8FD4\u5374\u3055\u308C\u305F", {
41100
40785
  requestId,
41101
40786
  resource,
41102
40787
  iterations
@@ -41131,7 +40816,7 @@ function selectFilterFirstCandidate(parsedFilters, sortField, schema, perPage) {
41131
40816
  if (eqFilters.length === 0) return void 0;
41132
40817
  const cardinality = schema?.cardinality;
41133
40818
  if (!cardinality) {
41134
- return void 0;
40819
+ return eqFilters[0];
41135
40820
  }
41136
40821
  const threshold = perPage / 2;
41137
40822
  const scored = eqFilters.map((f5) => ({ f: f5, score: cardinality[f5.parsed.field] ?? 0 })).filter(({ score }) => score > threshold).sort((a5, b5) => b5.score - a5.score);
@@ -41150,7 +40835,7 @@ function sortInMemory(items, sort) {
41150
40835
  return 0;
41151
40836
  });
41152
40837
  }
41153
- async function executeShadowRecordQuery(resource, sort, perPage, nextToken, optimizableFilter, costTracker, _requestId) {
40838
+ async function executeShadowRecordQuery(resource, sort, perPage, nextToken, optimizableFilter, costTracker, _requestId, secondFilter) {
41154
40839
  const dbClient2 = getDBClient();
41155
40840
  const tableName = getTableName();
41156
40841
  let exclusiveStartKey;
@@ -41164,11 +40849,12 @@ async function executeShadowRecordQuery(resource, sort, perPage, nextToken, opti
41164
40849
  const { keyConditionExpression, expressionAttributeValues } = buildKeyCondition(
41165
40850
  resource,
41166
40851
  sort.field,
41167
- optimizableFilter
40852
+ optimizableFilter,
40853
+ secondFilter
41168
40854
  );
41169
40855
  const result = await executeDynamoDBOperation(
41170
40856
  () => dbClient2.send(
41171
- new import_lib_dynamodb5.QueryCommand({
40857
+ new import_lib_dynamodb4.QueryCommand({
41172
40858
  TableName: tableName,
41173
40859
  KeyConditionExpression: keyConditionExpression,
41174
40860
  ExpressionAttributeValues: expressionAttributeValues,
@@ -41184,102 +40870,6 @@ async function executeShadowRecordQuery(resource, sort, perPage, nextToken, opti
41184
40870
  costTracker.add(result.ConsumedCapacity);
41185
40871
  return result;
41186
40872
  }
41187
- function buildKeyCondition(resource, sortField, optimizableFilter) {
41188
- const expressionAttributeValues = {
41189
- ":pk": resource
41190
- };
41191
- if (!optimizableFilter) {
41192
- return {
41193
- keyConditionExpression: "PK = :pk AND begins_with(SK, :skPrefix)",
41194
- expressionAttributeValues: {
41195
- ...expressionAttributeValues,
41196
- ":skPrefix": `${sortField}#`
41197
- }
41198
- };
41199
- }
41200
- const { operator, type } = optimizableFilter.parsed;
41201
- const value = optimizableFilter.value;
41202
- const { encoded, exact } = encodeValueForShadowSK(value, type, operator);
41203
- const skValue = `${sortField}#${encoded}`;
41204
- const afterValue = `${skValue}#id#~`;
41205
- const beforeValue = `${skValue}#id#`;
41206
- switch (operator) {
41207
- case "$eq":
41208
- return {
41209
- keyConditionExpression: "PK = :pk AND begins_with(SK, :skValue)",
41210
- expressionAttributeValues: {
41211
- ...expressionAttributeValues,
41212
- ":skValue": beforeValue
41213
- }
41214
- };
41215
- // 範囲検索は SK BETWEEN の 1 条件にする。
41216
- // - DynamoDB はソートキーに 1 つの条件しか許さない(begins_with と比較を並べると ValidationException)
41217
- // - 上限・下限を sortField の範囲に閉じないと、他の項目のシャドー(や本体 id#…)まで読む
41218
- // BETWEEN は両端を含むが、端の値(`…#id#`、`…#id#~`、`{sortField}$`)と一致する SK は実在しない
41219
- case "$gt":
41220
- return rangeCondition(
41221
- expressionAttributeValues,
41222
- exact ? afterValue : beforeValue,
41223
- fieldUpperBound(sortField)
41224
- );
41225
- case "$gte":
41226
- return rangeCondition(expressionAttributeValues, beforeValue, fieldUpperBound(sortField));
41227
- case "$lt":
41228
- return rangeCondition(
41229
- expressionAttributeValues,
41230
- `${sortField}#`,
41231
- exact ? beforeValue : afterValue
41232
- );
41233
- case "$lte":
41234
- return rangeCondition(expressionAttributeValues, `${sortField}#`, afterValue);
41235
- case "$starts":
41236
- return {
41237
- keyConditionExpression: "PK = :pk AND begins_with(SK, :skValue)",
41238
- expressionAttributeValues: {
41239
- ...expressionAttributeValues,
41240
- ":skValue": skValue
41241
- }
41242
- };
41243
- default:
41244
- return {
41245
- keyConditionExpression: "PK = :pk AND begins_with(SK, :skPrefix)",
41246
- expressionAttributeValues: {
41247
- ...expressionAttributeValues,
41248
- ":skPrefix": `${sortField}#`
41249
- }
41250
- };
41251
- }
41252
- }
41253
- function fieldUpperBound(sortField) {
41254
- return `${sortField}$`;
41255
- }
41256
- function rangeCondition(base, low, high) {
41257
- return {
41258
- keyConditionExpression: "PK = :pk AND SK BETWEEN :skLow AND :skHigh",
41259
- expressionAttributeValues: { ...base, ":skLow": low, ":skHigh": high }
41260
- };
41261
- }
41262
- function encodeValueForShadowSK(value, type, operator) {
41263
- const config = getShadowConfig();
41264
- if (type === "number" || typeof value === "number") {
41265
- const num = Number(value);
41266
- return { encoded: formatFieldValue2("number", num, config), exact: false };
41267
- }
41268
- if (type === "boolean" || typeof value === "boolean") {
41269
- const bool = typeof value === "boolean" ? value : String(value).toLowerCase() === "true";
41270
- return { encoded: formatFieldValue2("boolean", bool, config), exact: true };
41271
- }
41272
- const str = String(value);
41273
- if (operator !== "$starts" && (type === "date" || inferFieldType(str) === "datetime")) {
41274
- return { encoded: formatFieldValue2("datetime", str, config), exact: true };
41275
- }
41276
- const encoded = formatFieldValue2("string", str, config);
41277
- const bytes = new TextEncoder().encode(str).length;
41278
- return {
41279
- encoded,
41280
- exact: encoded === escapeString2(str) && bytes < config.stringMaxBytes - 3
41281
- };
41282
- }
41283
40873
  function extractRecordIds(shadowRecords) {
41284
40874
  return shadowRecords.map((record) => {
41285
40875
  const sk = record.SK;
@@ -41292,7 +40882,7 @@ async function fetchMainRecords(resource, recordIds, costTracker, requestId) {
41292
40882
  recordIds.map((id) => ({ PK: resource, SK: `id#${id}` })),
41293
40883
  { consistentRead: true, costTracker, requestId }
41294
40884
  );
41295
- logger10.debug("Main records fetched", {
40885
+ logger7.debug("Main records fetched", {
41296
40886
  requestId,
41297
40887
  resource,
41298
40888
  requestedCount: new Set(recordIds).size,
@@ -41300,24 +40890,23 @@ async function fetchMainRecords(resource, recordIds, costTracker, requestId) {
41300
40890
  });
41301
40891
  return allRecords;
41302
40892
  }
41303
- var import_lib_dynamodb5, logger10, KEY_CONDITION_OPERATORS;
40893
+ var import_lib_dynamodb4, logger7;
41304
40894
  var init_shadowQuery = __esm({
41305
40895
  "src/server/operations/find/shadowQuery.ts"() {
41306
40896
  "use strict";
41307
- import_lib_dynamodb5 = __toESM(require_dist_cjs22(), 1);
40897
+ import_lib_dynamodb4 = __toESM(require_dist_cjs22(), 1);
41308
40898
  init_shared();
41309
- init_shadow();
41310
40899
  init_batchGet();
41311
40900
  init_cost_tracker();
41312
40901
  init_dynamodb3();
41313
40902
  init_pagination();
41314
40903
  init_scanWarning();
40904
+ init_keyCondition();
41315
40905
  init_utils6();
41316
- logger10 = createLogger({
40906
+ logger7 = createLogger({
41317
40907
  service: "shadow-query",
41318
40908
  level: process.env.LOG_LEVEL || "info"
41319
40909
  });
41320
- KEY_CONDITION_OPERATORS = /* @__PURE__ */ new Set(["$eq", "$gt", "$gte", "$lt", "$lte", "$starts"]);
41321
40910
  __name(executeShadowQuery, "executeShadowQuery");
41322
40911
  __name(executeFilterFirstQuery, "executeFilterFirstQuery");
41323
40912
  __name(executeFullScanQuery, "executeFullScanQuery");
@@ -41325,42 +40914,184 @@ var init_shadowQuery = __esm({
41325
40914
  __name(selectFilterFirstCandidate, "selectFilterFirstCandidate");
41326
40915
  __name(sortInMemory, "sortInMemory");
41327
40916
  __name(executeShadowRecordQuery, "executeShadowRecordQuery");
41328
- __name(buildKeyCondition, "buildKeyCondition");
41329
- __name(fieldUpperBound, "fieldUpperBound");
41330
- __name(rangeCondition, "rangeCondition");
41331
- __name(encodeValueForShadowSK, "encodeValueForShadowSK");
41332
40917
  __name(extractRecordIds, "extractRecordIds");
41333
40918
  __name(fetchMainRecords, "fetchMainRecords");
41334
40919
  }
41335
40920
  });
41336
40921
 
40922
+ // src/server/operations/find/nearQuery.ts
40923
+ async function executeNearQuery(resource, fieldName, nearQuery, limit, requestId, condition) {
40924
+ logger8.debug("Executing $near query", {
40925
+ requestId,
40926
+ resource,
40927
+ fieldName,
40928
+ nearQuery,
40929
+ limit
40930
+ });
40931
+ const costTracker = new CostTracker();
40932
+ const searchShadows = /* @__PURE__ */ __name(async (geohashPrefix) => {
40933
+ const dbClient2 = getDBClient();
40934
+ const tableName = getTableName();
40935
+ logger8.debug("Searching shadow records", {
40936
+ requestId,
40937
+ resource,
40938
+ fieldName,
40939
+ geohashPrefix,
40940
+ skPrefix: `${fieldName}#${geohashPrefix}`
40941
+ });
40942
+ const shadowRecords = [];
40943
+ const watcher = new ScanWatcher({
40944
+ requestId,
40945
+ resource,
40946
+ path: "near-search",
40947
+ sortField: fieldName,
40948
+ filters: ["$near"]
40949
+ });
40950
+ let exclusiveStartKey;
40951
+ let previousKeySignature;
40952
+ do {
40953
+ const queryResult = await executeDynamoDBOperation(
40954
+ () => dbClient2.send(
40955
+ new import_lib_dynamodb5.QueryCommand({
40956
+ TableName: tableName,
40957
+ KeyConditionExpression: "PK = :pk AND begins_with(SK, :skPrefix)",
40958
+ ExpressionAttributeValues: {
40959
+ ":pk": resource,
40960
+ ":skPrefix": `${fieldName}#${geohashPrefix}`
40961
+ },
40962
+ ExclusiveStartKey: exclusiveStartKey,
40963
+ ConsistentRead: false,
40964
+ // シャドウレコードは結果整合性で十分
40965
+ ReturnConsumedCapacity: "TOTAL"
40966
+ })
40967
+ ),
40968
+ "Query"
40969
+ );
40970
+ costTracker.add(queryResult.ConsumedCapacity);
40971
+ shadowRecords.push(...queryResult.Items || []);
40972
+ watcher.add((queryResult.Items || []).length);
40973
+ const nextKey = queryResult.LastEvaluatedKey;
40974
+ const nextKeySignature = nextKey ? `${nextKey.PK}#${nextKey.SK}` : void 0;
40975
+ if (nextKeySignature && nextKeySignature === previousKeySignature) {
40976
+ throw new AppError(
40977
+ "INTERNAL_ERROR" /* INTERNAL_ERROR */,
40978
+ "Near search received the same LastEvaluatedKey repeatedly",
40979
+ 500,
40980
+ { resource, geohashPrefix }
40981
+ );
40982
+ }
40983
+ previousKeySignature = nextKeySignature;
40984
+ exclusiveStartKey = nextKey;
40985
+ } while (exclusiveStartKey);
40986
+ logger8.debug("Shadow records found", {
40987
+ requestId,
40988
+ resource,
40989
+ geohashPrefix,
40990
+ count: shadowRecords.length
40991
+ });
40992
+ const hits = [];
40993
+ for (const record of shadowRecords) {
40994
+ const sk = String(record.SK);
40995
+ const afterField = sk.slice(fieldName.length + 1);
40996
+ const geohash = afterField.slice(0, afterField.indexOf("#"));
40997
+ const [id] = extractRecordIds([record]);
40998
+ if (id !== void 0 && geohash !== "") hits.push({ id, geohash });
40999
+ }
41000
+ return hits;
41001
+ }, "searchShadows");
41002
+ const matches = conditionMatcher(condition);
41003
+ const readBodies = /* @__PURE__ */ __name(async (ids) => {
41004
+ const bodies = await batchGetAll(
41005
+ ids.map((id) => ({ PK: resource, SK: `id#${id}` })),
41006
+ { consistentRead: false, costTracker, requestId }
41007
+ );
41008
+ return bodies.map((record) => extractCleanRecord(record)).filter(matches);
41009
+ }, "readBodies");
41010
+ const minPrecisionOverride = "minPrecision" in nearQuery ? nearQuery.minPrecision : "$minPrecision" in nearQuery ? nearQuery.$minPrecision : void 0;
41011
+ const config = minPrecisionOverride !== void 0 ? { ...DEFAULT_GEOHASH_CONFIG, minPrecision: minPrecisionOverride } : DEFAULT_GEOHASH_CONFIG;
41012
+ const result = await executeNearSearch(
41013
+ nearQuery,
41014
+ fieldName,
41015
+ limit,
41016
+ searchShadows,
41017
+ readBodies,
41018
+ config
41019
+ );
41020
+ const items = result.documents;
41021
+ logger8.info("$near query succeeded", {
41022
+ requestId,
41023
+ resource,
41024
+ fieldName,
41025
+ count: items.length,
41026
+ iterations: result.metadata.iterations,
41027
+ candidatesFound: result.metadata.candidatesFound,
41028
+ bodiesRead: result.metadata.bodiesRead,
41029
+ exhaustive: result.metadata.exhaustive
41030
+ });
41031
+ return {
41032
+ items,
41033
+ pageInfo: {
41034
+ hasNextPage: false,
41035
+ // $near検索はページネーション非対応
41036
+ hasPreviousPage: false,
41037
+ exhaustive: result.metadata.exhaustive
41038
+ },
41039
+ consumedCapacity: costTracker.getAggregated()
41040
+ };
41041
+ }
41042
+ var import_lib_dynamodb5, logger8;
41043
+ var init_nearQuery = __esm({
41044
+ "src/server/operations/find/nearQuery.ts"() {
41045
+ "use strict";
41046
+ import_lib_dynamodb5 = __toESM(require_dist_cjs22(), 1);
41047
+ init_geohash();
41048
+ init_shared();
41049
+ init_nearSearch();
41050
+ init_batchGet();
41051
+ init_cost_tracker();
41052
+ init_dynamodb3();
41053
+ init_idFilter();
41054
+ init_scanWarning();
41055
+ init_shadowQuery();
41056
+ logger8 = createLogger({
41057
+ service: "near-query",
41058
+ level: process.env.LOG_LEVEL || "info"
41059
+ });
41060
+ __name(executeNearQuery, "executeNearQuery");
41061
+ }
41062
+ });
41063
+
41337
41064
  // src/server/operations/find/handler.ts
41338
41065
  async function handleFind(resource, params, requestId) {
41339
- logger11.debug("Executing find", {
41066
+ logger9.debug("Executing find", {
41340
41067
  requestId,
41341
41068
  resource,
41342
41069
  params
41343
41070
  });
41344
41071
  const nearDetection = detectNearQuery(params.filter);
41345
41072
  if (nearDetection) {
41346
- logger11.debug("$near operator detected, executing near search", {
41073
+ logger9.debug("$near operator detected, executing near search", {
41347
41074
  requestId,
41348
41075
  resource,
41349
41076
  fieldName: nearDetection.fieldName
41350
41077
  });
41351
41078
  const limit = params.pagination?.perPage || 10;
41079
+ const otherFilters = Object.fromEntries(
41080
+ Object.entries(params.filter ?? {}).filter(([field]) => field !== nearDetection.fieldName)
41081
+ );
41352
41082
  return executeNearQuery(
41353
41083
  resource,
41354
41084
  nearDetection.fieldName,
41355
41085
  nearDetection.nearQuery,
41356
41086
  limit,
41357
- requestId
41087
+ requestId,
41088
+ conditionOf(otherFilters)
41358
41089
  );
41359
41090
  }
41360
41091
  const config = initializeFindConfig();
41361
41092
  const normalizedParams = normalizeFindParams(config, resource, params);
41362
41093
  validateSortField(config, resource, normalizedParams.sort);
41363
- logger11.debug("Find parameters normalized", {
41094
+ logger9.debug("Find parameters normalized", {
41364
41095
  requestId,
41365
41096
  resource,
41366
41097
  sort: normalizedParams.sort,
@@ -41375,17 +41106,18 @@ async function handleFind(resource, params, requestId) {
41375
41106
  }
41376
41107
  return executeShadowQuery(resource, normalizedParams, requestId);
41377
41108
  }
41378
- var logger11;
41109
+ var logger9;
41379
41110
  var init_handler = __esm({
41380
41111
  "src/server/operations/find/handler.ts"() {
41381
41112
  "use strict";
41382
41113
  init_shared();
41114
+ init_idFilter();
41383
41115
  init_validation2();
41384
41116
  init_idQuery();
41385
41117
  init_nearQuery();
41386
41118
  init_shadowQuery();
41387
41119
  init_utils6();
41388
- logger11 = createLogger({
41120
+ logger9 = createLogger({
41389
41121
  service: "find-handler",
41390
41122
  level: process.env.LOG_LEVEL || "info"
41391
41123
  });
@@ -41455,6 +41187,312 @@ var init_findAll = __esm({
41455
41187
  }
41456
41188
  });
41457
41189
 
41190
+ // src/server/utils/bulkOperations.ts
41191
+ function logLargeBatchWarning(operation2, recordCount, requestId, resource) {
41192
+ if (recordCount > LARGE_BATCH_WARNING_THRESHOLD) {
41193
+ logger10.warn(`Large batch ${operation2} operation detected`, {
41194
+ requestId,
41195
+ resource,
41196
+ recordCount,
41197
+ warningThreshold: LARGE_BATCH_WARNING_THRESHOLD,
41198
+ estimatedTimeoutRisk: "high",
41199
+ recommendation: "Consider splitting the batch into smaller requests to avoid Lambda timeout (15 min limit)"
41200
+ });
41201
+ }
41202
+ }
41203
+ function calculateTimeoutRisk(startTime) {
41204
+ const elapsedMs = Date.now() - startTime;
41205
+ const remainingMs = LAMBDA_TIMEOUT_MS - elapsedMs;
41206
+ const utilizationPercent = Math.round(elapsedMs / LAMBDA_TIMEOUT_MS * 100);
41207
+ const risk = remainingMs < LAMBDA_TIMEOUT_MS * TIMEOUT_RISK_THRESHOLD ? "high" : "low";
41208
+ return {
41209
+ elapsedMs,
41210
+ remainingMs,
41211
+ risk,
41212
+ utilizationPercent
41213
+ };
41214
+ }
41215
+ function logPreparationTimeoutRisk(requestId, resource, totalRecords, chunkCount, riskInfo) {
41216
+ logger10.info("Records prepared for chunk execution", {
41217
+ requestId,
41218
+ resource,
41219
+ totalRecords,
41220
+ chunkCount,
41221
+ preparationTimeMs: riskInfo.elapsedMs,
41222
+ remainingTimeMs: riskInfo.remainingMs,
41223
+ timeoutRisk: riskInfo.risk
41224
+ });
41225
+ if (riskInfo.risk === "high") {
41226
+ logger10.warn("High timeout risk detected during preparation phase", {
41227
+ requestId,
41228
+ resource,
41229
+ preparationElapsedMs: riskInfo.elapsedMs,
41230
+ remainingTimeMs: riskInfo.remainingMs,
41231
+ lambdaTimeoutMs: LAMBDA_TIMEOUT_MS,
41232
+ recommendation: "Consider reducing batch size or optimizing preparation logic"
41233
+ });
41234
+ }
41235
+ }
41236
+ function logBulkOperationComplete(operation2, requestId, resource, requested, succeeded, failed, riskInfo, additionalInfo) {
41237
+ const totalElapsedSeconds = Math.round(riskInfo.elapsedMs / 1e3);
41238
+ logger10.info(`${operation2} completed`, {
41239
+ requestId,
41240
+ resource,
41241
+ requested,
41242
+ succeeded,
41243
+ totalFailed: failed,
41244
+ totalExecutionTimeMs: riskInfo.elapsedMs,
41245
+ totalExecutionTimeSeconds: totalElapsedSeconds,
41246
+ lambdaTimeoutMs: LAMBDA_TIMEOUT_MS,
41247
+ timeoutUtilization: `${riskInfo.utilizationPercent}%`,
41248
+ ...additionalInfo
41249
+ });
41250
+ }
41251
+ function logPartialFailure(operation2, requestId, resource, requested, succeeded, failed, errorCodes, additionalInfo) {
41252
+ const failureRate = Math.round(failed / requested * 100);
41253
+ logger10.warn(`Partial failure in ${operation2} operation`, {
41254
+ requestId,
41255
+ resource,
41256
+ totalRequested: requested,
41257
+ successCount: succeeded,
41258
+ failedCount: failed,
41259
+ failureRate: `${failureRate}%`,
41260
+ errorCodes: [...new Set(errorCodes)],
41261
+ ...additionalInfo
41262
+ });
41263
+ }
41264
+ var logger10;
41265
+ var init_bulkOperations = __esm({
41266
+ "src/server/utils/bulkOperations.ts"() {
41267
+ "use strict";
41268
+ init_shared();
41269
+ logger10 = createLogger({ service: "records-lambda" });
41270
+ __name(logLargeBatchWarning, "logLargeBatchWarning");
41271
+ __name(calculateTimeoutRisk, "calculateTimeoutRisk");
41272
+ __name(logPreparationTimeoutRisk, "logPreparationTimeoutRisk");
41273
+ __name(logBulkOperationComplete, "logBulkOperationComplete");
41274
+ __name(logPartialFailure, "logPartialFailure");
41275
+ }
41276
+ });
41277
+
41278
+ // src/server/utils/chunking.ts
41279
+ function estimateRecordBytes(record) {
41280
+ return Buffer.byteLength(JSON.stringify(record) ?? "", "utf8");
41281
+ }
41282
+ function calculateChunks(records, getItemCount, getByteSize = estimateRecordBytes) {
41283
+ const chunks = [];
41284
+ const itemCounts = [];
41285
+ let currentChunk = [];
41286
+ let currentItemCount = 0;
41287
+ let currentBytes = 0;
41288
+ for (const record of records) {
41289
+ const itemCount = getItemCount(record);
41290
+ const bytes = getByteSize(record);
41291
+ if (itemCount > DYNAMODB_TRANSACT_WRITE_MAX_ITEMS) {
41292
+ const errorMsg = `Single record exceeds ${DYNAMODB_TRANSACT_WRITE_MAX_ITEMS} items limit: ${itemCount} items`;
41293
+ logger11.error("Chunk validation failed", {
41294
+ itemCount,
41295
+ limit: DYNAMODB_TRANSACT_WRITE_MAX_ITEMS
41296
+ });
41297
+ throw new Error(errorMsg);
41298
+ }
41299
+ if (currentItemCount + itemCount > DYNAMODB_TRANSACT_WRITE_MAX_ITEMS || currentBytes + bytes > CHUNK_MAX_BYTES) {
41300
+ if (currentChunk.length > 0) {
41301
+ chunks.push(currentChunk);
41302
+ itemCounts.push(currentItemCount);
41303
+ }
41304
+ currentChunk = [record];
41305
+ currentItemCount = itemCount;
41306
+ currentBytes = bytes;
41307
+ } else {
41308
+ currentChunk.push(record);
41309
+ currentItemCount += itemCount;
41310
+ currentBytes += bytes;
41311
+ }
41312
+ }
41313
+ if (currentChunk.length > 0) {
41314
+ chunks.push(currentChunk);
41315
+ itemCounts.push(currentItemCount);
41316
+ }
41317
+ logger11.info("Chunk calculation completed", {
41318
+ totalRecords: records.length,
41319
+ chunkCount: chunks.length,
41320
+ itemCounts,
41321
+ minItemsPerChunk: itemCounts.length > 0 ? Math.min(...itemCounts) : 0,
41322
+ maxItemsPerChunk: itemCounts.length > 0 ? Math.max(...itemCounts) : 0,
41323
+ avgItemsPerChunk: itemCounts.length > 0 ? Math.round(itemCounts.reduce((sum, count) => sum + count, 0) / itemCounts.length) : 0
41324
+ });
41325
+ return { chunks, itemCounts };
41326
+ }
41327
+ async function executeChunks(chunks, executeChunk, getRecordId) {
41328
+ const successRecords = [];
41329
+ const failedIds = [];
41330
+ const errors = [];
41331
+ const totalRecords = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
41332
+ const executionStartTime = Date.now();
41333
+ logger11.info("Starting chunk execution", {
41334
+ totalChunks: chunks.length,
41335
+ totalRecords
41336
+ });
41337
+ for (let i5 = 0; i5 < chunks.length; i5++) {
41338
+ const chunk = chunks[i5];
41339
+ const chunkStartTime = Date.now();
41340
+ try {
41341
+ logger11.debug(`Executing chunk ${i5 + 1}/${chunks.length}`, {
41342
+ chunkIndex: i5,
41343
+ recordCount: chunk.length
41344
+ });
41345
+ const successfulRecords = await executeChunk(chunk);
41346
+ successRecords.push(...successfulRecords);
41347
+ const chunkDuration = Date.now() - chunkStartTime;
41348
+ logger11.info(`Chunk ${i5 + 1}/${chunks.length} succeeded`, {
41349
+ chunkIndex: i5,
41350
+ recordCount: chunk.length,
41351
+ durationMs: chunkDuration
41352
+ });
41353
+ } catch (error2) {
41354
+ const chunkDuration = Date.now() - chunkStartTime;
41355
+ const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
41356
+ const errorCode = getErrorCode(error2);
41357
+ logger11.error(`Chunk ${i5 + 1}/${chunks.length} failed`, {
41358
+ chunkIndex: i5,
41359
+ recordCount: chunk.length,
41360
+ durationMs: chunkDuration,
41361
+ error: errorMessage,
41362
+ errorCode
41363
+ });
41364
+ for (const record of chunk) {
41365
+ const recordId = getRecordId(record);
41366
+ failedIds.push(recordId);
41367
+ errors.push({
41368
+ id: recordId,
41369
+ code: errorCode,
41370
+ message: errorMessage
41371
+ });
41372
+ }
41373
+ }
41374
+ }
41375
+ const totalExecutionTime = Date.now() - executionStartTime;
41376
+ logger11.info("Chunk execution completed", {
41377
+ totalChunks: chunks.length,
41378
+ totalRecords,
41379
+ successCount: successRecords.length,
41380
+ failedCount: failedIds.length,
41381
+ totalExecutionTimeMs: totalExecutionTime,
41382
+ avgTimePerChunkMs: chunks.length > 0 ? Math.round(totalExecutionTime / chunks.length) : 0
41383
+ });
41384
+ if (failedIds.length > 0) {
41385
+ logger11.warn("Partial failure detected in chunk execution", {
41386
+ totalRecords,
41387
+ successCount: successRecords.length,
41388
+ failedCount: failedIds.length,
41389
+ failureRate: `${Math.round(failedIds.length / totalRecords * 100)}%`,
41390
+ failedIds: failedIds.slice(0, 10),
41391
+ // 最初の10件のみログ出力
41392
+ errorSummary: errors.slice(0, 5).map((e5) => ({
41393
+ id: e5.id,
41394
+ code: e5.code,
41395
+ message: e5.message.substring(0, 100)
41396
+ // メッセージを100文字に制限
41397
+ }))
41398
+ });
41399
+ }
41400
+ return {
41401
+ successRecords,
41402
+ failedIds,
41403
+ errors
41404
+ };
41405
+ }
41406
+ function getErrorCode(error2) {
41407
+ if (error2 && typeof error2 === "object") {
41408
+ if ("name" in error2 && typeof error2.name === "string") {
41409
+ return error2.name;
41410
+ }
41411
+ if ("code" in error2 && typeof error2.code === "string") {
41412
+ return error2.code;
41413
+ }
41414
+ }
41415
+ return "TRANSACTION_FAILED";
41416
+ }
41417
+ var logger11, CHUNK_MAX_BYTES;
41418
+ var init_chunking = __esm({
41419
+ "src/server/utils/chunking.ts"() {
41420
+ "use strict";
41421
+ init_shared();
41422
+ logger11 = createLogger({ service: "records-lambda" });
41423
+ CHUNK_MAX_BYTES = 3.5 * 1024 * 1024;
41424
+ __name(estimateRecordBytes, "estimateRecordBytes");
41425
+ __name(calculateChunks, "calculateChunks");
41426
+ __name(executeChunks, "executeChunks");
41427
+ __name(getErrorCode, "getErrorCode");
41428
+ }
41429
+ });
41430
+
41431
+ // src/server/utils/revision.ts
41432
+ function revisionOf(item) {
41433
+ const rev = item[REVISION_ATTRIBUTE];
41434
+ return typeof rev === "number" ? rev : void 0;
41435
+ }
41436
+ function nextRevision(current) {
41437
+ return (current ?? 0) + 1;
41438
+ }
41439
+ function notExistsCondition() {
41440
+ return { ConditionExpression: "attribute_not_exists(PK)" };
41441
+ }
41442
+ function unchangedCondition(revision) {
41443
+ const names = { "#rev": REVISION_ATTRIBUTE };
41444
+ if (revision === void 0) {
41445
+ return {
41446
+ ConditionExpression: "attribute_exists(PK) AND attribute_not_exists(#rev)",
41447
+ ExpressionAttributeNames: names
41448
+ };
41449
+ }
41450
+ return {
41451
+ ConditionExpression: "#rev = :rev",
41452
+ ExpressionAttributeNames: names,
41453
+ ExpressionAttributeValues: { ":rev": revision }
41454
+ };
41455
+ }
41456
+ function isWriteConflict(error2) {
41457
+ if (!error2 || typeof error2 !== "object") return false;
41458
+ const { name, CancellationReasons } = error2;
41459
+ if (name === "TransactionConflictException") return true;
41460
+ if (name !== "TransactionCanceledException" || !Array.isArray(CancellationReasons)) return false;
41461
+ const codes = CancellationReasons.map((r5) => r5?.Code).filter((c5) => c5 && c5 !== "None");
41462
+ return codes.length > 0 && codes.every((c5) => c5 === "ConditionalCheckFailed" || c5 === "TransactionConflict");
41463
+ }
41464
+ function sleep3(ms) {
41465
+ return new Promise((resolve) => setTimeout(resolve, ms));
41466
+ }
41467
+ async function writeWithConflictRetry(initial, write, refresh, baseDelayMs = 20) {
41468
+ let records = initial;
41469
+ for (let attempt = 0; ; attempt++) {
41470
+ try {
41471
+ if (records.length > 0) await write(records);
41472
+ return records;
41473
+ } catch (error2) {
41474
+ if (!isWriteConflict(error2) || attempt >= MAX_CONFLICT_RETRIES) throw error2;
41475
+ await sleep3(baseDelayMs * 2 ** attempt * (0.5 + Math.random() / 2));
41476
+ records = await refresh(records);
41477
+ }
41478
+ }
41479
+ }
41480
+ var REVISION_ATTRIBUTE, MAX_CONFLICT_RETRIES;
41481
+ var init_revision = __esm({
41482
+ "src/server/utils/revision.ts"() {
41483
+ "use strict";
41484
+ REVISION_ATTRIBUTE = "__rev";
41485
+ MAX_CONFLICT_RETRIES = 5;
41486
+ __name(revisionOf, "revisionOf");
41487
+ __name(nextRevision, "nextRevision");
41488
+ __name(notExistsCondition, "notExistsCondition");
41489
+ __name(unchangedCondition, "unchangedCondition");
41490
+ __name(isWriteConflict, "isWriteConflict");
41491
+ __name(sleep3, "sleep");
41492
+ __name(writeWithConflictRetry, "writeWithConflictRetry");
41493
+ }
41494
+ });
41495
+
41458
41496
  // src/server/operations/deleteMany.ts
41459
41497
  var deleteMany_exports = {};
41460
41498
  __export(deleteMany_exports, {
@@ -41466,7 +41504,7 @@ async function handleDeleteMany(resource, params, requestId) {
41466
41504
  let ids;
41467
41505
  let condition;
41468
41506
  if ("ids" in params) {
41469
- ids = params.ids;
41507
+ ids = [...new Set(params.ids)];
41470
41508
  condition = params.condition;
41471
41509
  logger12.debug("Executing deleteMany with ids", {
41472
41510
  requestId,
@@ -41609,7 +41647,7 @@ async function handleDeleteMany(resource, params, requestId) {
41609
41647
  if (transactItems.length === 0) return;
41610
41648
  const result = await executeDynamoDBOperation(
41611
41649
  () => dbClient2.send(
41612
- new import_lib_dynamodb6.TransactWriteCommand({
41650
+ new import_lib_dynamodb7.TransactWriteCommand({
41613
41651
  TransactItems: transactItems,
41614
41652
  ReturnConsumedCapacity: "TOTAL"
41615
41653
  })
@@ -41720,11 +41758,11 @@ async function handleDeleteMany(resource, params, requestId) {
41720
41758
  consumedCapacity: costTracker.getAggregated()
41721
41759
  };
41722
41760
  }
41723
- var import_lib_dynamodb6, logger12;
41761
+ var import_lib_dynamodb7, logger12;
41724
41762
  var init_deleteMany = __esm({
41725
41763
  "src/server/operations/deleteMany.ts"() {
41726
41764
  "use strict";
41727
- import_lib_dynamodb6 = __toESM(require_dist_cjs22(), 1);
41765
+ import_lib_dynamodb7 = __toESM(require_dist_cjs22(), 1);
41728
41766
  init_shared();
41729
41767
  init_shadow();
41730
41768
  init_batchGet();
@@ -41905,56 +41943,6 @@ var init_timestamps = __esm({
41905
41943
  }
41906
41944
  });
41907
41945
 
41908
- // src/server/utils/ttl.ts
41909
- function calculateTTL(resource, createdAt) {
41910
- const envKey = `${resource.toUpperCase()}_TTL_DAYS`;
41911
- const ttlDaysStr = process.env[envKey];
41912
- if (!ttlDaysStr) {
41913
- return void 0;
41914
- }
41915
- const ttlDays = parseInt(ttlDaysStr, 10);
41916
- if (isNaN(ttlDays) || ttlDays <= 0) {
41917
- logger17.warn("Invalid TTL_DAYS value", { resource, envKey, value: ttlDaysStr });
41918
- return void 0;
41919
- }
41920
- const createdAtMs = new Date(createdAt).getTime();
41921
- const ttlMs = createdAtMs + ttlDays * 24 * 60 * 60 * 1e3;
41922
- const ttl = Math.floor(ttlMs / 1e3);
41923
- logger17.debug("TTL calculated", {
41924
- resource,
41925
- ttlDays,
41926
- createdAt,
41927
- ttl,
41928
- ttlDate: new Date(ttl * 1e3).toISOString()
41929
- });
41930
- return ttl;
41931
- }
41932
- function addTTL(resource, recordData) {
41933
- const createdAt = recordData.createdAt;
41934
- if (!createdAt) {
41935
- logger17.warn("createdAt not found, skipping TTL calculation", { resource });
41936
- return recordData;
41937
- }
41938
- const ttl = calculateTTL(resource, createdAt);
41939
- if (ttl === void 0) {
41940
- return recordData;
41941
- }
41942
- return {
41943
- ...recordData,
41944
- ttl
41945
- };
41946
- }
41947
- var logger17;
41948
- var init_ttl = __esm({
41949
- "src/server/utils/ttl.ts"() {
41950
- "use strict";
41951
- init_index2();
41952
- logger17 = createLogger({ service: "records-lambda" });
41953
- __name(calculateTTL, "calculateTTL");
41954
- __name(addTTL, "addTTL");
41955
- }
41956
- });
41957
-
41958
41946
  // src/server/operations/insertMany.ts
41959
41947
  var insertMany_exports = {};
41960
41948
  __export(insertMany_exports, {
@@ -41964,7 +41952,7 @@ async function handleInsertMany(resource, params, requestId) {
41964
41952
  const { data: recordsData } = params;
41965
41953
  const startTime = Date.now();
41966
41954
  const costTracker = new CostTracker();
41967
- logger18.debug("Executing insertMany", {
41955
+ logger17.debug("Executing insertMany", {
41968
41956
  requestId,
41969
41957
  resource,
41970
41958
  count: recordsData.length
@@ -41989,11 +41977,10 @@ async function handleInsertMany(resource, params, requestId) {
41989
41977
  const recordData = recordsData[i5];
41990
41978
  try {
41991
41979
  const id = recordData.id || ulid2();
41992
- let fullRecordData = addCreateTimestamps({
41980
+ const fullRecordData = addCreateTimestamps({
41993
41981
  ...recordData,
41994
41982
  id
41995
41983
  });
41996
- fullRecordData = addTTL(resource, fullRecordData);
41997
41984
  const shadowRecords = generateShadowRecords(fullRecordData, resource, shadowConfig);
41998
41985
  const shadowKeys = shadowRecords.map((shadow) => shadow.SK);
41999
41986
  const mainSK = generateMainRecordSK2(id);
@@ -42007,7 +41994,7 @@ async function handleInsertMany(resource, params, requestId) {
42007
41994
  const failedId = recordData.id || `temp-id-${i5}`;
42008
41995
  const errorMessage = error2 instanceof Error ? error2.message : "Unknown preparation error";
42009
41996
  const errorCode = getPreparationErrorCode(error2);
42010
- logger18.error("Failed to prepare record for creation", {
41997
+ logger17.error("Failed to prepare record for creation", {
42011
41998
  requestId,
42012
41999
  recordId: failedId,
42013
42000
  error: errorMessage,
@@ -42076,7 +42063,7 @@ async function handleInsertMany(resource, params, requestId) {
42076
42063
  }
42077
42064
  const result = await executeDynamoDBOperation(
42078
42065
  () => dbClient2.send(
42079
- new import_lib_dynamodb8.TransactWriteCommand({
42066
+ new import_lib_dynamodb9.TransactWriteCommand({
42080
42067
  TransactItems: transactItems,
42081
42068
  ReturnConsumedCapacity: "TOTAL"
42082
42069
  })
@@ -42201,11 +42188,11 @@ function getPreparationErrorCode(error2) {
42201
42188
  }
42202
42189
  return "VALIDATION_ERROR" /* VALIDATION_ERROR */;
42203
42190
  }
42204
- var import_lib_dynamodb8, logger18;
42191
+ var import_lib_dynamodb9, logger17;
42205
42192
  var init_insertMany = __esm({
42206
42193
  "src/server/operations/insertMany.ts"() {
42207
42194
  "use strict";
42208
- import_lib_dynamodb8 = __toESM(require_dist_cjs22(), 1);
42195
+ import_lib_dynamodb9 = __toESM(require_dist_cjs22(), 1);
42209
42196
  init_shared();
42210
42197
  init_shadow();
42211
42198
  init_shadow();
@@ -42216,8 +42203,7 @@ var init_insertMany = __esm({
42216
42203
  init_dynamodb3();
42217
42204
  init_revision();
42218
42205
  init_timestamps();
42219
- init_ttl();
42220
- logger18 = createLogger({ service: "records-lambda" });
42206
+ logger17 = createLogger({ service: "records-lambda" });
42221
42207
  __name(handleInsertMany, "handleInsertMany");
42222
42208
  __name(getPreparationErrorCode, "getPreparationErrorCode");
42223
42209
  }
@@ -42351,10 +42337,39 @@ function unsetFields(value) {
42351
42337
  }
42352
42338
  return Object.keys(asObject(value, "$unset"));
42353
42339
  }
42340
+ function incFields(value) {
42341
+ const inc = {};
42342
+ for (const [field, amount] of Object.entries(asObject(value, "$inc"))) {
42343
+ if (typeof amount !== "number" || !Number.isFinite(amount)) {
42344
+ throw invalid(`$inc value for "${field}" must be a finite number`);
42345
+ }
42346
+ inc[field] = amount;
42347
+ }
42348
+ return inc;
42349
+ }
42350
+ function readByPath(data, path) {
42351
+ let current = data;
42352
+ for (const key of path.split(".")) {
42353
+ if (typeof current !== "object" || current === null) return void 0;
42354
+ current = current[key];
42355
+ }
42356
+ return current;
42357
+ }
42358
+ function applyInc(data, inc) {
42359
+ const added = {};
42360
+ for (const [field, amount] of Object.entries(inc)) {
42361
+ const current = readByPath(data, field);
42362
+ if (current !== void 0 && current !== null && (typeof current !== "number" || !Number.isFinite(current))) {
42363
+ throw invalid(`Field "${field}" is not a number, $inc cannot be applied`);
42364
+ }
42365
+ added[field] = (current ?? 0) + amount;
42366
+ }
42367
+ return added;
42368
+ }
42354
42369
  function resolveUpdateOperators(data) {
42355
42370
  const operators = Object.keys(data).filter((key) => key.startsWith("$"));
42356
42371
  if (operators.length === 0) {
42357
- return { patch: data, setOnInsert: {}, returned: data };
42372
+ return { patch: data, setOnInsert: {}, inc: {}, returned: data };
42358
42373
  }
42359
42374
  const unsupported = operators.filter((op2) => !SUPPORTED_OPERATORS.includes(op2));
42360
42375
  if (unsupported.length > 0) {
@@ -42370,7 +42385,12 @@ function resolveUpdateOperators(data) {
42370
42385
  }
42371
42386
  patch[field] = null;
42372
42387
  }
42373
- return { patch, setOnInsert: asObject(data.$setOnInsert, "$setOnInsert"), returned: set };
42388
+ const inc = incFields(data.$inc);
42389
+ for (const field of Object.keys(inc)) {
42390
+ if (field in set) throw invalid(`Field "${field}" is in both $set and $inc`);
42391
+ if (field in patch) throw invalid(`Field "${field}" is in both $unset and $inc`);
42392
+ }
42393
+ return { patch, setOnInsert: asObject(data.$setOnInsert, "$setOnInsert"), inc, returned: set };
42374
42394
  }
42375
42395
  function equalityFieldsOf(filter) {
42376
42396
  const fields = {};
@@ -42386,10 +42406,13 @@ var init_updateOperators = __esm({
42386
42406
  "src/server/utils/updateOperators.ts"() {
42387
42407
  "use strict";
42388
42408
  init_shared();
42389
- SUPPORTED_OPERATORS = ["$set", "$setOnInsert", "$unset"];
42409
+ SUPPORTED_OPERATORS = ["$set", "$setOnInsert", "$unset", "$inc"];
42390
42410
  __name(invalid, "invalid");
42391
42411
  __name(asObject, "asObject");
42392
42412
  __name(unsetFields, "unsetFields");
42413
+ __name(incFields, "incFields");
42414
+ __name(readByPath, "readByPath");
42415
+ __name(applyInc, "applyInc");
42393
42416
  __name(resolveUpdateOperators, "resolveUpdateOperators");
42394
42417
  __name(equalityFieldsOf, "equalityFieldsOf");
42395
42418
  }
@@ -42406,7 +42429,7 @@ async function handleUpdateMany(resource, params, requestId) {
42406
42429
  const startTime = Date.now();
42407
42430
  const costTracker = new CostTracker();
42408
42431
  const update = resolveUpdateOperators(patchData);
42409
- logger20.debug("Executing updateMany", {
42432
+ logger19.debug("Executing updateMany", {
42410
42433
  requestId,
42411
42434
  resource,
42412
42435
  upsert
@@ -42414,15 +42437,15 @@ async function handleUpdateMany(resource, params, requestId) {
42414
42437
  let ids;
42415
42438
  let condition;
42416
42439
  if ("ids" in params) {
42417
- ids = params.ids;
42440
+ ids = [...new Set(params.ids)];
42418
42441
  condition = params.condition;
42419
- logger20.debug("Executing updateMany with ids", {
42442
+ logger19.debug("Executing updateMany with ids", {
42420
42443
  requestId,
42421
42444
  resource,
42422
42445
  count: ids.length
42423
42446
  });
42424
42447
  } else {
42425
- logger20.debug("Executing updateMany with filter", {
42448
+ logger19.debug("Executing updateMany with filter", {
42426
42449
  requestId,
42427
42450
  resource,
42428
42451
  filter: params.filter
@@ -42441,7 +42464,7 @@ async function handleUpdateMany(resource, params, requestId) {
42441
42464
  );
42442
42465
  ids = matched.map((item) => item.id);
42443
42466
  condition = params.filter;
42444
- logger20.debug("Found records with filter", {
42467
+ logger19.debug("Found records with filter", {
42445
42468
  requestId,
42446
42469
  resource,
42447
42470
  count: ids.length
@@ -42450,7 +42473,7 @@ async function handleUpdateMany(resource, params, requestId) {
42450
42473
  if (upsert) {
42451
42474
  const newId = ulid2();
42452
42475
  ids = [newId];
42453
- logger20.info("Creating new record with filter (upsert: true)", {
42476
+ logger19.info("Creating new record with filter (upsert: true)", {
42454
42477
  requestId,
42455
42478
  resource,
42456
42479
  newId,
@@ -42489,7 +42512,7 @@ async function handleUpdateMany(resource, params, requestId) {
42489
42512
  );
42490
42513
  const notFoundIds2 = targetIds.filter((id) => !existingIds.has(id));
42491
42514
  if (!upsert && notFoundIds2.length > 0) {
42492
- logger20.warn("Records not found (upsert: false)", {
42515
+ logger19.warn("Records not found (upsert: false)", {
42493
42516
  requestId,
42494
42517
  resource,
42495
42518
  notFoundCount: notFoundIds2.length,
@@ -42498,7 +42521,7 @@ async function handleUpdateMany(resource, params, requestId) {
42498
42521
  });
42499
42522
  }
42500
42523
  if (upsert && notFoundIds2.length > 0) {
42501
- logger20.info("Creating new records (upsert: true)", {
42524
+ logger19.info("Creating new records (upsert: true)", {
42502
42525
  requestId,
42503
42526
  resource,
42504
42527
  notFoundCount: notFoundIds2.length,
@@ -42521,7 +42544,11 @@ async function handleUpdateMany(resource, params, requestId) {
42521
42544
  const oldShadowKeys = item.__shadowKeys ?? existingData.__shadowKeys ?? [];
42522
42545
  const timestampedPatch = addUpdateTimestamp(update.patch);
42523
42546
  const mergedData = applyJsonMergePatch(removeShadowKeys(existingData), timestampedPatch);
42524
- const updatedData = { ...mergedData, id };
42547
+ const added = applyInc(mergedData, update.inc);
42548
+ const updatedData = {
42549
+ ...applyJsonMergePatch(mergedData, added),
42550
+ id
42551
+ };
42525
42552
  const newShadowRecords = generateShadowRecords(updatedData, resource, shadowConfig);
42526
42553
  const newShadowKeys = newShadowRecords.map((shadow) => shadow.SK);
42527
42554
  const mainSK = generateMainRecordSK2(id);
@@ -42532,6 +42559,7 @@ async function handleUpdateMany(resource, params, requestId) {
42532
42559
  newShadowKeys,
42533
42560
  mainSK,
42534
42561
  isNew: false,
42562
+ returned: { ...update.returned, ...added },
42535
42563
  revision: revisionOf(item)
42536
42564
  });
42537
42565
  } catch (error2) {
@@ -42539,7 +42567,7 @@ async function handleUpdateMany(resource, params, requestId) {
42539
42567
  const failedId = existingData.id || "unknown-id";
42540
42568
  const errorMessage = error2 instanceof Error ? error2.message : "Unknown preparation error";
42541
42569
  const errorCode = getPreparationErrorCode2(error2);
42542
- logger20.error("Failed to prepare record for update", {
42570
+ logger19.error("Failed to prepare record for update", {
42543
42571
  requestId,
42544
42572
  recordId: failedId,
42545
42573
  error: errorMessage,
@@ -42557,10 +42585,9 @@ async function handleUpdateMany(resource, params, requestId) {
42557
42585
  const { addCreateTimestamps: addCreateTimestamps2 } = await Promise.resolve().then(() => (init_timestamps(), timestamps_exports));
42558
42586
  for (const id of notFoundIds2) {
42559
42587
  try {
42560
- const mergedData = {
42561
- ...applyJsonMergePatch({}, { ...update.setOnInsert, ...update.patch }),
42562
- id
42563
- };
42588
+ const baseData = applyJsonMergePatch({}, { ...update.setOnInsert, ...update.patch });
42589
+ const added = applyInc(baseData, update.inc);
42590
+ const mergedData = { ...applyJsonMergePatch(baseData, added), id };
42564
42591
  const newData = addCreateTimestamps2(mergedData);
42565
42592
  const newShadowRecords = generateShadowRecords(newData, resource, shadowConfig);
42566
42593
  const newShadowKeys = newShadowRecords.map((shadow) => shadow.SK);
@@ -42572,12 +42599,13 @@ async function handleUpdateMany(resource, params, requestId) {
42572
42599
  // 新規作成なので空
42573
42600
  newShadowKeys,
42574
42601
  mainSK,
42575
- isNew: true
42602
+ isNew: true,
42603
+ returned: { ...update.setOnInsert, ...update.returned, ...added }
42576
42604
  });
42577
42605
  } catch (error2) {
42578
42606
  const errorMessage = error2 instanceof Error ? error2.message : "Unknown preparation error";
42579
42607
  const errorCode = getPreparationErrorCode2(error2);
42580
- logger20.error("Failed to prepare new record for upsert", {
42608
+ logger19.error("Failed to prepare new record for upsert", {
42581
42609
  requestId,
42582
42610
  recordId: id,
42583
42611
  error: errorMessage,
@@ -42660,7 +42688,7 @@ async function handleUpdateMany(resource, params, requestId) {
42660
42688
  }
42661
42689
  const result = await executeDynamoDBOperation(
42662
42690
  () => dbClient2.send(
42663
- new import_lib_dynamodb9.TransactWriteCommand({
42691
+ new import_lib_dynamodb10.TransactWriteCommand({
42664
42692
  TransactItems: transactItems,
42665
42693
  ReturnConsumedCapacity: "TOTAL"
42666
42694
  })
@@ -42679,7 +42707,7 @@ async function handleUpdateMany(resource, params, requestId) {
42679
42707
  const fresh = await prepare(stale.map((record) => record.id));
42680
42708
  if (fresh.preparedRecords.length !== stale.length) {
42681
42709
  throw new AppError(
42682
- "INTERNAL_ERROR" /* INTERNAL_ERROR */,
42710
+ "VERSION_CONFLICT" /* VERSION_CONFLICT */,
42683
42711
  "Records changed concurrently and could not be re-read for update",
42684
42712
  409
42685
42713
  );
@@ -42696,21 +42724,17 @@ async function handleUpdateMany(resource, params, requestId) {
42696
42724
  const failedIdsMap = {};
42697
42725
  const errorsMap = {};
42698
42726
  const successIdSet = new Set(successRecords.map((r5) => r5.id));
42727
+ const returnedById = new Map(successRecords.map((r5) => [r5.id, r5.returned]));
42728
+ const upsertedIds = [];
42699
42729
  for (let i5 = 0; i5 < ids.length; i5++) {
42700
42730
  const id = ids[i5];
42701
42731
  if (successIdSet.has(id)) {
42702
42732
  successIds[i5] = id;
42703
42733
  if (upsert && notFoundIds.includes(id)) {
42704
- items.push({
42705
- id,
42706
- ...update.setOnInsert,
42707
- ...update.returned
42708
- });
42734
+ upsertedIds.push(id);
42735
+ items.push({ id, ...returnedById.get(id) });
42709
42736
  } else {
42710
- items.push({
42711
- id,
42712
- ...update.returned
42713
- });
42737
+ items.push({ id, ...returnedById.get(id) });
42714
42738
  }
42715
42739
  }
42716
42740
  }
@@ -42794,6 +42818,7 @@ async function handleUpdateMany(resource, params, requestId) {
42794
42818
  errors: errorsMap,
42795
42819
  items,
42796
42820
  // 更新したフィールドのみを含むレコード配列(ADR 001)
42821
+ ...upsertedIds.length > 0 && { upsertedIds },
42797
42822
  consumedCapacity: costTracker.getAggregated()
42798
42823
  };
42799
42824
  }
@@ -42808,11 +42833,11 @@ function getPreparationErrorCode2(error2) {
42808
42833
  }
42809
42834
  return "VALIDATION_ERROR" /* VALIDATION_ERROR */;
42810
42835
  }
42811
- var import_lib_dynamodb9, logger20;
42836
+ var import_lib_dynamodb10, logger19;
42812
42837
  var init_updateMany = __esm({
42813
42838
  "src/server/operations/updateMany.ts"() {
42814
42839
  "use strict";
42815
- import_lib_dynamodb9 = __toESM(require_dist_cjs22(), 1);
42840
+ import_lib_dynamodb10 = __toESM(require_dist_cjs22(), 1);
42816
42841
  init_shared();
42817
42842
  init_shadow();
42818
42843
  init_shadow();
@@ -42827,7 +42852,7 @@ var init_updateMany = __esm({
42827
42852
  init_timestamps();
42828
42853
  init_updateOperators();
42829
42854
  init_findAll();
42830
- logger20 = createLogger({ service: "records-lambda" });
42855
+ logger19 = createLogger({ service: "records-lambda" });
42831
42856
  __name(handleUpdateMany, "handleUpdateMany");
42832
42857
  __name(getPreparationErrorCode2, "getPreparationErrorCode");
42833
42858
  }
@@ -42844,10 +42869,115 @@ init_shared();
42844
42869
 
42845
42870
  // src/server/operations/operationDispatcher.ts
42846
42871
  init_shared();
42872
+
42873
+ // src/server/operations/count.ts
42874
+ var import_lib_dynamodb6 = __toESM(require_dist_cjs22(), 1);
42875
+ init_errors();
42876
+ init_cost_tracker();
42877
+ init_dynamodb3();
42878
+ init_keyCondition();
42879
+ init_utils6();
42880
+ init_findAll();
42881
+ function planKeyCountFilters(parsedFilters) {
42882
+ const [first] = parsedFilters;
42883
+ if (!first || first.parsed.field === "id") return void 0;
42884
+ if (!KEY_CONDITION_OPERATORS.has(first.parsed.operator)) return void 0;
42885
+ const second = parsedFilters.length === 2 ? findComplementaryBound(first, parsedFilters) : void 0;
42886
+ if (parsedFilters.length > 1 && !second) return void 0;
42887
+ if (parsedFilters.length > 2) return void 0;
42888
+ const planned = second ? [first, second] : [first];
42889
+ const allExact = planned.every(
42890
+ (f5) => encodeValueForShadowSK(f5.value, f5.parsed.type, f5.parsed.operator).exact
42891
+ );
42892
+ return allExact ? { first, second } : void 0;
42893
+ }
42894
+ __name(planKeyCountFilters, "planKeyCountFilters");
42895
+ async function countByKeyCondition(keyConditionExpression, expressionAttributeValues, costTracker) {
42896
+ const dbClient2 = getDBClient();
42897
+ const tableName = getTableName();
42898
+ let total = 0;
42899
+ let exclusiveStartKey;
42900
+ do {
42901
+ const result = await executeDynamoDBOperation(
42902
+ () => dbClient2.send(
42903
+ new import_lib_dynamodb6.QueryCommand({
42904
+ TableName: tableName,
42905
+ KeyConditionExpression: keyConditionExpression,
42906
+ ExpressionAttributeValues: expressionAttributeValues,
42907
+ Select: "COUNT",
42908
+ ExclusiveStartKey: exclusiveStartKey,
42909
+ ConsistentRead: true,
42910
+ ReturnConsumedCapacity: "TOTAL"
42911
+ })
42912
+ ),
42913
+ "Query"
42914
+ );
42915
+ costTracker.add(result.ConsumedCapacity);
42916
+ total += result.Count ?? 0;
42917
+ exclusiveStartKey = result.LastEvaluatedKey;
42918
+ } while (exclusiveStartKey);
42919
+ return total;
42920
+ }
42921
+ __name(countByKeyCondition, "countByKeyCondition");
42922
+ async function handleCount(resource, params, requestId) {
42923
+ const filter = params.filter ?? {};
42924
+ if (detectNearQuery(filter)) {
42925
+ throw new InvalidFilterError("count does not support $near", { filter });
42926
+ }
42927
+ const parsedFilters = parseFilters(filter);
42928
+ const costTracker = new CostTracker();
42929
+ if (parsedFilters.length === 0) {
42930
+ const count = await countByKeyCondition(
42931
+ "PK = :pk AND begins_with(SK, :skPrefix)",
42932
+ { ":pk": resource, ":skPrefix": "id#" },
42933
+ costTracker
42934
+ );
42935
+ return { count, consumedCapacity: costTracker.getAggregated() };
42936
+ }
42937
+ const plan = planKeyCountFilters(parsedFilters);
42938
+ if (plan) {
42939
+ const { keyConditionExpression, expressionAttributeValues } = buildKeyCondition(
42940
+ resource,
42941
+ plan.first.parsed.field,
42942
+ plan.first,
42943
+ plan.second
42944
+ );
42945
+ const count = await countByKeyCondition(
42946
+ keyConditionExpression,
42947
+ expressionAttributeValues,
42948
+ costTracker
42949
+ );
42950
+ return { count, consumedCapacity: costTracker.getAggregated() };
42951
+ }
42952
+ const items = await findAllByFilter(resource, filter, requestId);
42953
+ return { count: items.length };
42954
+ }
42955
+ __name(handleCount, "handleCount");
42956
+
42957
+ // src/server/operations/operationDispatcher.ts
42847
42958
  init_deleteMany();
42848
42959
 
42849
42960
  // src/server/operations/deleteOne.ts
42850
42961
  init_shared();
42962
+
42963
+ // src/server/utils/bulkError.ts
42964
+ init_shared();
42965
+ function toAppError(error2, fallbackMessage) {
42966
+ const message = error2?.message ?? fallbackMessage;
42967
+ switch (error2?.code) {
42968
+ case "VALIDATION_ERROR" /* VALIDATION_ERROR */:
42969
+ return new AppError("VALIDATION_ERROR" /* VALIDATION_ERROR */, message, 400);
42970
+ case "ITEM_NOT_FOUND" /* ITEM_NOT_FOUND */:
42971
+ return new AppError("ITEM_NOT_FOUND" /* ITEM_NOT_FOUND */, message, 404);
42972
+ case "VERSION_CONFLICT" /* VERSION_CONFLICT */:
42973
+ return new AppError("VERSION_CONFLICT" /* VERSION_CONFLICT */, message, 409);
42974
+ default:
42975
+ return new AppError("INTERNAL_ERROR" /* INTERNAL_ERROR */, message, 500);
42976
+ }
42977
+ }
42978
+ __name(toAppError, "toAppError");
42979
+
42980
+ // src/server/operations/deleteOne.ts
42851
42981
  init_findAll();
42852
42982
  var logger13 = createLogger({ service: "records-lambda" });
42853
42983
  async function handleDeleteOne(resource, params, requestId) {
@@ -42870,11 +43000,7 @@ async function handleDeleteOne(resource, params, requestId) {
42870
43000
  );
42871
43001
  if (deleteManyResult.count === 0) {
42872
43002
  const error2 = Object.values(deleteManyResult.errors || {})[0];
42873
- if (error2) {
42874
- throw new Error(`Failed to delete record: ${error2.message}`);
42875
- } else {
42876
- throw new Error(`Failed to delete record: ${targetId}`);
42877
- }
43003
+ throw toAppError(error2, `Failed to delete record: ${targetId}`);
42878
43004
  }
42879
43005
  return {
42880
43006
  acknowledged: true,
@@ -42901,11 +43027,7 @@ async function handleDeleteOne(resource, params, requestId) {
42901
43027
  ) : await handleDeleteMany2(resource, { ids: [] }, requestId);
42902
43028
  if (deleteManyResult.count === 0) {
42903
43029
  const error2 = Object.values(deleteManyResult.errors || {})[0];
42904
- if (error2) {
42905
- throw new Error(`Failed to delete record: ${error2.message}`);
42906
- } else {
42907
- throw new Error(`No records found matching filter`);
42908
- }
43030
+ throw toAppError(error2 ?? { code: "ITEM_NOT_FOUND" }, "No records found matching filter");
42909
43031
  }
42910
43032
  const deletedId = Object.values(deleteManyResult.successIds || {})[0];
42911
43033
  if (!deletedId) {
@@ -42931,7 +43053,7 @@ init_find();
42931
43053
  init_findMany();
42932
43054
 
42933
43055
  // src/server/operations/findManyReference.ts
42934
- var import_lib_dynamodb7 = __toESM(require_dist_cjs22(), 1);
43056
+ var import_lib_dynamodb8 = __toESM(require_dist_cjs22(), 1);
42935
43057
  init_shared();
42936
43058
  init_shadow();
42937
43059
  init_batchGet();
@@ -42964,7 +43086,7 @@ async function handleFindManyReference(resource, params, requestId) {
42964
43086
  }
42965
43087
  const queryResult = await executeDynamoDBOperation(
42966
43088
  () => dbClient2.send(
42967
- new import_lib_dynamodb7.QueryCommand({
43089
+ new import_lib_dynamodb8.QueryCommand({
42968
43090
  TableName: tableName,
42969
43091
  KeyConditionExpression: "PK = :pk AND begins_with(SK, :skPrefix)",
42970
43092
  ExpressionAttributeValues: {
@@ -43043,9 +43165,9 @@ init_insertMany();
43043
43165
 
43044
43166
  // src/server/operations/insertOne.ts
43045
43167
  init_shared();
43046
- var logger19 = createLogger({ service: "records-lambda" });
43168
+ var logger18 = createLogger({ service: "records-lambda" });
43047
43169
  async function handleInsertOne(resource, params, requestId) {
43048
- logger19.debug("Executing insertOne", {
43170
+ logger18.debug("Executing insertOne", {
43049
43171
  requestId,
43050
43172
  resource
43051
43173
  });
@@ -43059,11 +43181,7 @@ async function handleInsertOne(resource, params, requestId) {
43059
43181
  );
43060
43182
  if (insertManyResult.count === 0) {
43061
43183
  const error2 = Object.values(insertManyResult.errors || {})[0];
43062
- if (error2) {
43063
- throw new Error(`Failed to create record: ${error2.message}`);
43064
- } else {
43065
- throw new Error("Failed to create record");
43066
- }
43184
+ throw toAppError(error2, "Failed to create record");
43067
43185
  }
43068
43186
  const createdId = Object.values(insertManyResult.successIds || {})[0];
43069
43187
  if (!createdId) {
@@ -43071,7 +43189,7 @@ async function handleInsertOne(resource, params, requestId) {
43071
43189
  }
43072
43190
  const { handleFindOne: handleFindOne2 } = await Promise.resolve().then(() => (init_findOne(), findOne_exports));
43073
43191
  const createdRecord = await handleFindOne2(resource, { id: createdId }, requestId);
43074
- logger19.info("insertOne succeeded", {
43192
+ logger18.info("insertOne succeeded", {
43075
43193
  requestId,
43076
43194
  resource,
43077
43195
  id: createdId
@@ -43237,13 +43355,17 @@ init_updateMany();
43237
43355
  // src/server/operations/updateOne.ts
43238
43356
  init_shared();
43239
43357
  init_findAll();
43240
- var logger21 = createLogger({ service: "records-lambda" });
43358
+ var logger20 = createLogger({ service: "records-lambda" });
43359
+ function upsertedIdOf(result, id) {
43360
+ return result.upsertedIds?.includes(id) ? { upsertedId: id } : {};
43361
+ }
43362
+ __name(upsertedIdOf, "upsertedIdOf");
43241
43363
  async function handleUpdateOne(resource, params, requestId) {
43242
43364
  const { data: patchData, options } = params;
43243
43365
  const { handleUpdateMany: handleUpdateMany2 } = await Promise.resolve().then(() => (init_updateMany(), updateMany_exports));
43244
43366
  if ("id" in params) {
43245
43367
  const targetId = params.id;
43246
- logger21.debug("Executing updateOne with id", {
43368
+ logger20.debug("Executing updateOne with id", {
43247
43369
  requestId,
43248
43370
  resource,
43249
43371
  id: targetId,
@@ -43261,14 +43383,7 @@ async function handleUpdateOne(resource, params, requestId) {
43261
43383
  );
43262
43384
  if (updateManyResult.count === 0) {
43263
43385
  const error2 = Object.values(updateManyResult.errors || {})[0];
43264
- if (error2) {
43265
- if (error2.code === "VALIDATION_ERROR" /* VALIDATION_ERROR */) {
43266
- throw new AppError("VALIDATION_ERROR" /* VALIDATION_ERROR */, error2.message ?? "Invalid patch", 400);
43267
- }
43268
- throw new Error(`Failed to update record: ${error2.message}`);
43269
- } else {
43270
- throw new Error(`Failed to update record: ${targetId}`);
43271
- }
43386
+ throw toAppError(error2, `Failed to update record: ${targetId}`);
43272
43387
  }
43273
43388
  if (!updateManyResult.items || updateManyResult.items.length === 0) {
43274
43389
  throw new Error("updateMany did not return items");
@@ -43283,10 +43398,11 @@ async function handleUpdateOne(resource, params, requestId) {
43283
43398
  modifiedCount: 1,
43284
43399
  id: targetId,
43285
43400
  ...updatedItem,
43401
+ ...upsertedIdOf(updateManyResult, targetId),
43286
43402
  consumedCapacity: updateManyResult.consumedCapacity
43287
43403
  };
43288
43404
  } else {
43289
- logger21.debug("Executing updateOne with filter", {
43405
+ logger20.debug("Executing updateOne with filter", {
43290
43406
  requestId,
43291
43407
  resource,
43292
43408
  filter: params.filter,
@@ -43310,14 +43426,10 @@ async function handleUpdateOne(resource, params, requestId) {
43310
43426
  );
43311
43427
  if (updateManyResult.count === 0) {
43312
43428
  const error2 = Object.values(updateManyResult.errors || {})[0];
43313
- if (error2) {
43314
- if (error2.code === "VALIDATION_ERROR" /* VALIDATION_ERROR */) {
43315
- throw new AppError("VALIDATION_ERROR" /* VALIDATION_ERROR */, error2.message ?? "Invalid patch", 400);
43316
- }
43317
- throw new Error(`Failed to update record: ${error2.message}`);
43318
- } else {
43319
- throw new Error(`No records found matching filter`);
43320
- }
43429
+ throw toAppError(
43430
+ error2 ?? { code: "ITEM_NOT_FOUND" /* ITEM_NOT_FOUND */ },
43431
+ "No records found matching filter"
43432
+ );
43321
43433
  }
43322
43434
  if (!updateManyResult.items || updateManyResult.items.length === 0) {
43323
43435
  throw new Error("updateMany did not return items");
@@ -43336,6 +43448,7 @@ async function handleUpdateOne(resource, params, requestId) {
43336
43448
  modifiedCount: 1,
43337
43449
  id: updatedId,
43338
43450
  ...updatedItem,
43451
+ ...upsertedIdOf(updateManyResult, updatedId),
43339
43452
  consumedCapacity: updateManyResult.consumedCapacity
43340
43453
  };
43341
43454
  }
@@ -43343,13 +43456,13 @@ async function handleUpdateOne(resource, params, requestId) {
43343
43456
  __name(handleUpdateOne, "handleUpdateOne");
43344
43457
 
43345
43458
  // src/server/operations/operationDispatcher.ts
43346
- var logger22 = createLogger({
43459
+ var logger21 = createLogger({
43347
43460
  service: "operation-dispatcher",
43348
43461
  level: process.env.LOG_LEVEL || "info"
43349
43462
  });
43350
43463
  async function executeOperation(request2, requestId) {
43351
43464
  const { op: op2, resource } = request2;
43352
- logger22.debug("Executing operation", {
43465
+ logger21.debug("Executing operation", {
43353
43466
  requestId,
43354
43467
  operation: op2,
43355
43468
  resource
@@ -43373,6 +43486,8 @@ async function executeOperation(request2, requestId) {
43373
43486
  request2.params,
43374
43487
  requestId
43375
43488
  );
43489
+ case "count":
43490
+ return await handleCount(resource, request2.params, requestId);
43376
43491
  case "insertOne": {
43377
43492
  const internalParams = convertInsertOneParams(request2.params);
43378
43493
  return await handleInsertOne(resource, internalParams, requestId);
@@ -44602,13 +44717,13 @@ CognitoJwtVerifier.USER_POOL_ID_REGEX = /^(?<region>(?:eusc-[a-z]{2}|[a-z]{2})-(
44602
44717
 
44603
44718
  // src/server/utils/auth.ts
44604
44719
  init_index2();
44605
- var logger23 = createLogger({ service: "records-lambda" });
44720
+ var logger22 = createLogger({ service: "records-lambda" });
44606
44721
  var verifierInstance = null;
44607
44722
  function getVerifier(userPoolId, clientId) {
44608
44723
  if (!verifierInstance) {
44609
- logger23.debug("Creating JWT verifier instance", { userPoolId, clientId });
44724
+ logger22.debug("Creating JWT verifier instance", { userPoolId, clientId });
44610
44725
  if (!clientId) {
44611
- logger23.warn(
44726
+ logger22.warn(
44612
44727
  "COGNITO_CLIENT_ID is not set: JWT audience (aud) verification is DISABLED. Tokens issued to ANY app client of this user pool are accepted. Set cognito_client_id (Terraform) / COGNITO_CLIENT_ID in production. See docs/AUTHORIZATION.md",
44613
44728
  { userPoolId }
44614
44729
  );
@@ -44625,18 +44740,18 @@ function getVerifier(userPoolId, clientId) {
44625
44740
  }
44626
44741
  __name(getVerifier, "getVerifier");
44627
44742
  async function verifyJwt(token, userPoolId, clientId) {
44628
- logger23.debug("Verifying JWT token with signature validation");
44743
+ logger22.debug("Verifying JWT token with signature validation");
44629
44744
  try {
44630
44745
  const verifier = getVerifier(userPoolId, clientId);
44631
44746
  const payload2 = await verifier.verify(token);
44632
- logger23.debug("JWT token verified successfully", {
44747
+ logger22.debug("JWT token verified successfully", {
44633
44748
  sub: payload2.sub,
44634
44749
  email: payload2.email,
44635
44750
  tokenUse: payload2.token_use
44636
44751
  });
44637
44752
  return payload2;
44638
44753
  } catch (error2) {
44639
- logger23.error("JWT verification failed", {
44754
+ logger22.error("JWT verification failed", {
44640
44755
  error: error2 instanceof Error ? error2.message : String(error2)
44641
44756
  });
44642
44757
  let message = "JWT verification failed";
@@ -44677,7 +44792,7 @@ async function verifyAuthHeader(authHeader, userPoolId, clientId) {
44677
44792
  __name(verifyAuthHeader, "verifyAuthHeader");
44678
44793
 
44679
44794
  // src/server/utils/authHandler.ts
44680
- var logger24 = createLogger({
44795
+ var logger23 = createLogger({
44681
44796
  service: "auth-handler",
44682
44797
  level: process.env.LOG_LEVEL || "info"
44683
44798
  });
@@ -44692,7 +44807,7 @@ async function handleAuthentication(event, requestId) {
44692
44807
  }
44693
44808
  __name(handleAuthentication, "handleAuthentication");
44694
44809
  function handleIAMAuthentication(iam, requestId) {
44695
- logger24.info("IAM authenticated request", {
44810
+ logger23.info("IAM authenticated request", {
44696
44811
  requestId,
44697
44812
  userArn: iam.userArn,
44698
44813
  accountId: iam.accountId,
@@ -44707,7 +44822,7 @@ async function handleCognitoAuthentication(authHeader, requestId) {
44707
44822
  throw new Error("COGNITO_USER_POOL_ID environment variable is required");
44708
44823
  }
44709
44824
  const jwtPayload = await verifyAuthHeader(authHeader, userPoolId, clientId);
44710
- logger24.debug("Cognito JWT verified", {
44825
+ logger23.debug("Cognito JWT verified", {
44711
44826
  requestId,
44712
44827
  sub: jwtPayload.sub
44713
44828
  });
@@ -44722,7 +44837,7 @@ init_shared();
44722
44837
  // src/server/utils/responseBuilder.ts
44723
44838
  init_http();
44724
44839
  init_shared();
44725
- var logger25 = createLogger({
44840
+ var logger24 = createLogger({
44726
44841
  service: "response-builder",
44727
44842
  level: process.env.LOG_LEVEL || "info"
44728
44843
  });
@@ -44732,7 +44847,7 @@ function createSuccessResponse(data, requestId) {
44732
44847
  success: true,
44733
44848
  data
44734
44849
  };
44735
- logger25.info("Request succeeded", { requestId });
44850
+ logger24.info("Request succeeded", { requestId });
44736
44851
  return {
44737
44852
  statusCode: HTTP_STATUS.OK,
44738
44853
  headers: {
@@ -44753,7 +44868,7 @@ function createErrorResponse(code, message, statusCode, requestId, logContext) {
44753
44868
  }
44754
44869
  };
44755
44870
  const level = statusCode >= 500 ? "error" : "warn";
44756
- logger25[level]("Request failed", {
44871
+ logger24[level]("Request failed", {
44757
44872
  requestId,
44758
44873
  event: code,
44759
44874
  message,
@@ -44872,14 +44987,14 @@ function parseRequestBody(body) {
44872
44987
  __name(parseRequestBody, "parseRequestBody");
44873
44988
 
44874
44989
  // src/server/handler.ts
44875
- var logger26 = createLogger({
44990
+ var logger25 = createLogger({
44876
44991
  service: "records-lambda",
44877
44992
  level: process.env.LOG_LEVEL || "info"
44878
44993
  });
44879
- logger26.info("Records Lambda started with automatic shadow field detection");
44994
+ logger25.info("Records Lambda started with automatic shadow field detection");
44880
44995
  async function handler(event) {
44881
44996
  const requestId = event.requestContext.requestId;
44882
- logger26.info("Received request", {
44997
+ logger25.info("Received request", {
44883
44998
  requestId,
44884
44999
  method: event.requestContext.http.method,
44885
45000
  path: event.requestContext.http.path
@@ -44889,15 +45004,15 @@ async function handler(event) {
44889
45004
  return createCorsResponse(HTTP_STATUS.OK);
44890
45005
  }
44891
45006
  if (event.requestContext.http.method === "GET" && event.requestContext.http.path === "/version") {
44892
- const version = "1.26.0";
45007
+ const version = "1.27.1";
44893
45008
  return createSuccessResponse({ version, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, requestId);
44894
45009
  }
44895
45010
  if (event.requestContext.http.method !== "POST") {
44896
- throw new Error("Only POST method is allowed");
45011
+ throw new AppError("VALIDATION_ERROR" /* VALIDATION_ERROR */, "Only POST method is allowed", 405);
44897
45012
  }
44898
45013
  await handleAuthentication(event, requestId);
44899
45014
  const request2 = parseRequestBody(event.body);
44900
- logger26.info("Parsed request", {
45015
+ logger25.info("Parsed request", {
44901
45016
  requestId,
44902
45017
  operation: request2.op,
44903
45018
  resource: request2.resource