@cdkd/cli 0.358.3 → 0.358.5

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 (54) hide show
  1. package/dist/{ambient-client-defaults-BN4tRwp9.js → ambient-client-defaults-sV7_Dag9.js} +3 -3
  2. package/dist/{ambient-client-defaults-BN4tRwp9.js.map → ambient-client-defaults-sV7_Dag9.js.map} +1 -1
  3. package/dist/{asg-provider-DHkF4o0Q.js → asg-provider-C8Z9gQh6.js} +6 -6
  4. package/dist/{asg-provider-DHkF4o0Q.js.map → asg-provider-C8Z9gQh6.js.map} +1 -1
  5. package/dist/cli.js +3 -3
  6. package/dist/{custom-resource-runtime-KEMII41H.js → custom-resource-runtime-CFKtxcut.js} +6 -6
  7. package/dist/{custom-resource-runtime-KEMII41H.js.map → custom-resource-runtime-CFKtxcut.js.map} +1 -1
  8. package/dist/{db-associated-roles-0r3NPm7U.js → db-associated-roles-CAqrOMb6.js} +2 -2
  9. package/dist/{db-associated-roles-0r3NPm7U.js.map → db-associated-roles-CAqrOMb6.js.map} +1 -1
  10. package/dist/{delete-started-xsYgmgVh.js → delete-started-nZR1YxYW.js} +4 -4
  11. package/dist/{delete-started-xsYgmgVh.js.map → delete-started-nZR1YxYW.js.map} +1 -1
  12. package/dist/{deploy-engine-2R2hbP5Y.js → deploy-engine-DD0u1ctj.js} +1302 -285
  13. package/dist/deploy-engine-DD0u1ctj.js.map +1 -0
  14. package/dist/{diff-calculator-CIuzHmBn.js → diff-calculator-D6-l89Im.js} +12 -12
  15. package/dist/{diff-calculator-CIuzHmBn.js.map → diff-calculator-D6-l89Im.js.map} +1 -1
  16. package/dist/{ec2-termination-protection-DIdBlUyw.js → ec2-termination-protection-CrZB0URU.js} +6 -6
  17. package/dist/{ec2-termination-protection-DIdBlUyw.js.map → ec2-termination-protection-CrZB0URU.js.map} +1 -1
  18. package/dist/{ecr-uri-DD3r4tU6.js → ecr-uri-97_fu_HH.js} +2 -2
  19. package/dist/{ecr-uri-DD3r4tU6.js.map → ecr-uri-97_fu_HH.js.map} +1 -1
  20. package/dist/{expected-bucket-owner-Cm4q0WEG.js → expected-bucket-owner-DztbSJ4h.js} +2 -2
  21. package/dist/{expected-bucket-owner-Cm4q0WEG.js.map → expected-bucket-owner-DztbSJ4h.js.map} +1 -1
  22. package/dist/{iam-role-provider-DiB7B6vR.js → iam-role-provider-CMtP4Ptf.js} +8 -8
  23. package/dist/{iam-role-provider-DiB7B6vR.js.map → iam-role-provider-CMtP4Ptf.js.map} +1 -1
  24. package/dist/{image-plan-VU9zHTjW.js → image-plan-B9r5-bNi.js} +8 -8
  25. package/dist/{image-plan-VU9zHTjW.js.map → image-plan-B9r5-bNi.js.map} +1 -1
  26. package/dist/index.d.ts +16 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +5 -5
  29. package/dist/{logger-C4kIC51Z.js → logger-D2Z2OHGQ.js} +2 -2
  30. package/dist/{logger-C4kIC51Z.js.map → logger-D2Z2OHGQ.js.map} +1 -1
  31. package/dist/{neptune-provider-CVtiI39K.js → neptune-provider-CXTIUxND.js} +7 -7
  32. package/dist/{neptune-provider-CVtiI39K.js.map → neptune-provider-CXTIUxND.js.map} +1 -1
  33. package/dist/{program-BOR4WbUs.js → program-fQBUrH4s.js} +416 -50
  34. package/dist/program-fQBUrH4s.js.map +1 -0
  35. package/dist/{provider-classes-CwFJ4uJU.js → provider-classes-ZbdmR8mu.js} +1588 -1332
  36. package/dist/provider-classes-ZbdmR8mu.js.map +1 -0
  37. package/dist/{rds-provider-CYCp7gwi.js → rds-provider-DH7JWWZE.js} +10 -10
  38. package/dist/{rds-provider-CYCp7gwi.js.map → rds-provider-DH7JWWZE.js.map} +1 -1
  39. package/dist/{read-replica-DBLr287T.js → read-replica-DPeTyeJe.js} +3 -3
  40. package/dist/{read-replica-DBLr287T.js.map → read-replica-DPeTyeJe.js.map} +1 -1
  41. package/dist/{replacement-rules-DLJ-yZz-.js → replacement-rules-CRiQUpPY.js} +3 -3
  42. package/dist/{replacement-rules-DLJ-yZz-.js.map → replacement-rules-CRiQUpPY.js.map} +1 -1
  43. package/dist/{resource-deadline-j2gItrpv.js → resource-deadline-8W0fpf3B.js} +8 -5
  44. package/dist/{resource-deadline-j2gItrpv.js.map → resource-deadline-8W0fpf3B.js.map} +1 -1
  45. package/dist/{restore-source-guard-BZ5CE9r9.js → restore-source-guard-BFsarBUR.js} +4 -4
  46. package/dist/{restore-source-guard-BZ5CE9r9.js.map → restore-source-guard-BFsarBUR.js.map} +1 -1
  47. package/dist/{run-cli-CWVdMkku.js → run-cli-APX25Mdo.js} +2 -2
  48. package/dist/{run-cli-CWVdMkku.js.map → run-cli-APX25Mdo.js.map} +1 -1
  49. package/dist/{version-D4vZ_aE6.js → version-DiLAo6CH.js} +2 -2
  50. package/dist/{version-D4vZ_aE6.js.map → version-DiLAo6CH.js.map} +1 -1
  51. package/package.json +1 -1
  52. package/dist/deploy-engine-2R2hbP5Y.js.map +0 -1
  53. package/dist/program-BOR4WbUs.js.map +0 -1
  54. package/dist/provider-classes-CwFJ4uJU.js.map +0 -1
@@ -1,21 +1,21 @@
1
- import { a as IamCreateClientCache, i as isEntityAlreadyExists, n as collectInlinePolicyNamesManagedBySiblings, r as iamEntityLeftByThisCreate, t as IAMRoleProvider } from "./iam-role-provider-DiB7B6vR.js";
2
- import { A as configStringRefusal, B as generateResourceName, D as coerceCfnInteger, E as coerceCfnBoolean, F as requireConfigString, J as getCurrentStackName, M as replayWarn, N as requireConfigArray, O as configBooleanRefusal, P as requireConfigObject, U as recordedGeneratedNameKept, V as generateResourceNameWithFallback, Y as isBeforeStateRead, c as VERBOSE_POINTER, d as describeAwsStatusReason, f as isAwsAuthoredFailure, g as verbosePointerTail, h as verbosePointerSentence, j as readConfigString, k as configIntegerRefusal, n as getLogger, p as safeStringify, q as getCurrentStackInstanceId, u as describeAwsFailure, w as generatedNameFor } from "./logger-C4kIC51Z.js";
1
+ import { a as IamCreateClientCache, i as isEntityAlreadyExists, n as collectInlinePolicyNamesManagedBySiblings, r as iamEntityLeftByThisCreate, t as IAMRoleProvider } from "./iam-role-provider-CMtP4Ptf.js";
2
+ import { A as configStringRefusal, B as generateResourceName, D as coerceCfnInteger, E as coerceCfnBoolean, F as requireConfigString, J as getCurrentStackName, M as replayWarn, N as requireConfigArray, O as configBooleanRefusal, P as requireConfigObject, U as recordedGeneratedNameKept, V as generateResourceNameWithFallback, Y as isBeforeStateRead, c as VERBOSE_POINTER, d as describeAwsStatusReason, f as isAwsAuthoredFailure, g as verbosePointerTail, h as verbosePointerSentence, j as readConfigString, k as configIntegerRefusal, n as getLogger, p as safeStringify, q as getCurrentStackInstanceId, u as describeAwsFailure, w as generatedNameFor } from "./logger-D2Z2OHGQ.js";
3
3
  import { d as withApiGatewayPacing, l as s3ClientDefaults, r as getAwsClients } from "./aws-clients-DOkPjjAW.js";
4
- import { D as markReplayMayCollide, E as markNameCollision, F as isAmbiguousOutcomeError, G as markRedactedCause, H as isMarkedNonRetryable, I as isExplicitDenyError, K as wrapMaskedAwsError, M as explicitDenyPolicyKind, O as relayedNameCollision, Q as AccountIdUnavailableError, R as isRetryableTransientError, U as isThrottlingError, V as THROTTLING_ERROR_NAMES, W as markNonRetryable, _ as ResourceUpdateNotSupportedError, at as ProvisioningError, et as CdkdError, i as credentialFingerprint, n as ambientCredentialConfig, r as clientDefaultsFor, t as ambientClientDefaults, x as hasReplayMayCollide, z as isTransientServerError } from "./ambient-client-defaults-BN4tRwp9.js";
5
- import { $ as logGroupProtectionSite, $t as markCreatedBeforeFailure, A as ambiguousAttemptLead, At as compositeIdFormatMessage, B as isPlainImportValue, Bt as isSecretDerivedValue, Ct as renderDisableCommand, D as AmbiguousCreateLatch, Dt as isInterruptedWaitError, E as AMBIGUOUS_LATCH_TTL_MS, F as setBounded, G as remedyLogicalId, H as normalizeAwsTagsToCfn, Ht as maskerOrIdentity, I as withoutServerErrorRetries, It as segmentAfterAnchor, J as assertRegionMatch, K as resolveExplicitPhysicalId, Kt as clearCreatedBeforeFailure, L as VALUE_NOT_SHOWN, Lt as stateOrphanRecordRemedy, M as isInsideWindow, Mt as compositeIdSkipResult, N as replayFollowedAmbiguousAttempt, Nt as logicalIdShown, O as CREATION_DATE_SKEW_MARGIN_MS, Ot as startInterruptWatch, P as replayedSendWindow, Pt as packCompositeId, Q as deleteWithProtectionCompensation, Qt as markAuxiliaryFailure, R as importRemedyCommand, Rt as createMaskedLogSinks, S as readPrincipalLists, St as protectedReplacementAdvice, U as quotedRemedyLogicalId, Ut as withDerivedNameMasks, V as isQuotableImportValue, Vt as maskDeep, W as refusalTypeShown, X as markNotGone, Xt as isAuxiliaryFailure, _n as injectiveKeyPrefix, a as clearOnUpdateRemoval, at as deleteAfterProtectionFlipWithFinalSnapshot, b as holdsSecretDerivedEntry, bt as isAwsCliLiteral, c as removedTemplateKeys, ct as isTerminalDbWaitStatus, dt as isTerminalDeleteFailure, en as markSupersedesEarlierCreate, et as observeThenDisableProtection, ft as protectionFlipKey, g as retractCreatedResource, gn as injectiveKey, hn as withPasteableAwsProfile, ht as ElapsedBudgetRegistry, it as PROTECTION_FLIP_RETRY_WAIT_MS, j as createAttemptKey, jt as compositeIdSeparatorRefusal, k as RecentIdSet, kt as canonicalizeRoute53QueryName, l as withRemovalDefaults, m as reportCreatedResource, mt as ElapsedBudget, n as enclosingDeadlineRemainingMs, q as RESOURCE_NOT_FOUND, rt as userPoolProtectionSite, st as isProceedDbStatus, t as enclosingDeadlineExpired, tt as rdsFamilyProtectionSite, ut as ProtectionFlipRegistry, vt as UNNAMEABLE_ID_CLAUSE, w as recordedPrincipalsRepair, x as onlySecretDerived, xt as pasteableAwsCommand, y as SECRET_DERIVED_READ_LIVE, yt as WITHHELD_AWS_COMMAND, z as isPlainImportJson, zt as createMaskedRetryLogger } from "./resource-deadline-j2gItrpv.js";
6
- import { A as displayStackName, N as plainIdentOr, O as displayIdent, P as safeMsg, S as SECRET_REF_MAX_CODE_POINTS, T as asIsMessage, _ as shellQuote, c as deployReplaceCommand, d as pasteableCommand, j as isPasteableIdent, k as displaySafe, l as hasClauseBreak, m as proseQuoted, o as cdkdRemedy, p as plainOrDescribed, s as commandHole, u as isInertUnquoted, v as withheldTargetClause } from "./version-D4vZ_aE6.js";
7
- import { gt as slowCcOperationTimeoutMs, n as isRefusedByName, r as markDeleteStarted } from "./delete-started-xsYgmgVh.js";
8
- import { a as resolveSecretDerivedPrincipals, i as isResolvableSecretPrincipalList, n as runDestroyForStack, r as holdsUnprovenSecretPrincipalToken, t as canonicalizeIpv4Cidr } from "./program-BOR4WbUs.js";
9
- import { $ as sendTtlWaitingOutRateLimit, $c as withoutSdkUnwiredProperties, $n as canonicalizeIpProtocolValue, Ao as s3BucketDualStackDomainName, At as S3_AUTO_DELETE_OBJECTS_TAG, B as declaredStreamTagsMember, Ct as INDEX_SETTLE_POLL_INTERVAL_MS, Cu as renderAssemblyPathEscape, Dl as renderNestedTemplateTreeDefect, Dt as relayedIndexBusyDelete, Ec as refuseMalformedNestedChildOutputs, El as listNestedTemplateRows, Et as maskedLogger, G as streamDeclaresTags, Gt as chunks, Hc as withheldAccountClause, Ho as parseWebACLArn, I as DynamoDBGlobalTableProvider, Ic as refuseMalformedResourcesForDestroy, Ir as REDACTED_DELETE_ADDRESS_SKIP_REASON, J as streamTagsMatchDeclared, Ja as deleteSkipReason, Jn as siblingOwnedSgRuleIdentities, Jt as withApiLimit, K as streamMemberRefusals, Kl as rewriteTemplateAssetReferences, Ko as outputReferenceProvenanceOf, Kt as isAccessDeniedError, L as STREAM_POLICY_KEY, Lr as isRedactedRecordedValue, Mo as s3BucketWebsiteUrl, Mt as isTruthyCfnBoolean, Oo as s3BucketArn, Ot as waitForIndexesSettled, Pl as decodeListingKey, Q as readTtlSpec, Qa as markWaitAbandoned, Qi as secretNamedAttributeNamesOf, Qn as sgProtocolKey, Qo as getAccountInfo, R as STREAM_TAGS_KEY, Rr as redactedDeleteAddressFields, Si as getStackRecords, Sl as stringifyValue, Ss as toFiniteNumber, St as DELETE_INDEX_WAIT_PROCEED_NOTE, Tl as isAbsoluteAssetPath, Tt as deleteTableWithIndexBusyRetry, U as reverseMapStreamPolicy, Ua as waitForGoneAfterDelete, V as planStreamMemberOps, Va as waitForLambdaFunctionActive, Vc as accountArgs, W as streamDeclaresPolicy, X as isTtlRateLimited, Xc as findSdkUnwiredProperties, Xn as withoutSiblingOwnedSgRules, Xr as getCurrentProducerRegions, Y as isTtlAlreadyDisabled, Ya as withIndeterminateGuard, Z as planTimeToLive, Zn as cfnIngressPortValue, _a as withoutSiblingAttachedArns, _r as reserveStackCreateToken, _t as beginDeleteWait, ao as APPSYNC_APIKEY_ARN_RESOURCE_PATH, at as CONTRIBUTOR_INSIGHTS_KEY, bi as awaitInFlightSibling, bs as isWarmThroughputDecrease, bt as resolveDynamoDbDeleteBudgetClock, bu as describeFileReadFailure, cn as getCurrentNestedStackContext, ct as planContributorInsightsOp, dt as reverseMapIndexContributorInsights, et as planVectorIndexUpdates, ft as reverseMapTableContributorInsights, gt as DYNAMODB_DELETE_POLL_COST_MS, ha as collectPrincipalsAttachingPolicy, hr as earliestDefined, ht as DYNAMODB_DELETE_MIN_RESOURCE_TIMEOUT_MS, in as revertNestedChildFromJournal, io as isSettledInstanceState, it as vectorIndexesShapeDetail, ja as getCurrentResourceSecrets, jo as s3BucketRegionalDomainName, js as passedParameterClassesOf, jt as hasCdkAutoDeleteTag, ko as s3BucketDomainName, kt as ECR_AUTO_DELETE_IMAGES_TAG, ln as withNestedStackContext, lt as planIndexContributorInsightsOps, ma as collectManagedPolicyArnsAttachedBySiblings, mt as DYNAMODB_DELETE_DEADLINE_MARGIN_MS, nt as vectorIndexesForCreate, oo as maskedSecretSegment, ot as contributorInsightsRefusals, pa as collectGroupsAddedBySiblings, pt as stripIndexContributorInsights, q as streamPolicyMatchesDeclared, qt as lookupEachName, rt as vectorIndexesSettled, st as indexDeclaresContributorInsights, t as DeployEngine, tn as getNestedRevertRun, tt as readbackVectorIndexes, ut as readContributorInsightsSpec, va as withoutSiblingOwned, vs as WARM_THROUGHPUT_MEMBERS, vt as compensateRemovedDeletionProtection, wi as replacedDeleteFailureVerdict, wl as findNestedTemplateTreeDefect, wt as TABLE_INDEX_NOUN, wu as resolveAssemblyPath, xs as toCfnInteger, xt as resolveDynamoDbDeleteBudgetMs, xu as displayAssemblyPath, yr as acquireIdempotencyToken, ys as coerceWarmThroughput$1, yt as deleteBudgetKey, z as declaredStreamPolicyMember, zr as redactedDeleteAddressSkip } from "./deploy-engine-2R2hbP5Y.js";
10
- import { _ as isUsableAttemptedName, c as planTagDiff, d as tagMapAsList, f as tagPlanWarning, g as stringifyIfAssigned, h as definedAttributes, i as refuseRestoreFromItself, l as readTagList, m as modifyDbInstanceWhenAvailable, o as DBPROXY_TAGS_WHAT, p as isModifyNotAvailableRefusal, s as DBPROXY_TAG_OPTIONS, u as refuseMalformedDesiredTags } from "./restore-source-guard-BZ5CE9r9.js";
11
- import { A as withRetry, U as timePhase, _ as unchangedBehindSecretReference, a as reDisableInstanceApiTermination, d as markRefusedBeforeApplying, g as onlySecretReferencesDiffer, i as observeThenDisableInstanceApiTermination, l as getPriorAttempts, n as ec2InstanceProtectionSite, o as reEnableInstanceApiTermination, r as isTerminationProtectionPropagationError, s as resolvedResourceTimeoutMs } from "./ec2-termination-protection-DIdBlUyw.js";
4
+ import { D as markReplayMayCollide, E as markNameCollision, F as isAmbiguousOutcomeError, G as markRedactedCause, I as isExplicitDenyError, K as wrapMaskedAwsError, M as explicitDenyPolicyKind, O as relayedNameCollision, Q as AccountIdUnavailableError, R as isRetryableTransientError, U as isThrottlingError, V as THROTTLING_ERROR_NAMES, W as markNonRetryable, _ as ResourceUpdateNotSupportedError, at as ProvisioningError, et as CdkdError, i as credentialFingerprint, n as ambientCredentialConfig, r as clientDefaultsFor, t as ambientClientDefaults, x as hasReplayMayCollide, z as isTransientServerError } from "./ambient-client-defaults-sV7_Dag9.js";
5
+ import { $ as deleteWithProtectionCompensation, $t as markAuxiliaryFailure, A as ambiguousAttemptLead, At as canonicalizeRoute53QueryName, B as isPlainImportValue, Bt as createMaskedRetryLogger, Ct as protectedReplacementAdvice, D as AmbiguousCreateLatch, E as AMBIGUOUS_LATCH_TTL_MS, F as setBounded, Ft as packCompositeId, G as remedyLogicalId, H as normalizeAwsTagsToCfn, Ht as maskDeep, I as withoutServerErrorRetries, J as RESOURCE_NOT_FOUND, K as resolveExplicitPhysicalId, L as VALUE_NOT_SHOWN, Lt as segmentAfterAnchor, M as isInsideWindow, Mt as compositeIdSeparatorRefusal, N as replayFollowedAmbiguousAttempt, Nt as compositeIdSkipResult, O as CREATION_DATE_SKEW_MARGIN_MS, Ot as isInterruptedWaitError, P as replayedSendWindow, Pt as logicalIdShown, R as importRemedyCommand, Rt as stateOrphanRecordRemedy, S as readPrincipalLists, St as pasteableAwsCommand, U as quotedRemedyLogicalId, Ut as maskerOrIdentity, V as isQuotableImportValue, Vt as isSecretDerivedValue, W as refusalTypeShown, Wt as withDerivedNameMasks, Y as assertRegionMatch, Z as markNotGone, Zt as isAuxiliaryFailure, _n as injectiveKey, a as clearOnUpdateRemoval, at as PROTECTION_FLIP_RETRY_WAIT_MS, b as holdsSecretDerivedEntry, bt as WITHHELD_AWS_COMMAND, c as removedTemplateKeys, ct as isProceedDbStatus, dt as ProtectionFlipRegistry, en as markCreatedBeforeFailure, et as logGroupProtectionSite, ft as isTerminalDeleteFailure, g as retractCreatedResource, gn as withPasteableAwsProfile, gt as ElapsedBudgetRegistry, ht as ElapsedBudget, it as userPoolProtectionSite, j as createAttemptKey, jt as compositeIdFormatMessage, k as RecentIdSet, kt as startInterruptWatch, l as withRemovalDefaults, lt as isTerminalDbWaitStatus, m as reportCreatedResource, n as enclosingDeadlineRemainingMs, nt as rdsFamilyProtectionSite, ot as deleteAfterProtectionFlipWithFinalSnapshot, pt as protectionFlipKey, q as DriftReadRefusedError, qt as clearCreatedBeforeFailure, t as enclosingDeadlineExpired, tn as markSupersedesEarlierCreate, tt as observeThenDisableProtection, vn as injectiveKeyPrefix, w as recordedPrincipalsRepair, wt as renderDisableCommand, x as onlySecretDerived, xt as isAwsCliLiteral, y as SECRET_DERIVED_READ_LIVE, yt as UNNAMEABLE_ID_CLAUSE, z as isPlainImportJson, zt as createMaskedLogSinks } from "./resource-deadline-8W0fpf3B.js";
6
+ import { A as displayStackName, N as plainIdentOr, O as displayIdent, P as safeMsg, S as SECRET_REF_MAX_CODE_POINTS, T as asIsMessage, _ as shellQuote, c as deployReplaceCommand, d as pasteableCommand, j as isPasteableIdent, k as displaySafe, l as hasClauseBreak, m as proseQuoted, o as cdkdRemedy, p as plainOrDescribed, s as commandHole, u as isInertUnquoted, v as withheldTargetClause } from "./version-DiLAo6CH.js";
7
+ import { gt as slowCcOperationTimeoutMs, n as isRefusedByName, r as markDeleteStarted } from "./delete-started-nZR1YxYW.js";
8
+ import { _ as warnUnsettledMember, a as resolveSecretDerivedPrincipals, c as SNS_DEFAULT_POLICY_ID, d as efsPolicyMatchesDeclared, f as lambdaPermissionMatchesDeclared, g as settleDeclaredMember, h as reReadUntilSettled, i as isResolvableSecretPrincipalList, l as declaredMemberDocument, m as policyDocumentMatchesDeclared, n as runDestroyForStack, o as KMS_DEFAULT_KEY_POLICY_ID, p as memberReadFailure, r as holdsUnprovenSecretPrincipalToken, s as OWN_WRITE_REREAD_DELAYS_MS, t as canonicalizeIpv4Cidr, u as declaredPolicyDocument, v as attemptedPolicyDocument, y as policyContentKey } from "./program-fQBUrH4s.js";
9
+ import { $ as sendTtlWaitingOutRateLimit, $c as findSdkUnwiredProperties, $n as sgProtocolKey, Al as renderNestedTemplateTreeDefect, At as S3_AUTO_DELETE_OBJECTS_TAG, B as declaredStreamTagsMember, Ci as replacedDeleteFailureVerdict, Cs as isWarmThroughputDecrease, Ct as INDEX_SETTLE_POLL_INTERVAL_MS, Cu as describeFileReadFailure, Dl as findNestedTemplateTreeDefect, Dt as relayedIndexBusyDelete, Du as resolveAssemblyPath, Et as maskedLogger, Eu as renderAssemblyPathEscape, Fo as s3BucketWebsiteUrl, Fr as REDACTED_DELETE_ADDRESS_SKIP_REASON, G as streamDeclaresTags, Gc as withheldAccountClause, Go as parseWebACLArn, Gt as chunks, I as DynamoDBGlobalTableProvider, Ir as isRedactedRecordedValue, J as streamTagsMatchDeclared, Jt as withApiLimit, K as streamMemberRefusals, Ka as waitForGoneAfterDelete, Kt as isAccessDeniedError, L as STREAM_POLICY_KEY, Ll as decodeListingKey, Lr as redactedDeleteAddressFields, Mo as s3BucketDomainName, Mt as isTruthyCfnBoolean, No as s3BucketDualStackDomainName, Ol as isAbsoluteAssetPath, Ot as waitForIndexesSettled, Pa as getCurrentResourceSecrets, Po as s3BucketRegionalDomainName, Ps as passedParameterClassesOf, Q as readTtlSpec, Qa as withIndeterminateGuard, Qn as cfnIngressPortValue, R as STREAM_TAGS_KEY, Rr as redactedDeleteAddressSkip, Ss as coerceWarmThroughput$1, St as DELETE_INDEX_WAIT_PROCEED_NOTE, Tl as stringifyValue, Ts as toFiniteNumber, Tt as deleteTableWithIndexBusyRetry, U as reverseMapStreamPolicy, V as planStreamMemberOps, W as streamDeclaresPolicy, Wa as waitForLambdaFunctionActive, Wc as accountArgs, X as isTtlRateLimited, Xn as siblingOwnedSgRuleIdentities, Y as isTtlAlreadyDisabled, Yl as rewriteTemplateAssetReferences, Yo as outputReferenceProvenanceOf, Yr as getCurrentProducerRegions, Z as planTimeToLive, Za as deleteSkipReason, Zn as withoutSiblingOwnedSgRules, _a as collectManagedPolicyArnsAttachedBySiblings, _r as earliestDefined, _t as beginDeleteWait, at as CONTRIBUTOR_INSIGHTS_KEY, ba as withoutSiblingAttachedArns, bt as resolveDynamoDbDeleteBudgetClock, cn as getCurrentNestedStackContext, co as APPSYNC_APIKEY_ARN_RESOURCE_PATH, cr as calculateResourceDrift, ct as planContributorInsightsOp, dt as reverseMapIndexContributorInsights, er as canonicalizeIpProtocolValue, et as planVectorIndexUpdates, fr as verbatimEchoDriftKeys, ft as reverseMapTableContributorInsights, ga as collectGroupsAddedBySiblings, gt as DYNAMODB_DELETE_POLL_COST_MS, ht as DYNAMODB_DELETE_MIN_RESOURCE_TIMEOUT_MS, in as revertNestedChildFromJournal, it as vectorIndexesShapeDetail, jo as s3BucketArn, jt as hasCdkAutoDeleteTag, kc as refuseMalformedNestedChildOutputs, kl as listNestedTemplateRows, kt as ECR_AUTO_DELETE_IMAGES_TAG, ln as withNestedStackContext, lo as maskedSecretSegment, lt as planIndexContributorInsightsOps, mt as DYNAMODB_DELETE_DEADLINE_MARGIN_MS, nl as withoutSdkUnwiredProperties, nt as vectorIndexesForCreate, ot as contributorInsightsRefusals, pt as stripIndexContributorInsights, q as streamPolicyMatchesDeclared, qt as lookupEachName, rt as vectorIndexesSettled, so as isSettledInstanceState, st as indexDeclaresContributorInsights, t as DeployEngine, ta as secretNamedAttributeNamesOf, tn as getNestedRevertRun, to as markWaitAbandoned, ts as getAccountInfo, tt as readbackVectorIndexes, ut as readContributorInsightsSpec, va as collectPrincipalsAttachingPolicy, vt as compensateRemovedDeletionProtection, ws as toCfnInteger, wt as TABLE_INDEX_NOUN, wu as displayAssemblyPath, xa as withoutSiblingOwned, xi as getStackRecords, xr as acquireIdempotencyToken, xs as WARM_THROUGHPUT_MEMBERS, xt as resolveDynamoDbDeleteBudgetMs, ya as isStoredExpression, yi as awaitInFlightSibling, yr as reserveStackCreateToken, yt as deleteBudgetKey, z as declaredStreamPolicyMember, zc as refuseMalformedResourcesForDestroy } from "./deploy-engine-DD0u1ctj.js";
10
+ import { _ as isUsableAttemptedName, c as planTagDiff, d as tagMapAsList, f as tagPlanWarning, g as stringifyIfAssigned, h as definedAttributes, i as refuseRestoreFromItself, l as readTagList, m as modifyDbInstanceWhenAvailable, o as DBPROXY_TAGS_WHAT, p as isModifyNotAvailableRefusal, s as DBPROXY_TAG_OPTIONS, u as refuseMalformedDesiredTags } from "./restore-source-guard-BFsarBUR.js";
11
+ import { A as withRetry, U as timePhase, _ as unchangedBehindSecretReference, a as reDisableInstanceApiTermination, d as markRefusedBeforeApplying, g as onlySecretReferencesDiffer, i as observeThenDisableInstanceApiTermination, l as getPriorAttempts, n as ec2InstanceProtectionSite, o as reEnableInstanceApiTermination, r as isTerminationProtectionPropagationError, s as resolvedResourceTimeoutMs } from "./ec2-termination-protection-CrZB0URU.js";
12
12
  import { n as canonicalizeRegion, r as derivePartitionAndUrlSuffix } from "./aws-partition-DA0r2sr-.js";
13
13
  import { f as ambientRegion, r as awsEndpointOverrideActive } from "./aws-client-defaults-DAebi99J.js";
14
- import { n as planSubscriptionAttributes } from "./diff-calculator-CIuzHmBn.js";
15
- import { $ as snapshotPassProvenance, At as withoutPhysicalNameCopies, C as passedNoEchoParametersOf, I as markSameGenerationBag, Nt as dynamicReferenceTokens, W as redactForState, Z as recordReferenceProvenanceEntry, a as emrClusterInstancesReplaced, cn as recordAttributeIdCopy, i as ecsServiceLaunchTypeSetOrChanged, it as hasMaskableValues, l as sameLambdaFunctionAddress, mn as carriesSecretMask, n as blockDeviceMappingsDifferOnlyInDeleteOnTermination, o as canonicalLambdaFunctionName, on as recoverMaskedOutput, s as lambdaFunctionNameForMask, sn as physicalNameCopiesOf } from "./replacement-rules-DLJ-yZz-.js";
16
- import { RDSProvider } from "./rds-provider-CYCp7gwi.js";
17
- import { NeptuneProvider } from "./neptune-provider-CVtiI39K.js";
18
- import { ASGProvider } from "./asg-provider-DHkF4o0Q.js";
14
+ import { n as planSubscriptionAttributes } from "./diff-calculator-D6-l89Im.js";
15
+ import { $ as snapshotPassProvenance, At as withoutPhysicalNameCopies, C as passedNoEchoParametersOf, I as markSameGenerationBag, Nt as dynamicReferenceTokens, W as redactForState, Z as recordReferenceProvenanceEntry, a as emrClusterInstancesReplaced, cn as recordAttributeIdCopy, i as ecsServiceLaunchTypeSetOrChanged, it as hasMaskableValues, l as sameLambdaFunctionAddress, mn as carriesSecretMask, n as blockDeviceMappingsDifferOnlyInDeleteOnTermination, o as canonicalLambdaFunctionName, on as recoverMaskedOutput, s as lambdaFunctionNameForMask, sn as physicalNameCopiesOf } from "./replacement-rules-CRiQUpPY.js";
16
+ import { RDSProvider } from "./rds-provider-DH7JWWZE.js";
17
+ import { NeptuneProvider } from "./neptune-provider-CXTIUxND.js";
18
+ import { ASGProvider } from "./asg-provider-C8Z9gQh6.js";
19
19
  import { createHash, randomUUID } from "node:crypto";
20
20
  import { CreateBucketCommand, CreateBucketMetadataConfigurationCommand, DeleteBucketAnalyticsConfigurationCommand, DeleteBucketCommand, DeleteBucketCorsCommand, DeleteBucketEncryptionCommand, DeleteBucketIntelligentTieringConfigurationCommand, DeleteBucketInventoryConfigurationCommand, DeleteBucketLifecycleCommand, DeleteBucketMetadataConfigurationCommand, DeleteBucketMetricsConfigurationCommand, DeleteBucketOwnershipControlsCommand, DeleteBucketPolicyCommand, DeleteBucketReplicationCommand, DeleteBucketTaggingCommand, DeleteBucketWebsiteCommand, DeleteObjectsCommand, GetBucketAbacCommand, GetBucketAccelerateConfigurationCommand, GetBucketCorsCommand, GetBucketEncryptionCommand, GetBucketLifecycleConfigurationCommand, GetBucketLocationCommand, GetBucketLoggingCommand, GetBucketMetadataConfigurationCommand, GetBucketNotificationConfigurationCommand, GetBucketOwnershipControlsCommand, GetBucketPolicyCommand, GetBucketReplicationCommand, GetBucketTaggingCommand, GetBucketVersioningCommand, GetBucketWebsiteCommand, GetObjectCommand, GetObjectLockConfigurationCommand, GetPublicAccessBlockCommand, HeadBucketCommand, ListBucketAnalyticsConfigurationsCommand, ListBucketIntelligentTieringConfigurationsCommand, ListBucketInventoryConfigurationsCommand, ListBucketMetricsConfigurationsCommand, ListBucketsCommand, ListObjectVersionsCommand, ListObjectsV2Command, NoSuchBucket, PutBucketAbacCommand, PutBucketAccelerateConfigurationCommand, PutBucketAnalyticsConfigurationCommand, PutBucketCorsCommand, PutBucketEncryptionCommand, PutBucketIntelligentTieringConfigurationCommand, PutBucketInventoryConfigurationCommand, PutBucketLifecycleConfigurationCommand, PutBucketLoggingCommand, PutBucketMetricsConfigurationCommand, PutBucketNotificationConfigurationCommand, PutBucketOwnershipControlsCommand, PutBucketPolicyCommand, PutBucketReplicationCommand, PutBucketTaggingCommand, PutBucketVersioningCommand, PutBucketWebsiteCommand, PutObjectLockConfigurationCommand, PutPublicAccessBlockCommand, S3Client, UpdateBucketMetadataAnnotationTableConfigurationCommand, UpdateBucketMetadataInventoryTableConfigurationCommand, UpdateBucketMetadataJournalTableConfigurationCommand } from "@aws-sdk/client-s3";
21
21
  import { AddRoleToInstanceProfileCommand, AddUserToGroupCommand, AttachGroupPolicyCommand, AttachRolePolicyCommand, AttachUserPolicyCommand, CreateAccessKeyCommand, CreateGroupCommand, CreateInstanceProfileCommand, CreateLoginProfileCommand, CreatePolicyCommand, CreatePolicyVersionCommand, CreateUserCommand, DeleteAccessKeyCommand, DeleteGroupCommand, DeleteGroupPolicyCommand, DeleteInstanceProfileCommand, DeleteLoginProfileCommand, DeletePolicyCommand, DeletePolicyVersionCommand, DeleteRolePolicyCommand, DeleteUserCommand, DeleteUserPermissionsBoundaryCommand, DeleteUserPolicyCommand, DetachGroupPolicyCommand, DetachRolePolicyCommand, DetachUserPolicyCommand, GetAccessKeyLastUsedCommand, GetGroupCommand, GetGroupPolicyCommand, GetInstanceProfileCommand, GetPolicyCommand, GetPolicyVersionCommand, GetRolePolicyCommand, GetUserCommand, GetUserPolicyCommand, IAMClient, ListAccessKeysCommand, ListAttachedGroupPoliciesCommand, ListAttachedUserPoliciesCommand, ListEntitiesForPolicyCommand, ListGroupPoliciesCommand, ListGroupsForUserCommand, ListPoliciesCommand, ListPolicyTagsCommand, ListPolicyVersionsCommand, ListUserPoliciesCommand, NoSuchEntityException, PutGroupPolicyCommand, PutRolePolicyCommand, PutUserPermissionsBoundaryCommand, PutUserPolicyCommand, RemoveRoleFromInstanceProfileCommand, RemoveUserFromGroupCommand, TagPolicyCommand, TagUserCommand, UntagPolicyCommand, UntagUserCommand, UpdateAccessKeyCommand, UpdateGroupCommand, UpdateLoginProfileCommand, UpdateUserCommand } from "@aws-sdk/client-iam";
@@ -41,7 +41,7 @@ import { CreateWebFunctionEndpointCommand, CreateWebFunctionRevisionCommand, Del
41
41
  import { CreateNetworkConnectorCommand, DeleteNetworkConnectorCommand, GetNetworkConnectorCommand, LambdaCoreClient, ResourceNotFoundException as ResourceNotFoundException$10, UpdateNetworkConnectorCommand } from "@aws-sdk/client-lambda-core";
42
42
  import * as fs from "node:fs";
43
43
  import * as path from "node:path";
44
- import { CreateRepositoryCommand, DeleteLifecyclePolicyCommand, DeleteRepositoryCommand, DeleteRepositoryPolicyCommand, DescribeRepositoriesCommand, ECRClient, GetLifecyclePolicyCommand, LifecyclePolicyNotFoundException, ListTagsForResourceCommand as ListTagsForResourceCommand$9, PutImageScanningConfigurationCommand, PutImageTagMutabilityCommand, PutLifecyclePolicyCommand, RepositoryNotEmptyException, RepositoryNotFoundException, SetRepositoryPolicyCommand, TagResourceCommand as TagResourceCommand$11, UntagResourceCommand as UntagResourceCommand$11 } from "@aws-sdk/client-ecr";
44
+ import { CreateRepositoryCommand, DeleteLifecyclePolicyCommand, DeleteRepositoryCommand, DeleteRepositoryPolicyCommand, DescribeRepositoriesCommand, ECRClient, GetLifecyclePolicyCommand, GetRepositoryPolicyCommand, LifecyclePolicyNotFoundException, ListTagsForResourceCommand as ListTagsForResourceCommand$9, PutImageScanningConfigurationCommand, PutImageTagMutabilityCommand, PutLifecyclePolicyCommand, RepositoryNotEmptyException, RepositoryNotFoundException, RepositoryPolicyNotFoundException, SetRepositoryPolicyCommand, TagResourceCommand as TagResourceCommand$11, UntagResourceCommand as UntagResourceCommand$11 } from "@aws-sdk/client-ecr";
45
45
  import { AddTagsCommand, CreateListenerCommand, CreateLoadBalancerCommand, CreateTargetGroupCommand, DeleteListenerCommand, DeleteLoadBalancerCommand, DeleteTargetGroupCommand, DeregisterTargetsCommand, DescribeCapacityReservationCommand, DescribeListenerAttributesCommand, DescribeListenersCommand, DescribeLoadBalancerAttributesCommand, DescribeLoadBalancersCommand, DescribeTagsCommand, DescribeTargetGroupAttributesCommand, DescribeTargetGroupsCommand, DescribeTargetHealthCommand, ElasticLoadBalancingV2Client, ModifyCapacityReservationCommand, ModifyIpPoolsCommand, ModifyListenerAttributesCommand, ModifyListenerCommand, ModifyLoadBalancerAttributesCommand, ModifyTargetGroupAttributesCommand, ModifyTargetGroupCommand, RegisterTargetsCommand, RemoveTagsCommand, SetIpAddressTypeCommand, SetSecurityGroupsCommand, SetSubnetsCommand, waitUntilLoadBalancerAvailable } from "@aws-sdk/client-elastic-load-balancing-v2";
46
46
  import { CreateAliasCommand, CreateKeyCommand, DeleteAliasCommand, DescribeKeyCommand, DisableKeyCommand, DisableKeyRotationCommand, DisabledException, EnableKeyCommand, EnableKeyRotationCommand, GetKeyPolicyCommand, GetKeyRotationStatusCommand, KMSClient, ListAliasesCommand, ListKeysCommand, ListResourceTagsCommand, NotFoundException as NotFoundException$2, PutKeyPolicyCommand, ScheduleKeyDeletionCommand, TagResourceCommand as TagResourceCommand$12, UntagResourceCommand as UntagResourceCommand$12, UpdateAliasCommand, UpdateKeyDescriptionCommand } from "@aws-sdk/client-kms";
47
47
  import { isDeepStrictEqual } from "node:util";
@@ -236,6 +236,14 @@ async function detachPartialPolicy(logicalId, policyName, attached, sinks, maskS
236
236
  if (failed.length > 0) log.warn(`Failed to detach the partially-created IAM policy ${logicalId} (${v(policyName)}) after its create failed; cdkd has no record of it, so it stays attached and granting until it is removed by hand${withheld && verbosePointerSentence() ? ` (${VERBOSE_POINTER.replace(/\.$/, "")})` : ""}: ${failed.join("; ")}`);
237
237
  }
238
238
 
239
+ // src/provisioning/revert-no-replace.ts
240
+ function isDriftRevert(context) {
241
+ return context?.desiredFromAwsReadback === true;
242
+ }
243
+ function revertReplacementRefusal(resourceType, logicalId, reason) {
244
+ return new ResourceUpdateNotSupportedError(resourceType, logicalId, `${reason}, so reverting it would replace it, and a drift revert never replaces a resource. Nothing was changed; re-deploy with ${deployReplaceCommand()} to replace it`);
245
+ }
246
+
239
247
  // src/provisioning/providers/iam-policy/update.ts
240
248
  async function update$42(logicalId, physicalId, resourceType, properties, previousProperties, context) {
241
249
  const oldPolicyName = physicalId.includes(":") ? physicalId.split(":")[0] : physicalId;
@@ -251,6 +259,7 @@ async function update$42(logicalId, physicalId, resourceType, properties, previo
251
259
  logicalId,
252
260
  options: { maxLength: 64 }
253
261
  }) ? oldPolicyName : derivedPolicyName;
262
+ if (isDriftRevert(context) && newPolicyName !== oldPolicyName) throw revertReplacementRefusal(resourceType, logicalId, "its PolicyName differs from the name the policy is recorded under");
254
263
  const recordedPolicyName = previousProperties["PolicyName"];
255
264
  const oldPolicyNames = [...new Set([oldPolicyName, recordedPolicyName].filter((name) => typeof name === "string" && IAM_POLICY_NAME.test(name)))];
256
265
  const newTargets = readPolicyTargetLists(properties);
@@ -342,7 +351,7 @@ async function update$42(logicalId, physicalId, resourceType, properties, previo
342
351
  }
343
352
  log.debug(`Successfully updated IAM policy ${logicalId}`);
344
353
  return {
345
- physicalId: newPolicyName,
354
+ physicalId: isDriftRevert(context) ? physicalId : newPolicyName,
346
355
  wasReplaced: false,
347
356
  attributes: { PolicyName: newPolicyName }
348
357
  };
@@ -527,48 +536,108 @@ async function deleteImpl$40(logicalId, physicalId, resourceType, properties, co
527
536
  }
528
537
 
529
538
  // src/provisioning/providers/iam-policy/read-state.ts
530
- async function readCurrentState$40(physicalId, _logicalId, _resourceType, properties) {
539
+ const TARGET_READ_CONCURRENCY = 5;
540
+ async function readCurrentState$41(physicalId, _logicalId, _resourceType, properties, context) {
531
541
  if (!properties) return void 0;
532
- if (!properties["PolicyDocument"]) return void 0;
542
+ const policyDocument = properties["PolicyDocument"];
543
+ if (!policyDocument) return void 0;
533
544
  const policyName = physicalId.includes(":") ? physicalId.split(":")[0] : physicalId;
534
545
  const targets = readPolicyTargetLists(properties);
535
546
  if ("malformed" in targets) return void 0;
536
547
  const { roles, groups, users } = targets;
537
- let liveDocument;
538
- try {
539
- if (roles && roles.length > 0) {
540
- const resp = await this.iamClient.send(new GetRolePolicyCommand({
541
- RoleName: roles[0],
542
- PolicyName: policyName
543
- }));
544
- liveDocument = this.decodePolicyDocument(resp.PolicyDocument);
545
- } else if (groups && groups.length > 0) {
546
- const resp = await this.iamClient.send(new GetGroupPolicyCommand({
547
- GroupName: groups[0],
548
- PolicyName: policyName
549
- }));
550
- liveDocument = this.decodePolicyDocument(resp.PolicyDocument);
551
- } else if (users && users.length > 0) {
552
- const resp = await this.iamClient.send(new GetUserPolicyCommand({
553
- UserName: users[0],
554
- PolicyName: policyName
555
- }));
556
- liveDocument = this.decodePolicyDocument(resp.PolicyDocument);
557
- } else return;
558
- } catch (err) {
559
- if (err instanceof NoSuchEntityException) return RESOURCE_NOT_FOUND;
560
- throw err;
548
+ const allTargets = [
549
+ ...(roles ?? []).map((name) => ({
550
+ kind: "role",
551
+ name
552
+ })),
553
+ ...(groups ?? []).map((name) => ({
554
+ kind: "group",
555
+ name
556
+ })),
557
+ ...(users ?? []).map((name) => ({
558
+ kind: "user",
559
+ name
560
+ }))
561
+ ];
562
+ if (allTargets.length === 0) return void 0;
563
+ const readTargets = context?.afterOwnWrite === true ? allTargets.slice(0, 1) : allTargets;
564
+ const readOne = async (target) => {
565
+ try {
566
+ const raw = await getTargetPolicyDocument.call(this, target, policyName);
567
+ return {
568
+ target,
569
+ document: this.decodePolicyDocument(raw)
570
+ };
571
+ } catch (err) {
572
+ if (err instanceof NoSuchEntityException) return {
573
+ target,
574
+ missing: true
575
+ };
576
+ throw err;
577
+ }
578
+ };
579
+ const reads = [];
580
+ for (let i = 0; i < readTargets.length; i += TARGET_READ_CONCURRENCY) reads.push(...await Promise.all(readTargets.slice(i, i + TARGET_READ_CONCURRENCY).map(readOne)));
581
+ const documents = reads.flatMap((r) => "document" in r ? [r.document] : []);
582
+ if (documents.length === 0) return RESOURCE_NOT_FOUND;
583
+ if (!reads.some((r) => "missing" in r) && documents.every((d) => d === void 0)) return void 0;
584
+ const union = context?.driftBaseline !== void 0;
585
+ const unionWalkPaths = verbatimEchoDriftKeys("AWS::IAM::Policy");
586
+ const comparatorEqual = (a, b) => calculateResourceDrift({ PolicyDocument: a }, { PolicyDocument: b }, {
587
+ unionWalkObjects: union,
588
+ unionWalkPaths
589
+ }).length === 0;
590
+ const baseline = context?.driftBaseline?.["PolicyDocument"] !== void 0 ? context.driftBaseline["PolicyDocument"] : parseRecordedDocument(policyDocument);
591
+ let liveDocument = documents[0];
592
+ if (documents.some((d) => !comparatorEqual(liveDocument, d) || !comparatorEqual(d, liveDocument))) {
593
+ if (holdsSecretLeaf(baseline)) throw new DriftReadRefusedError(`the copies of inline policy ${policyName} differ across its principals and its recorded document holds a secret reference, so cdkd cannot tell which copy was edited — inspect each principal's copy by hand`);
594
+ const edited = documents.findIndex((d) => !comparatorEqual(baseline, d));
595
+ if (edited !== -1) liveDocument = documents[edited];
561
596
  }
562
- if (liveDocument === void 0) return void 0;
563
597
  const result = {
564
598
  PolicyName: policyName,
565
599
  PolicyDocument: liveDocument
566
600
  };
567
- if (roles) result["Roles"] = roles;
568
- if (groups) result["Groups"] = groups;
569
- if (users) result["Users"] = users;
601
+ const echo = (kind, names) => {
602
+ const missing = new Set(reads.flatMap((r) => "missing" in r && r.target.kind === kind ? [r.target.name] : []));
603
+ return names.filter((name) => !missing.has(name));
604
+ };
605
+ if (roles) result["Roles"] = echo("role", roles);
606
+ if (groups) result["Groups"] = echo("group", groups);
607
+ if (users) result["Users"] = echo("user", users);
570
608
  return result;
571
609
  }
610
+ async function getTargetPolicyDocument(target, policyName) {
611
+ switch (target.kind) {
612
+ case "role": return (await this.iamClient.send(new GetRolePolicyCommand({
613
+ RoleName: target.name,
614
+ PolicyName: policyName
615
+ }))).PolicyDocument;
616
+ case "group": return (await this.iamClient.send(new GetGroupPolicyCommand({
617
+ GroupName: target.name,
618
+ PolicyName: policyName
619
+ }))).PolicyDocument;
620
+ case "user": return (await this.iamClient.send(new GetUserPolicyCommand({
621
+ UserName: target.name,
622
+ PolicyName: policyName
623
+ }))).PolicyDocument;
624
+ }
625
+ }
626
+ function holdsSecretLeaf(value, depth = 0) {
627
+ if (depth > 64) return true;
628
+ if (typeof value === "string") return isStoredExpression(value);
629
+ if (Array.isArray(value)) return value.some((v) => holdsSecretLeaf(v, depth + 1));
630
+ if (typeof value === "object" && value !== null) return Object.entries(value).some(([k, v]) => holdsSecretLeaf(k, depth + 1) || holdsSecretLeaf(v, depth + 1));
631
+ return false;
632
+ }
633
+ function parseRecordedDocument(recorded) {
634
+ if (typeof recorded !== "string") return recorded;
635
+ try {
636
+ return JSON.parse(recorded);
637
+ } catch {
638
+ return recorded;
639
+ }
640
+ }
572
641
  function decodePolicyDocument(raw) {
573
642
  if (!raw) return void 0;
574
643
  try {
@@ -619,8 +688,8 @@ var IAMPolicyProvider = class {
619
688
  delete(logicalId, physicalId, resourceType, properties, context) {
620
689
  return deleteImpl$40.call(this, logicalId, physicalId, resourceType, properties, context);
621
690
  }
622
- readCurrentState(physicalId, logicalId, resourceType, properties) {
623
- return readCurrentState$40.call(this, physicalId, logicalId, resourceType, properties);
691
+ readCurrentState(physicalId, logicalId, resourceType, properties, context) {
692
+ return readCurrentState$41.call(this, physicalId, logicalId, resourceType, properties, context);
624
693
  }
625
694
  decodePolicyDocument(raw) {
626
695
  return decodePolicyDocument.call(this, raw);
@@ -980,7 +1049,7 @@ async function deleteImpl$39(logicalId, physicalId, resourceType, _properties, c
980
1049
 
981
1050
  // src/provisioning/providers/iam-managed-policy/read-state.ts
982
1051
  const AWS_MANAGED_POLICY_ARN_RE = /^arn:aws[a-z0-9-]*:iam::aws:/;
983
- async function readCurrentState$39(physicalId, _logicalId, _resourceType, properties, context) {
1052
+ async function readCurrentState$40(physicalId, _logicalId, _resourceType, properties, context) {
984
1053
  let policy;
985
1054
  try {
986
1055
  policy = (await this.iamClient.send(new GetPolicyCommand({ PolicyArn: physicalId }))).Policy;
@@ -1128,7 +1197,7 @@ var IAMManagedPolicyProvider = class {
1128
1197
  }
1129
1198
  }
1130
1199
  readCurrentState(physicalId, logicalId, resourceType, properties, context) {
1131
- return readCurrentState$39.call(this, physicalId, logicalId, resourceType, properties, context);
1200
+ return readCurrentState$40.call(this, physicalId, logicalId, resourceType, properties, context);
1132
1201
  }
1133
1202
  import(input) {
1134
1203
  return importImpl$39.call(this, input);
@@ -3018,7 +3087,7 @@ async function readIdIfExists(resourceType, name) {
3018
3087
  if (token === void 0) throw new Error(`IAM returned no ${noun === "user" ? "UserId" : "GroupId"}`);
3019
3088
  return token;
3020
3089
  }
3021
- async function readCurrentState$38(physicalId, logicalId, resourceType, properties, context) {
3090
+ async function readCurrentState$39(physicalId, logicalId, resourceType, properties, context) {
3022
3091
  switch (resourceType) {
3023
3092
  case "AWS::IAM::User": return this.readUserCurrentState(physicalId, properties, context);
3024
3093
  case "AWS::IAM::Group": return this.readGroupCurrentState(physicalId, properties, context);
@@ -3307,7 +3376,7 @@ var IAMUserGroupProvider = class {
3307
3376
  return readIdIfExists.call(this, resourceType, name);
3308
3377
  }
3309
3378
  readCurrentState(physicalId, logicalId, resourceType, properties, context) {
3310
- return readCurrentState$38.call(this, physicalId, logicalId, resourceType, properties, context);
3379
+ return readCurrentState$39.call(this, physicalId, logicalId, resourceType, properties, context);
3311
3380
  }
3312
3381
  readUserCurrentState(physicalId, properties, context) {
3313
3382
  return readUserCurrentState.call(this, physicalId, properties, context);
@@ -6176,8 +6245,49 @@ async function create$38(logicalId, resourceType, properties, context) {
6176
6245
  }
6177
6246
  }
6178
6247
 
6248
+ // src/provisioning/providers/s3-bucket/survivor-identity.ts
6249
+ const UNKNOWN = { kind: "unknown" };
6250
+ async function replacedSurvivorIdentity(physicalId, resourceType, context) {
6251
+ try {
6252
+ if (resourceType !== "AWS::S3::Bucket" || !isPlainBucketName(physicalId)) return UNKNOWN;
6253
+ const want = canonicalizeRegion(context.expectedRegion);
6254
+ if (canonicalizeRegion(await this.getRegion()) !== want) return UNKNOWN;
6255
+ const probe = await this.probeBucketRegion(physicalId);
6256
+ if (probe.kind === "absent") return { kind: "gone" };
6257
+ const started = Date.now();
6258
+ for (let attempt = 0; attempt < 3; attempt++) {
6259
+ if (attempt > 0) {
6260
+ if (Date.now() - started > 6e3) break;
6261
+ await new Promise((r) => setTimeout(r, BUCKET_LIST_IDENTITY_DELAY_MS));
6262
+ }
6263
+ const listed = await this.listOwnedBucket(physicalId);
6264
+ if ("unknown" in listed) return UNKNOWN;
6265
+ if (listed.bucket === void 0) continue;
6266
+ if (probe.kind !== "region") return {
6267
+ kind: "owned",
6268
+ identity: void 0
6269
+ };
6270
+ if (probe.region !== want) return {
6271
+ kind: "foreign",
6272
+ seen: "other-region"
6273
+ };
6274
+ const created = listed.bucket.CreationDate;
6275
+ return {
6276
+ kind: "owned",
6277
+ identity: created instanceof Date && !Number.isNaN(created.getTime()) ? `${want}|${created.toISOString()}` : void 0
6278
+ };
6279
+ }
6280
+ return probe.kind === "region" || probe.kind === "indeterminate" && probe.errorName === "AccessDenied" ? {
6281
+ kind: "foreign",
6282
+ seen: "other-account"
6283
+ } : UNKNOWN;
6284
+ } catch {
6285
+ return UNKNOWN;
6286
+ }
6287
+ }
6288
+
6179
6289
  // src/provisioning/providers/s3-bucket/read-state.ts
6180
- async function readCurrentState$37(physicalId, logicalId, _resourceType, _properties, context) {
6290
+ async function readCurrentState$38(physicalId, logicalId, _resourceType, _properties, context) {
6181
6291
  const headAttempts = context?.afterOwnWrite === true ? 5 : 1;
6182
6292
  for (let attempt = 1;; attempt++) try {
6183
6293
  await this.s3Client.send(new HeadBucketCommand({ Bucket: physicalId }));
@@ -6700,7 +6810,7 @@ var S3BucketProvider = class {
6700
6810
  return canonicalizeDesiredProperties$3.call(this, resourceType, properties);
6701
6811
  }
6702
6812
  readCurrentState(physicalId, logicalId, _resourceType, _properties, context) {
6703
- return readCurrentState$37.call(this, physicalId, logicalId, _resourceType, _properties, context);
6813
+ return readCurrentState$38.call(this, physicalId, logicalId, _resourceType, _properties, context);
6704
6814
  }
6705
6815
  getDriftAbsentMeansDefaultKeys(_resourceType, properties) {
6706
6816
  return getDriftAbsentMeansDefaultKeys.call(this, _resourceType, properties);
@@ -6789,6 +6899,9 @@ var S3BucketProvider = class {
6789
6899
  resourceIdentity(physicalId, resourceType, context) {
6790
6900
  return resourceIdentity$6.call(this, physicalId, resourceType, context);
6791
6901
  }
6902
+ replacedSurvivorIdentity(physicalId, resourceType, context) {
6903
+ return replacedSurvivorIdentity.call(this, physicalId, resourceType, context);
6904
+ }
6792
6905
  generatedCreateName(_resourceType, logicalId, properties) {
6793
6906
  return generatedCreateName$3.call(this, _resourceType, logicalId, properties);
6794
6907
  }
@@ -6844,10 +6957,14 @@ function withoutInsecureTransportDenies(document) {
6844
6957
  };
6845
6958
  const kept = statements.filter((statement) => !isInsecureTransportDeny(statement));
6846
6959
  const dropped = statements.length - kept.length;
6847
- if (dropped === 0 || kept.length === 0) return {
6960
+ if (dropped === 0) return {
6848
6961
  document,
6849
6962
  dropped: 0
6850
6963
  };
6964
+ if (kept.length === 0) return {
6965
+ document: void 0,
6966
+ dropped
6967
+ };
6851
6968
  return {
6852
6969
  document: {
6853
6970
  ...parsed,
@@ -6860,148 +6977,35 @@ function sentPolicyDocument(document) {
6860
6977
  if (!awsEndpointOverrideActive()) return document;
6861
6978
  return withoutInsecureTransportDenies(document).document;
6862
6979
  }
6980
+ function sendsNoPolicy(document) {
6981
+ return document != null && sentPolicyDocument(document) === void 0;
6982
+ }
6863
6983
  function policyDocumentForEmulator(document, resourceType, logicalId) {
6864
6984
  if (!awsEndpointOverrideActive()) return document;
6865
6985
  const { document: sent, dropped } = withoutInsecureTransportDenies(document);
6866
6986
  if (dropped === 0) return document;
6867
6987
  const what = dropped === 1 ? "a Deny statement" : `${dropped} Deny statements`;
6868
- getLogger().warn(safeMsg`--aws-emulator: left ${what} on aws:SecureTransport out of ${logicalId} (${resourceType}): AWS Emulator does not evaluate that key, so the statement would deny every request; on AWS it never matches an HTTPS request. The state record keeps the templated policy.`);
6988
+ const outcome = sent === void 0 ? ", which leaves no statement, so no policy is set" : "";
6989
+ getLogger().warn(safeMsg`--aws-emulator: left ${what} on aws:SecureTransport out of ${logicalId} (${resourceType})${outcome}: AWS Emulator does not evaluate that key, so the statement would deny every request; on AWS it never matches an HTTPS request. The state record keeps the templated policy.`);
6869
6990
  return sent;
6870
6991
  }
6871
6992
  function serializeResourcePolicy(document, resourceType, logicalId) {
6872
6993
  const sent = policyDocumentForEmulator(document, resourceType, logicalId);
6994
+ if (sent === void 0) return void 0;
6873
6995
  return typeof sent === "string" ? sent : JSON.stringify(sent);
6874
6996
  }
6875
6997
 
6876
- // src/provisioning/policy-document-content.ts
6877
- const MASK = "***";
6878
- const PERMANENT_CDKD_CODES = /* @__PURE__ */ new Set(["ROLLBACK_SECRET_TOKEN_SCAN_MISMATCH"]);
6879
- const MARKED_PERMANENT_CODE_PREFIXES = ["INTRINSIC_RESOLUTION_REFUSAL", "ROLLBACK_SECRET_REGION_AMBIGUOUS"];
6880
- const NOT_FOUND_ERROR_NAMES = /* @__PURE__ */ new Set([
6881
- "ResourceNotFoundException",
6882
- "ParameterNotFound",
6883
- "ParameterVersionNotFound"
6884
- ]);
6885
- function holdsUnresolvedValue(document) {
6886
- let root = document;
6887
- if (typeof document === "string") try {
6888
- root = JSON.parse(document);
6889
- } catch {
6890
- root = document;
6891
- }
6892
- const walk = (v) => {
6893
- if (typeof v === "string") return v === MASK || v.includes("{{resolve:");
6894
- if (Array.isArray(v)) return v.some(walk);
6895
- if (v !== null && typeof v === "object") return Object.values(v).some(walk);
6896
- return false;
6897
- };
6898
- return walk(root);
6899
- }
6900
- function isPermanentResolutionError(error) {
6901
- let current = error;
6902
- for (let depth = 0; depth < 5 && current != null; depth++) {
6903
- const e = current;
6904
- if (typeof e.name === "string" && NOT_FOUND_ERROR_NAMES.has(e.name)) return true;
6905
- if (typeof e.code === "string") {
6906
- if (PERMANENT_CDKD_CODES.has(e.code)) return true;
6907
- const code = e.code;
6908
- if (MARKED_PERMANENT_CODE_PREFIXES.some((p) => code.startsWith(p)) && isMarkedNonRetryable(current)) return true;
6909
- }
6910
- if (typeof e.message === "string" && e.message.startsWith("Dynamic reference: ")) return true;
6911
- current = e.cause;
6912
- }
6913
- return false;
6914
- }
6915
- function errorName(error) {
6916
- const name = error?.name;
6917
- return typeof name === "string" && /^[\w.-]{1,128}$/.test(name) ? name : "error";
6918
- }
6919
- async function attemptedPolicyDocument(recorded, resolve) {
6920
- let document = recorded;
6921
- if (resolve) try {
6922
- document = await resolve();
6923
- } catch (error) {
6924
- return isPermanentResolutionError(error) ? {
6925
- kind: "unusable",
6926
- why: "a secret it references does not exist or cannot be used"
6927
- } : {
6928
- kind: "retry",
6929
- errorName: errorName(error)
6930
- };
6931
- }
6932
- if (!(typeof document === "string" && document.length > 0 || document !== null && typeof document === "object")) return {
6933
- kind: "unusable",
6934
- why: "no policy document it attempted is recorded"
6935
- };
6936
- if (holdsUnresolvedValue(document)) return {
6937
- kind: "unusable",
6938
- why: "its policy document still holds a secret reference or masked value"
6939
- };
6940
- return {
6941
- kind: "document",
6942
- document
6943
- };
6944
- }
6945
- const ACCOUNT_ID = /^\d{12}$/;
6946
- const ACCOUNT_ROOT_ARN = /^arn:[a-z-]+:iam::(\d{12}):root$/;
6947
- const LIST_KEYS = [
6948
- "Action",
6949
- "NotAction",
6950
- "Resource",
6951
- "NotResource"
6952
- ];
6953
- const PRINCIPAL_KEYS = ["Principal", "NotPrincipal"];
6954
- function unwrapSingle(value) {
6955
- return Array.isArray(value) && value.length === 1 ? value[0] : value;
6956
- }
6957
- function accountKey(value) {
6958
- if (typeof value !== "string") return value;
6959
- if (ACCOUNT_ID.test(value)) return `account:${value}`;
6960
- const m = ACCOUNT_ROOT_ARN.exec(value);
6961
- return m ? `account:${m[1]}` : value;
6962
- }
6963
- const ANYONE = "anyone:*";
6964
- function normalizePrincipal(principal) {
6965
- if (principal === "*") return ANYONE;
6966
- if (principal === null || typeof principal !== "object" || Array.isArray(principal)) return principal;
6967
- const keys = Object.keys(principal);
6968
- if (keys.length === 1 && keys[0] === "AWS" && unwrapSingle(principal["AWS"]) === "*") return ANYONE;
6969
- const out = {};
6970
- for (const [key, raw] of Object.entries(principal)) out[key] = unwrapSingle(key === "AWS" ? Array.isArray(raw) ? raw.map(accountKey) : accountKey(raw) : raw);
6971
- return out;
6972
- }
6973
- function normalizeStatement(statement) {
6974
- if (statement === null || typeof statement !== "object" || Array.isArray(statement)) return statement;
6975
- const out = { ...statement };
6976
- for (const key of LIST_KEYS) if (Object.prototype.hasOwnProperty.call(out, key)) out[key] = unwrapSingle(out[key]);
6977
- for (const key of PRINCIPAL_KEYS) if (Object.prototype.hasOwnProperty.call(out, key)) out[key] = normalizePrincipal(out[key]);
6978
- return out;
6979
- }
6980
- function canonicalJson$3(value) {
6981
- const sortKeys = (v) => {
6982
- if (Array.isArray(v)) return v.map(sortKeys);
6983
- if (v !== null && typeof v === "object") {
6984
- const out = Object.create(null);
6985
- for (const key of Object.keys(v).sort()) out[key] = sortKeys(v[key]);
6986
- return out;
6987
- }
6988
- return v;
6989
- };
6990
- return JSON.stringify(sortKeys(value));
6998
+ // src/provisioning/s3-bucket-policy-helpers.ts
6999
+ function isS3BucketName(value) {
7000
+ if (value.length < 3 || value.length > 63) return false;
7001
+ if (!/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(value)) return false;
7002
+ if (value.includes("..")) return false;
7003
+ if (value.startsWith("xn--")) return false;
7004
+ if (value.endsWith("-s3alias") || value.endsWith("--ol-s3")) return false;
7005
+ return true;
6991
7006
  }
6992
- function policyContentKey(document) {
6993
- let value = document;
6994
- if (typeof document === "string") try {
6995
- value = JSON.parse(document);
6996
- } catch {
6997
- return `raw:${document}`;
6998
- }
6999
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
7000
- const doc = { ...value };
7001
- if (Object.prototype.hasOwnProperty.call(doc, "Statement")) doc["Statement"] = (Array.isArray(doc["Statement"]) ? doc["Statement"] : [doc["Statement"]]).map(normalizeStatement);
7002
- value = doc;
7003
- }
7004
- return canonicalJson$3(value);
7007
+ function ownPolicyHolder(logicalId, bucketName) {
7008
+ for (const [otherId, record] of getStackRecords()?.live() ?? []) if (otherId !== logicalId && record.resourceType === "AWS::S3::BucketPolicy" && record.physicalId === bucketName) return otherId;
7005
7009
  }
7006
7010
 
7007
7011
  // src/provisioning/providers/s3-bucket-policy-provider.ts
@@ -7062,7 +7066,18 @@ var S3BucketPolicyProvider = class {
7062
7066
  } catch (error) {
7063
7067
  throw this.wrapOperationError("create", logicalId, resourceType, bucketName, error, context?.maskSecrets);
7064
7068
  }
7065
- await this.decideOnExistingPolicy(logicalId, resourceType, bucketName, policyDoc, existing, context?.replayingState === true, mask);
7069
+ await this.decideOnExistingPolicy(logicalId, resourceType, bucketName, policyDoc ?? (typeof policyDocument === "string" ? policyDocument : JSON.stringify(policyDocument)), existing, context?.replayingState === true, mask);
7070
+ if (policyDoc === void 0) {
7071
+ if (existing.kind === "present") try {
7072
+ await this.s3Client.send(new DeleteBucketPolicyCommand({ Bucket: bucketName }));
7073
+ } catch (error) {
7074
+ if (error.name !== "NoSuchBucketPolicy") throw this.wrapOperationError("create", logicalId, resourceType, bucketName, error, context?.maskSecrets);
7075
+ }
7076
+ return {
7077
+ physicalId: bucketName,
7078
+ attributes: {}
7079
+ };
7080
+ }
7066
7081
  try {
7067
7082
  await this.s3Client.send(new PutBucketPolicyCommand({
7068
7083
  Bucket: bucketName,
@@ -7087,7 +7102,12 @@ var S3BucketPolicyProvider = class {
7087
7102
  if (!policyDocument) throw new ProvisioningError(`PolicyDocument is required for S3 bucket policy ${logicalId}`, resourceType, logicalId, physicalId);
7088
7103
  try {
7089
7104
  const policyDoc = serializeResourcePolicy(policyDocument, resourceType, logicalId);
7090
- await this.s3Client.send(new PutBucketPolicyCommand({
7105
+ if (policyDoc === void 0) try {
7106
+ await this.s3Client.send(new DeleteBucketPolicyCommand({ Bucket: bucketName }));
7107
+ } catch (error) {
7108
+ if (error.name !== "NoSuchBucketPolicy") throw error;
7109
+ }
7110
+ else await this.s3Client.send(new PutBucketPolicyCommand({
7091
7111
  Bucket: bucketName,
7092
7112
  Policy: policyDoc
7093
7113
  }));
@@ -7244,7 +7264,10 @@ var S3BucketPolicyProvider = class {
7244
7264
  policyJson = (await this.s3Client.send(new GetBucketPolicyCommand({ Bucket: physicalId }))).Policy;
7245
7265
  } catch (err) {
7246
7266
  if (err instanceof NoSuchBucket) return RESOURCE_NOT_FOUND;
7247
- if (err.name === "NoSuchBucketPolicy") return RESOURCE_NOT_FOUND;
7267
+ if (err.name === "NoSuchBucketPolicy") {
7268
+ if (properties !== void 0 && sendsNoPolicy(properties["PolicyDocument"])) return { ...properties };
7269
+ return RESOURCE_NOT_FOUND;
7270
+ }
7248
7271
  throw err;
7249
7272
  }
7250
7273
  if (!policyJson) return void 0;
@@ -7311,17 +7334,6 @@ var S3BucketPolicyProvider = class {
7311
7334
  throw new Error(`Cannot determine bucket name for ${refusalTypeShown(input.resourceType)} ${logicalIdShown(input.logicalId)}.${knownNote}${bucketNote} Re-run with --resource ${remedyLogicalId(input.logicalId)}=${commandHole("bucketName")} (e.g. my-bucket-12345) to point cdkd at the bucket this policy is attached to.`);
7312
7335
  }
7313
7336
  };
7314
- function isS3BucketName(value) {
7315
- if (value.length < 3 || value.length > 63) return false;
7316
- if (!/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(value)) return false;
7317
- if (value.includes("..")) return false;
7318
- if (value.startsWith("xn--")) return false;
7319
- if (value.endsWith("-s3alias") || value.endsWith("--ol-s3")) return false;
7320
- return true;
7321
- }
7322
- function ownPolicyHolder(logicalId, bucketName) {
7323
- for (const [otherId, record] of getStackRecords()?.live() ?? []) if (otherId !== logicalId && record.resourceType === "AWS::S3::BucketPolicy" && record.physicalId === bucketName) return otherId;
7324
- }
7325
7337
 
7326
7338
  // src/provisioning/providers/sqs-queue-provider.ts
7327
7339
  function serializeRedrivePolicy(value) {
@@ -7664,6 +7676,7 @@ const QUEUE_POLICY_NOT_COMPARED_LEFT_REASON = "the document it attempted is miss
7664
7676
  var SQSQueuePolicyProvider = class {
7665
7677
  sqsClient;
7666
7678
  logger = getLogger().child("SQSQueuePolicyProvider");
7679
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
7667
7680
  handledProperties = /* @__PURE__ */ new Map([["AWS::SQS::QueuePolicy", /* @__PURE__ */ new Set(["Queues", "PolicyDocument"])]]);
7668
7681
  constructor() {
7669
7682
  const awsClients = getAwsClients();
@@ -7682,7 +7695,7 @@ var SQSQueuePolicyProvider = class {
7682
7695
  this.logger.debug(`Setting policy for queue: ${queueUrl}`);
7683
7696
  await this.sqsClient.send(new SetQueueAttributesCommand({
7684
7697
  QueueUrl: queueUrl,
7685
- Attributes: { Policy: policyDoc }
7698
+ Attributes: { Policy: policyDoc ?? "" }
7686
7699
  }));
7687
7700
  applied.push(queueUrl);
7688
7701
  }
@@ -7712,7 +7725,7 @@ var SQSQueuePolicyProvider = class {
7712
7725
  this.logger.debug(`Updating policy for queue: ${queueUrl}`);
7713
7726
  await this.sqsClient.send(new SetQueueAttributesCommand({
7714
7727
  QueueUrl: queueUrl,
7715
- Attributes: { Policy: policyDoc }
7728
+ Attributes: { Policy: policyDoc ?? "" }
7716
7729
  }));
7717
7730
  }
7718
7731
  for (const queueUrl of removed) await this.clearQueuePolicy(queueUrl, resourceType, logicalId, context?.expectedRegion, "pre-update");
@@ -7827,6 +7840,7 @@ var SQSQueuePolicyProvider = class {
7827
7840
  async queuesCarryingDocument(candidates, document, logicalId) {
7828
7841
  const carrying = [];
7829
7842
  if (candidates.length === 0) return carrying;
7843
+ if (sendsNoPolicy(document)) return carrying;
7830
7844
  const reference = policyReference(sentPolicyDocument(document));
7831
7845
  if (reference === void 0) {
7832
7846
  this.logger.warn(safeMsg`The queues ${candidates.join(", ")} listed by ${logicalId} were not checked (no policy document recorded to compare with) and may still carry its policy.`);
@@ -7859,7 +7873,24 @@ var SQSQueuePolicyProvider = class {
7859
7873
  };
7860
7874
  }
7861
7875
  }
7862
- async readCurrentState(physicalId, _logicalId, _resourceType) {
7876
+ async readCurrentState(physicalId, _logicalId, _resourceType, properties, context) {
7877
+ if (properties !== void 0 && sendsNoPolicy(properties["PolicyDocument"])) {
7878
+ const read = await this.readQueuePolicy(physicalId);
7879
+ return read === RESOURCE_NOT_FOUND ? { ...properties } : read;
7880
+ }
7881
+ const declared = context?.afterOwnWrite === true ? declaredPolicyDocument(properties) : void 0;
7882
+ if (declared === void 0) return this.readQueuePolicy(physicalId);
7883
+ const queueCount = splitQueueUrls(physicalId).length;
7884
+ let policies = [];
7885
+ const { answer, settled } = await reReadUntilSettled(() => {
7886
+ policies = [];
7887
+ return this.readQueuePolicy(physicalId, policies);
7888
+ }, (read) => read !== void 0 && read !== RESOURCE_NOT_FOUND && policies.length === queueCount && policies.every((policy) => policyDocumentMatchesDeclared(policy, declared)), this.ownWriteRereadDelaysMs);
7889
+ if (settled) return answer;
7890
+ if (answer !== void 0 && answer !== RESOURCE_NOT_FOUND && answer["Queues"].length === queueCount) return answer;
7891
+ this.logger.debug(safeMsg`No drift baseline captured for queue policy ${physicalId}: a queue still read back no policy after the write`);
7892
+ }
7893
+ async readQueuePolicy(physicalId, policies) {
7863
7894
  const queueUrls = splitQueueUrls(physicalId);
7864
7895
  if (queueUrls.length === 0) return void 0;
7865
7896
  const held = [];
@@ -7878,6 +7909,7 @@ var SQSQueuePolicyProvider = class {
7878
7909
  }
7879
7910
  if (!policyAttr) continue;
7880
7911
  held.push(queueUrl);
7912
+ policies?.push(policyAttr);
7881
7913
  firstPolicy ??= policyAttr;
7882
7914
  }
7883
7915
  if (firstPolicy === void 0) return RESOURCE_NOT_FOUND;
@@ -8386,7 +8418,7 @@ async function deleteImpl$36(logicalId, physicalId, resourceType, _properties, c
8386
8418
  }
8387
8419
 
8388
8420
  // src/provisioning/providers/sns-topic/read-state.ts
8389
- async function readCurrentState$36(physicalId, _logicalId, _resourceType, properties) {
8421
+ async function readCurrentState$37(physicalId, _logicalId, _resourceType, properties) {
8390
8422
  let attrs;
8391
8423
  try {
8392
8424
  attrs = (await this.snsClient.send(new GetTopicAttributesCommand({ TopicArn: physicalId }))).Attributes;
@@ -8557,7 +8589,7 @@ var SNSTopicProvider = class {
8557
8589
  }
8558
8590
  }
8559
8591
  readCurrentState(physicalId, logicalId, resourceType, properties) {
8560
- return readCurrentState$36.call(this, physicalId, logicalId, resourceType, properties);
8592
+ return readCurrentState$37.call(this, physicalId, logicalId, resourceType, properties);
8561
8593
  }
8562
8594
  getDriftUnknownPaths() {
8563
8595
  return [];
@@ -8653,7 +8685,10 @@ var SNSSubscriptionProvider = class {
8653
8685
  async update(logicalId, physicalId, resourceType, properties, _previousProperties, context) {
8654
8686
  this.logger.debug(`Updating SNS subscription ${logicalId}: ${physicalId}`);
8655
8687
  const plan = await this.planInPlaceUpdate(logicalId, physicalId, resourceType, properties, context);
8656
- if (plan === void 0) return this.replace(logicalId, physicalId, resourceType, properties, context);
8688
+ if (!Array.isArray(plan)) {
8689
+ if (isDriftRevert(context)) throw revertReplacementRefusal(resourceType, logicalId, plan.replace);
8690
+ return this.replace(logicalId, physicalId, resourceType, properties, context);
8691
+ }
8657
8692
  const mask = maskerOrIdentity(context?.maskSecrets);
8658
8693
  for (const [name, value] of plan) try {
8659
8694
  await this.snsClient.send(new SetSubscriptionAttributesCommand({
@@ -8673,21 +8708,22 @@ var SNSSubscriptionProvider = class {
8673
8708
  };
8674
8709
  }
8675
8710
  async planInPlaceUpdate(logicalId, physicalId, resourceType, properties, context) {
8676
- if (physicalId === "PendingConfirmation" || physicalId === "pending confirmation") return;
8711
+ if (physicalId === "PendingConfirmation" || physicalId === "pending confirmation") return { replace: "its record names the PendingConfirmation placeholder, not a subscription" };
8677
8712
  let current;
8678
8713
  try {
8679
8714
  current = (await this.snsClient.send(new GetSubscriptionAttributesCommand({ SubscriptionArn: physicalId })))?.Attributes;
8680
8715
  } catch (error) {
8681
- if (error instanceof NotFoundException) return void 0;
8716
+ if (error instanceof NotFoundException) return { replace: "AWS no longer has the subscription" };
8682
8717
  throw this.wrapMaskedAwsCallError(maskerOrIdentity(context?.maskSecrets), error, `Failed to update SNS subscription ${logicalId}: could not read its attributes`, resourceType, logicalId, physicalId);
8683
8718
  }
8684
- if (current === void 0 || current["PendingConfirmation"] === "true") return void 0;
8719
+ if (current === void 0) return { replace: "AWS returned no attributes for it" };
8720
+ if (current["PendingConfirmation"] === "true") return { replace: "the subscription is still PendingConfirmation" };
8685
8721
  for (const field of CREATE_ONLY_FIELDS) {
8686
8722
  const desired = properties[field];
8687
- if (desired !== void 0 && stringifyValue(desired) !== current[field]) return void 0;
8723
+ if (desired !== void 0 && stringifyValue(desired) !== current[field]) return { replace: `its ${field} differs from the live subscription's` };
8688
8724
  }
8689
8725
  const planned = planSubscriptionAttributes(current, properties);
8690
- return planned.kind === "replace" ? void 0 : planned.calls;
8726
+ return planned.kind === "replace" ? { replace: planned.reason } : planned.calls;
8691
8727
  }
8692
8728
  wrapMaskedAwsCallError(mask, error, prefix, resourceType, logicalId, physicalId) {
8693
8729
  const build = (text) => new ProvisioningError(`${prefix}: ${text}`, resourceType, logicalId, physicalId, error instanceof Error ? error : void 0);
@@ -8796,278 +8832,13 @@ function isPendingConfirmationError(error) {
8796
8832
  return error instanceof InvalidParameterException && error.message.toLowerCase().includes("pending confirmation");
8797
8833
  }
8798
8834
 
8799
- // src/provisioning/providers/sns-topic-policy-provider.ts
8800
- const TOPIC_POLICY_UNREADABLE_SKIP_REASON = "the policy of a topic it wrote could not be read, so whether that topic still carries it is unknown";
8801
- const TOPIC_POLICY_UNRESOLVED_DOCUMENT_SKIP_REASON = "the policy document it attempted could not be resolved right now to compare its topics with";
8802
- const TOPIC_POLICY_MISMATCH_LEFT_REASON = "a topic it wrote carries a policy that does not match the document it attempted, so that topic was not reset";
8803
- const TOPIC_POLICY_NOT_COMPARED_LEFT_REASON = "the document it attempted is missing, masked, or references a secret that does not exist or cannot be used, so none of its topics was reset";
8804
- var SNSTopicPolicyProvider = class {
8805
- logger = getLogger().child("SNSTopicPolicyProvider");
8806
- handledProperties = /* @__PURE__ */ new Map([["AWS::SNS::TopicPolicy", /* @__PURE__ */ new Set(["Topics", "PolicyDocument"])]]);
8807
- async create(logicalId, resourceType, properties, context) {
8808
- this.logger.debug(`Creating SNS topic policy ${logicalId}`);
8809
- const topics = properties["Topics"];
8810
- const policyDocument = properties["PolicyDocument"];
8811
- if (!topics || topics.length === 0) throw new ProvisioningError(`Topics is required for SNS topic policy ${logicalId}`, resourceType, logicalId);
8812
- if (!policyDocument) throw new ProvisioningError(`PolicyDocument is required for SNS topic policy ${logicalId}`, resourceType, logicalId);
8813
- const policyDoc = serializeResourcePolicy(policyDocument, resourceType, logicalId);
8814
- const applied = [];
8815
- try {
8816
- for (const topicArn of topics) {
8817
- await this.setTopicPolicy(topicArn, policyDoc);
8818
- applied.push(topicArn);
8819
- }
8820
- this.logger.debug(`Successfully created SNS topic policy ${logicalId}`);
8821
- return {
8822
- physicalId: topics.join(","),
8823
- attributes: {}
8824
- };
8825
- } catch (error) {
8826
- const thrown = this.wrapOperationError("create", logicalId, resourceType, void 0, error, context?.maskSecrets);
8827
- if (applied.length > 0) markCreatedBeforeFailure(thrown, logicalId, resourceType, applied.join(","));
8828
- throw thrown;
8829
- }
8830
- }
8831
- async update(logicalId, physicalId, resourceType, properties, previousProperties, context) {
8832
- this.logger.debug(`Updating SNS topic policy ${logicalId}: ${physicalId}`);
8833
- const topics = properties["Topics"];
8834
- const policyDocument = properties["PolicyDocument"];
8835
- if (!topics || topics.length === 0) throw new ProvisioningError(`Topics is required for SNS topic policy ${logicalId}`, resourceType, logicalId, physicalId);
8836
- if (!policyDocument) throw new ProvisioningError(`PolicyDocument is required for SNS topic policy ${logicalId}`, resourceType, logicalId, physicalId);
8837
- const policyDoc = serializeResourcePolicy(policyDocument, resourceType, logicalId);
8838
- const mask = context?.maskSecrets ?? ((t) => t);
8839
- const written = splitTopicArns(physicalId);
8840
- const listedOnly = await this.topicsCarryingDocument(listedTopics(previousProperties).filter((arn) => !written.includes(arn) && !topics.includes(arn)), previousProperties["PolicyDocument"], logicalId, mask);
8841
- const dropped = written.filter((arn) => !topics.includes(arn));
8842
- const unaddressable = dropped.filter((arn) => !isSnsTopicArn(arn));
8843
- if (unaddressable.length > 0) {
8844
- const message = mask(safeMsg`The recorded id segment(s) ${unaddressable.join(", ")} of ${logicalId} are not topic ARNs; ` + (listedTopics(previousProperties).length > 0 ? "the topics its previous Topics listed were checked instead." : "its previous Topics lists no topic ARN either, so a topic it was attached to may still carry its policy."));
8845
- if (listedTopics(previousProperties).length > 0) this.logger.debug(message);
8846
- else this.logger.warn(message);
8847
- }
8848
- const removed = [...dropped.filter((arn) => isSnsTopicArn(arn)), ...listedOnly];
8849
- try {
8850
- for (const topicArn of topics) await this.setTopicPolicy(topicArn, policyDoc);
8851
- for (const topicArn of removed) await this.resetTopicPolicy(topicArn, resourceType, logicalId, context?.expectedRegion, "not-found", mask);
8852
- this.logger.debug(`Successfully updated SNS topic policy ${logicalId}`);
8853
- return {
8854
- physicalId: topics.join(","),
8855
- wasReplaced: false,
8856
- attributes: {}
8857
- };
8858
- } catch (error) {
8859
- if (error instanceof ProvisioningError) throw error;
8860
- throw this.wrapOperationError("update", logicalId, resourceType, physicalId, error, mask);
8861
- }
8862
- }
8863
- async delete(logicalId, physicalId, resourceType, properties, context) {
8864
- this.logger.debug(`Deleting SNS topic policy ${logicalId}: ${physicalId}`);
8865
- if (context?.failedCreateOrphan === true) return this.deleteFailedCreateOrphan(logicalId, physicalId, resourceType, properties, context);
8866
- const named = splitTopicArns(physicalId);
8867
- if (named.length === 0) throw markNonRetryable(new ProvisioningError(`Failed to delete SNS topic policy ${logicalId}: its physical id is empty, so cdkd changed no topic. Set each topic the policy is attached to back to its default policy by hand, then drop the record with ${stateOrphanRecordRemedy(context, logicalId)}.`, resourceType, logicalId, physicalId));
8868
- const topicArns = named.every((arn) => isSnsTopicArn(arn)) ? named : [.../* @__PURE__ */ new Set([...named.filter((arn) => isSnsTopicArn(arn)), ...listedTopics(properties ?? {})])];
8869
- if (topicArns.length === 0) throw markNonRetryable(new ProvisioningError(`Failed to delete SNS topic policy ${logicalId}: its physical id names no SNS topic ARN and its Topics lists none either, so cdkd changed no topic. Set each topic the policy is attached to back to its default policy by hand, then drop the record with ${stateOrphanRecordRemedy(context, logicalId)}.`, resourceType, logicalId, physicalId));
8870
- let clearedAny = false;
8871
- for (const topicArn of topicArns) try {
8872
- await this.resetTopicPolicy(topicArn, resourceType, logicalId, context?.expectedRegion);
8873
- clearedAny = true;
8874
- } catch (error) {
8875
- const failure = error instanceof ProvisioningError ? error : this.wrapOperationError("delete", logicalId, resourceType, physicalId, error, context?.maskSecrets);
8876
- throw clearedAny ? markDeleteStarted(failure) : failure;
8877
- }
8878
- this.logger.debug(`Successfully deleted SNS topic policy ${logicalId}`);
8879
- }
8880
- async deleteFailedCreateOrphan(logicalId, physicalId, resourceType, properties, context) {
8881
- const named = splitTopicArns(physicalId);
8882
- if (named.length === 0) throw markNonRetryable(new ProvisioningError(`Failed to delete SNS topic policy ${logicalId}: its physical id names no topic`, resourceType, logicalId, physicalId));
8883
- const resolve = context.resolveAttemptedProperties;
8884
- const attempted = await attemptedPolicyDocument(properties?.["PolicyDocument"], resolve && (async () => (await resolve())?.["PolicyDocument"]));
8885
- if (attempted.kind === "retry") {
8886
- this.logger.warn(safeMsg`The policy document ${logicalId} attempted could not be resolved (${attempted.errorName}), so no topic it wrote is reset; the entry is kept for a re-run once that is fixed.`);
8887
- return {
8888
- outcome: "skipped",
8889
- reason: TOPIC_POLICY_UNRESOLVED_DOCUMENT_SKIP_REASON
8890
- };
8891
- }
8892
- if (attempted.kind === "unusable") {
8893
- this.logger.warn(safeMsg`${logicalId} is not reset on any topic it wrote (${attempted.why}); check each by hand and reset its policy where it still grants what ${logicalId} declared: ${named.join(", ")}.`);
8894
- return {
8895
- outcome: "deleted",
8896
- leftInPlace: TOPIC_POLICY_NOT_COMPARED_LEFT_REASON
8897
- };
8898
- }
8899
- const document = attempted.document;
8900
- const reference = policyContentKey(sentPolicyDocument(document));
8901
- const fresh = new Set((context.writtenThisRun ?? []).flatMap((r) => r.resourceType === resourceType && typeof r.physicalId === "string" ? [...splitTopicArns(r.physicalId), ...listedTopics(r.properties !== null && typeof r.properties === "object" ? r.properties : {})] : []));
8902
- let unreadable = false;
8903
- let mismatched = false;
8904
- for (const topicArn of named) {
8905
- if (fresh.has(topicArn)) {
8906
- mismatched = true;
8907
- this.logger.warn(safeMsg`Topic ${topicArn} was written by a TopicPolicy of this deploy, so it is not reset: its policy may not read back current yet; if it still grants what ${logicalId} declared, reset it manually.`);
8908
- continue;
8909
- }
8910
- const current = await this.readPolicyForWidening(topicArn);
8911
- if (current.kind === "gone") {
8912
- const clientRegion = await getAwsClients().sns.config.region();
8913
- assertRegionMatch(clientRegion, context.expectedRegion, resourceType, logicalId, topicArn, "not-found");
8914
- this.logger.debug(safeMsg`Topic ${topicArn} does not exist; nothing to reset`);
8915
- continue;
8916
- }
8917
- if (current.kind === "unreadable") {
8918
- unreadable = true;
8919
- this.logger.warn(safeMsg`Could not read the policy of topic ${topicArn} (${current.reason}), so it is not reset: it may still carry the policy of ${logicalId}.`);
8920
- continue;
8921
- }
8922
- const live = current.kind === "none" ? void 0 : policyContentKey(current.policy);
8923
- if (live === void 0 || live === reference) {
8924
- try {
8925
- await this.resetTopicPolicy(topicArn, resourceType, logicalId, context.expectedRegion);
8926
- } catch (error) {
8927
- if (error instanceof ProvisioningError) throw error;
8928
- throw this.wrapOperationError("delete", logicalId, resourceType, physicalId, error, context.maskSecrets);
8929
- }
8930
- continue;
8931
- }
8932
- const defaultPolicy = defaultTopicPolicy(topicArn);
8933
- if (defaultPolicy !== void 0 && live === policyContentKey(defaultPolicy)) {
8934
- this.logger.debug(safeMsg`Topic ${topicArn} already carries its default policy`);
8935
- continue;
8936
- }
8937
- mismatched = true;
8938
- this.logger.warn(safeMsg`Topic ${topicArn} carries a policy that does not match the document ${logicalId} attempted (a later write, or AWS stored it in another form), so it is not reset; if it still grants what ${logicalId} declared, reset it manually.`);
8939
- }
8940
- if (unreadable) return {
8941
- outcome: "skipped",
8942
- reason: TOPIC_POLICY_UNREADABLE_SKIP_REASON
8943
- };
8944
- if (mismatched) return {
8945
- outcome: "deleted",
8946
- leftInPlace: TOPIC_POLICY_MISMATCH_LEFT_REASON
8947
- };
8948
- }
8949
- wrapOperationError(operation, logicalId, resourceType, physicalId, error, maskSecrets) {
8950
- const mask = maskSecrets ?? ((t) => t);
8951
- const failure = describeAwsFailure(error);
8952
- if (failure.redacted) this.logger.debug(mask(`Failed to ${operation} SNS topic policy ${logicalId}: ${failure.detail}`));
8953
- const cause = error instanceof Error ? error : void 0;
8954
- const wrapped = new ProvisioningError(`Failed to ${operation} SNS topic policy ${logicalId}: ${failure.summary}`, resourceType, logicalId, physicalId, cause);
8955
- return failure.redacted && cause !== void 0 ? markRedactedCause(wrapped) : wrapped;
8956
- }
8957
- async resetTopicPolicy(topicArn, resourceType, logicalId, expectedRegion, phase = "not-found", mask = (t) => t) {
8958
- const defaultPolicy = defaultTopicPolicy(topicArn);
8959
- if (defaultPolicy === void 0) throw new ProvisioningError(`Cannot remove SNS topic policy ${logicalId} from ${topicArn}: not an SNS topic ARN`, resourceType, logicalId, topicArn);
8960
- try {
8961
- await this.setTopicPolicy(topicArn, defaultPolicy);
8962
- this.logger.debug(mask(safeMsg`Reset the policy of topic ${topicArn} to the default`));
8963
- } catch (error) {
8964
- const name = error?.name;
8965
- if (name === "NotFoundException" || name === "NotFound") {
8966
- const clientRegion = await getAwsClients().sns.config.region();
8967
- assertRegionMatch(clientRegion, expectedRegion, resourceType, logicalId, topicArn, phase);
8968
- this.logger.debug(mask(safeMsg`Topic ${topicArn} not found, skipping policy removal`));
8969
- return;
8970
- }
8971
- throw error;
8972
- }
8973
- }
8974
- async topicsCarryingDocument(candidates, document, logicalId, mask) {
8975
- if (candidates.length === 0) return [];
8976
- const sent = sentPolicyDocument(document);
8977
- let reference;
8978
- if (typeof sent === "string" && sent.length > 0) reference = canonicalPolicy(sent);
8979
- else if (sent !== null && typeof sent === "object") reference = canonicalJson$1(sent);
8980
- if (reference === void 0) {
8981
- this.logger.warn(mask(safeMsg`The topics ${candidates.join(", ")} listed by ${logicalId} were not checked (no policy document recorded to compare with) and may still carry its policy.`));
8982
- return [];
8983
- }
8984
- const carrying = [];
8985
- for (const topicArn of candidates) {
8986
- const current = await this.readPolicyForWidening(topicArn);
8987
- if (current.kind === "policy" && canonicalPolicy(current.policy) === reference) carrying.push(topicArn);
8988
- else if (current.kind === "unreadable") this.logger.warn(mask(safeMsg`Could not read the policy of topic ${topicArn} (${current.reason}), so it is not reset: it may still carry the policy of ${logicalId}.`));
8989
- else this.logger.debug(mask(safeMsg`Topic ${topicArn} does not carry the policy of ${logicalId}; left as is`));
8990
- }
8991
- return carrying;
8992
- }
8993
- async readPolicyForWidening(topicArn) {
8994
- try {
8995
- const policy = (await getAwsClients().sns.send(new GetTopicAttributesCommand({ TopicArn: topicArn }))).Attributes?.["Policy"];
8996
- return policy ? {
8997
- kind: "policy",
8998
- policy
8999
- } : { kind: "none" };
9000
- } catch (err) {
9001
- const name = err.name;
9002
- if (name === "NotFoundException" || name === "NotFound") return { kind: "gone" };
9003
- return {
9004
- kind: "unreadable",
9005
- reason: name ?? "error"
9006
- };
9007
- }
9008
- }
9009
- async readCurrentState(physicalId, _logicalId, _resourceType) {
9010
- const topics = physicalId.split(",").filter((t) => t.length > 0);
9011
- if (topics.length === 0) return void 0;
9012
- const firstTopic = topics[0];
9013
- let policyAttr;
9014
- try {
9015
- policyAttr = (await getAwsClients().sns.send(new GetTopicAttributesCommand({ TopicArn: firstTopic }))).Attributes?.["Policy"];
9016
- } catch (err) {
9017
- const e = err;
9018
- if (e.name === "NotFoundException" || e.name === "NotFound") return RESOURCE_NOT_FOUND;
9019
- throw err;
9020
- }
9021
- const result = { Topics: topics };
9022
- if (policyAttr) try {
9023
- result["PolicyDocument"] = JSON.parse(policyAttr);
9024
- } catch {
9025
- result["PolicyDocument"] = policyAttr;
9026
- }
9027
- return result;
9028
- }
9029
- async import(input) {
9030
- if (input.knownPhysicalId && isSnsTopicArnList(input.knownPhysicalId)) return {
9031
- physicalId: input.knownPhysicalId,
9032
- attributes: {}
9033
- };
9034
- const topics = input.properties["Topics"];
9035
- if (Array.isArray(topics) && topics.length > 0) {
9036
- if (topics.every((t) => typeof t === "string" && isSnsTopicArn(t))) return {
9037
- physicalId: topics.join(","),
9038
- attributes: {}
9039
- };
9040
- }
9041
- const knownNote = input.knownPhysicalId ? ` Got knownPhysicalId=${isPlainImportValue(input.knownPhysicalId) ? `'${input.knownPhysicalId}'` : VALUE_NOT_SHOWN} (not a comma-joined list of SNS topic ARNs; CloudFormation returns the policy resource NAME for AWS::SNS::TopicPolicy, which is not the operational identifier).` : "";
9042
- const topicsNote = Array.isArray(topics) && topics.length > 0 ? ` Properties.Topics${isPlainImportJson(topics) ? `=${JSON.stringify(topics)}` : ` ${VALUE_NOT_SHOWN}`} did not resolve to a list of literal topic ARNs (intrinsic-valued entries like {Ref: '<Topic>'} are not resolved at import time).` : " Properties.Topics is missing or empty.";
9043
- throw new Error(`Cannot determine topic ARNs for ${refusalTypeShown(input.resourceType)} ${logicalIdShown(input.logicalId)}.${knownNote}${topicsNote} Re-run with --resource ${remedyLogicalId(input.logicalId)}=${commandHole("comma-joined-topic-ARNs")} (e.g. arn:aws:sns:${isPasteableIdent(input.region) ? input.region : commandHole("region")}:'<account>':'<topic-name>') to point cdkd at the topic(s) this policy is attached to.`);
9044
- }
9045
- async setTopicPolicy(topicArn, policyDoc) {
9046
- await getAwsClients().sns.send(new SetTopicAttributesCommand({
9047
- TopicArn: topicArn,
9048
- AttributeName: "Policy",
9049
- AttributeValue: policyDoc
9050
- }));
9051
- }
9052
- };
8835
+ // src/provisioning/sns-default-topic-policy.ts
8836
+ function isSnsDefaultPolicy(document) {
8837
+ return typeof document === "object" && document !== null && document["Id"] === "__default_policy_ID";
8838
+ }
9053
8839
  function isSnsTopicArn(value) {
9054
8840
  return /^arn:[a-z0-9-]+:sns:[a-z0-9-]+:\d{12}:[\w.-]+$/.test(value);
9055
8841
  }
9056
- function isSnsTopicArnList(value) {
9057
- const segments = value.split(",");
9058
- if (segments.length === 0) return false;
9059
- return segments.every((s) => isSnsTopicArn(s));
9060
- }
9061
- function splitTopicArns(physicalId) {
9062
- return physicalId.split(",").filter((arn) => arn.length > 0);
9063
- }
9064
- function listedTopics(bag) {
9065
- const listed = bag["Topics"];
9066
- if (!Array.isArray(listed)) return [];
9067
- const out = [];
9068
- for (const entry of listed) if (typeof entry === "string" && isSnsTopicArn(entry) && !out.includes(entry)) out.push(entry);
9069
- return out;
9070
- }
9071
8842
  function defaultTopicPolicy(topicArn) {
9072
8843
  if (!isSnsTopicArn(topicArn)) return void 0;
9073
8844
  const account = topicArn.split(":")[4];
@@ -9093,6 +8864,300 @@ function defaultTopicPolicy(topicArn) {
9093
8864
  }]
9094
8865
  });
9095
8866
  }
8867
+ function defaultTopicPolicyOrThrow(topicArn, resourceType, logicalId) {
8868
+ const defaultPolicy = defaultTopicPolicy(topicArn);
8869
+ if (defaultPolicy === void 0) throw new ProvisioningError(`Cannot set SNS topic policy ${logicalId} on ${topicArn}: not an SNS topic ARN`, resourceType, logicalId, topicArn);
8870
+ return defaultPolicy;
8871
+ }
8872
+
8873
+ // src/provisioning/providers/sns-topic-policy-provider.ts
8874
+ const TOPIC_POLICY_UNREADABLE_SKIP_REASON = "the policy of a topic it wrote could not be read, so whether that topic still carries it is unknown";
8875
+ const TOPIC_POLICY_UNRESOLVED_DOCUMENT_SKIP_REASON = "the policy document it attempted could not be resolved right now to compare its topics with";
8876
+ const TOPIC_POLICY_MISMATCH_LEFT_REASON = "a topic it wrote carries a policy that does not match the document it attempted, so that topic was not reset";
8877
+ const TOPIC_POLICY_NOT_COMPARED_LEFT_REASON = "the document it attempted is missing, masked, or references a secret that does not exist or cannot be used, so none of its topics was reset";
8878
+ var SNSTopicPolicyProvider = class {
8879
+ logger = getLogger().child("SNSTopicPolicyProvider");
8880
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
8881
+ handledProperties = /* @__PURE__ */ new Map([["AWS::SNS::TopicPolicy", /* @__PURE__ */ new Set(["Topics", "PolicyDocument"])]]);
8882
+ async create(logicalId, resourceType, properties, context) {
8883
+ this.logger.debug(`Creating SNS topic policy ${logicalId}`);
8884
+ const topics = properties["Topics"];
8885
+ const policyDocument = properties["PolicyDocument"];
8886
+ if (!topics || topics.length === 0) throw new ProvisioningError(`Topics is required for SNS topic policy ${logicalId}`, resourceType, logicalId);
8887
+ if (!policyDocument) throw new ProvisioningError(`PolicyDocument is required for SNS topic policy ${logicalId}`, resourceType, logicalId);
8888
+ const policyDoc = serializeResourcePolicy(policyDocument, resourceType, logicalId);
8889
+ const applied = [];
8890
+ try {
8891
+ for (const topicArn of topics) {
8892
+ await this.setTopicPolicy(topicArn, policyDoc ?? defaultTopicPolicyOrThrow(topicArn, resourceType, logicalId));
8893
+ applied.push(topicArn);
8894
+ }
8895
+ this.logger.debug(`Successfully created SNS topic policy ${logicalId}`);
8896
+ return {
8897
+ physicalId: topics.join(","),
8898
+ attributes: {}
8899
+ };
8900
+ } catch (error) {
8901
+ const thrown = this.wrapOperationError("create", logicalId, resourceType, void 0, error, context?.maskSecrets);
8902
+ if (applied.length > 0) markCreatedBeforeFailure(thrown, logicalId, resourceType, applied.join(","));
8903
+ throw thrown;
8904
+ }
8905
+ }
8906
+ async update(logicalId, physicalId, resourceType, properties, previousProperties, context) {
8907
+ this.logger.debug(`Updating SNS topic policy ${logicalId}: ${physicalId}`);
8908
+ const topics = properties["Topics"];
8909
+ const policyDocument = properties["PolicyDocument"];
8910
+ if (!topics || topics.length === 0) throw new ProvisioningError(`Topics is required for SNS topic policy ${logicalId}`, resourceType, logicalId, physicalId);
8911
+ if (!policyDocument) throw new ProvisioningError(`PolicyDocument is required for SNS topic policy ${logicalId}`, resourceType, logicalId, physicalId);
8912
+ const policyDoc = serializeResourcePolicy(policyDocument, resourceType, logicalId);
8913
+ const mask = context?.maskSecrets ?? ((t) => t);
8914
+ const written = splitTopicArns(physicalId);
8915
+ const listedOnly = await this.topicsCarryingDocument(listedTopics(previousProperties).filter((arn) => !written.includes(arn) && !topics.includes(arn)), previousProperties["PolicyDocument"], logicalId, mask);
8916
+ const dropped = written.filter((arn) => !topics.includes(arn));
8917
+ const unaddressable = dropped.filter((arn) => !isSnsTopicArn(arn));
8918
+ if (unaddressable.length > 0) {
8919
+ const message = mask(safeMsg`The recorded id segment(s) ${unaddressable.join(", ")} of ${logicalId} are not topic ARNs; ` + (listedTopics(previousProperties).length > 0 ? "the topics its previous Topics listed were checked instead." : "its previous Topics lists no topic ARN either, so a topic it was attached to may still carry its policy."));
8920
+ if (listedTopics(previousProperties).length > 0) this.logger.debug(message);
8921
+ else this.logger.warn(message);
8922
+ }
8923
+ const removed = [...dropped.filter((arn) => isSnsTopicArn(arn)), ...listedOnly];
8924
+ try {
8925
+ for (const topicArn of topics) await this.setTopicPolicy(topicArn, policyDoc ?? defaultTopicPolicyOrThrow(topicArn, resourceType, logicalId));
8926
+ for (const topicArn of removed) await this.resetTopicPolicy(topicArn, resourceType, logicalId, context?.expectedRegion, "not-found", mask);
8927
+ this.logger.debug(`Successfully updated SNS topic policy ${logicalId}`);
8928
+ return {
8929
+ physicalId: topics.join(","),
8930
+ wasReplaced: false,
8931
+ attributes: {}
8932
+ };
8933
+ } catch (error) {
8934
+ if (error instanceof ProvisioningError) throw error;
8935
+ throw this.wrapOperationError("update", logicalId, resourceType, physicalId, error, mask);
8936
+ }
8937
+ }
8938
+ async delete(logicalId, physicalId, resourceType, properties, context) {
8939
+ this.logger.debug(`Deleting SNS topic policy ${logicalId}: ${physicalId}`);
8940
+ if (context?.failedCreateOrphan === true) return this.deleteFailedCreateOrphan(logicalId, physicalId, resourceType, properties, context);
8941
+ const named = splitTopicArns(physicalId);
8942
+ if (named.length === 0) throw markNonRetryable(new ProvisioningError(`Failed to delete SNS topic policy ${logicalId}: its physical id is empty, so cdkd changed no topic. Set each topic the policy is attached to back to its default policy by hand, then drop the record with ${stateOrphanRecordRemedy(context, logicalId)}.`, resourceType, logicalId, physicalId));
8943
+ const topicArns = named.every((arn) => isSnsTopicArn(arn)) ? named : [.../* @__PURE__ */ new Set([...named.filter((arn) => isSnsTopicArn(arn)), ...listedTopics(properties ?? {})])];
8944
+ if (topicArns.length === 0) throw markNonRetryable(new ProvisioningError(`Failed to delete SNS topic policy ${logicalId}: its physical id names no SNS topic ARN and its Topics lists none either, so cdkd changed no topic. Set each topic the policy is attached to back to its default policy by hand, then drop the record with ${stateOrphanRecordRemedy(context, logicalId)}.`, resourceType, logicalId, physicalId));
8945
+ let clearedAny = false;
8946
+ for (const topicArn of topicArns) try {
8947
+ await this.resetTopicPolicy(topicArn, resourceType, logicalId, context?.expectedRegion);
8948
+ clearedAny = true;
8949
+ } catch (error) {
8950
+ const failure = error instanceof ProvisioningError ? error : this.wrapOperationError("delete", logicalId, resourceType, physicalId, error, context?.maskSecrets);
8951
+ throw clearedAny ? markDeleteStarted(failure) : failure;
8952
+ }
8953
+ this.logger.debug(`Successfully deleted SNS topic policy ${logicalId}`);
8954
+ }
8955
+ async deleteFailedCreateOrphan(logicalId, physicalId, resourceType, properties, context) {
8956
+ const named = splitTopicArns(physicalId);
8957
+ if (named.length === 0) throw markNonRetryable(new ProvisioningError(`Failed to delete SNS topic policy ${logicalId}: its physical id names no topic`, resourceType, logicalId, physicalId));
8958
+ const resolve = context.resolveAttemptedProperties;
8959
+ const attempted = await attemptedPolicyDocument(properties?.["PolicyDocument"], resolve && (async () => (await resolve())?.["PolicyDocument"]));
8960
+ if (attempted.kind === "retry") {
8961
+ this.logger.warn(safeMsg`The policy document ${logicalId} attempted could not be resolved (${attempted.errorName}), so no topic it wrote is reset; the entry is kept for a re-run once that is fixed.`);
8962
+ return {
8963
+ outcome: "skipped",
8964
+ reason: TOPIC_POLICY_UNRESOLVED_DOCUMENT_SKIP_REASON
8965
+ };
8966
+ }
8967
+ if (attempted.kind === "unusable") {
8968
+ this.logger.warn(safeMsg`${logicalId} is not reset on any topic it wrote (${attempted.why}); check each by hand and reset its policy where it still grants what ${logicalId} declared: ${named.join(", ")}.`);
8969
+ return {
8970
+ outcome: "deleted",
8971
+ leftInPlace: TOPIC_POLICY_NOT_COMPARED_LEFT_REASON
8972
+ };
8973
+ }
8974
+ const document = attempted.document;
8975
+ if (sendsNoPolicy(document)) {
8976
+ this.logger.debug(safeMsg`${logicalId} set no policy of its own; nothing to reset`);
8977
+ return;
8978
+ }
8979
+ const reference = policyContentKey(sentPolicyDocument(document));
8980
+ const fresh = new Set((context.writtenThisRun ?? []).flatMap((r) => r.resourceType === resourceType && typeof r.physicalId === "string" ? [...splitTopicArns(r.physicalId), ...listedTopics(r.properties !== null && typeof r.properties === "object" ? r.properties : {})] : []));
8981
+ let unreadable = false;
8982
+ let mismatched = false;
8983
+ for (const topicArn of named) {
8984
+ if (fresh.has(topicArn)) {
8985
+ mismatched = true;
8986
+ this.logger.warn(safeMsg`Topic ${topicArn} was written by a TopicPolicy of this deploy, so it is not reset: its policy may not read back current yet; if it still grants what ${logicalId} declared, reset it manually.`);
8987
+ continue;
8988
+ }
8989
+ const current = await this.readPolicyForWidening(topicArn);
8990
+ if (current.kind === "gone") {
8991
+ const clientRegion = await getAwsClients().sns.config.region();
8992
+ assertRegionMatch(clientRegion, context.expectedRegion, resourceType, logicalId, topicArn, "not-found");
8993
+ this.logger.debug(safeMsg`Topic ${topicArn} does not exist; nothing to reset`);
8994
+ continue;
8995
+ }
8996
+ if (current.kind === "unreadable") {
8997
+ unreadable = true;
8998
+ this.logger.warn(safeMsg`Could not read the policy of topic ${topicArn} (${current.reason}), so it is not reset: it may still carry the policy of ${logicalId}.`);
8999
+ continue;
9000
+ }
9001
+ const live = current.kind === "none" ? void 0 : policyContentKey(current.policy);
9002
+ if (live === void 0 || live === reference) {
9003
+ try {
9004
+ await this.resetTopicPolicy(topicArn, resourceType, logicalId, context.expectedRegion);
9005
+ } catch (error) {
9006
+ if (error instanceof ProvisioningError) throw error;
9007
+ throw this.wrapOperationError("delete", logicalId, resourceType, physicalId, error, context.maskSecrets);
9008
+ }
9009
+ continue;
9010
+ }
9011
+ const defaultPolicy = defaultTopicPolicy(topicArn);
9012
+ if (defaultPolicy !== void 0 && live === policyContentKey(defaultPolicy)) {
9013
+ this.logger.debug(safeMsg`Topic ${topicArn} already carries its default policy`);
9014
+ continue;
9015
+ }
9016
+ mismatched = true;
9017
+ this.logger.warn(safeMsg`Topic ${topicArn} carries a policy that does not match the document ${logicalId} attempted (a later write, or AWS stored it in another form), so it is not reset; if it still grants what ${logicalId} declared, reset it manually.`);
9018
+ }
9019
+ if (unreadable) return {
9020
+ outcome: "skipped",
9021
+ reason: TOPIC_POLICY_UNREADABLE_SKIP_REASON
9022
+ };
9023
+ if (mismatched) return {
9024
+ outcome: "deleted",
9025
+ leftInPlace: TOPIC_POLICY_MISMATCH_LEFT_REASON
9026
+ };
9027
+ }
9028
+ wrapOperationError(operation, logicalId, resourceType, physicalId, error, maskSecrets) {
9029
+ const mask = maskSecrets ?? ((t) => t);
9030
+ const failure = describeAwsFailure(error);
9031
+ if (failure.redacted) this.logger.debug(mask(`Failed to ${operation} SNS topic policy ${logicalId}: ${failure.detail}`));
9032
+ const cause = error instanceof Error ? error : void 0;
9033
+ const wrapped = new ProvisioningError(`Failed to ${operation} SNS topic policy ${logicalId}: ${failure.summary}`, resourceType, logicalId, physicalId, cause);
9034
+ return failure.redacted && cause !== void 0 ? markRedactedCause(wrapped) : wrapped;
9035
+ }
9036
+ async resetTopicPolicy(topicArn, resourceType, logicalId, expectedRegion, phase = "not-found", mask = (t) => t) {
9037
+ const defaultPolicy = defaultTopicPolicy(topicArn);
9038
+ if (defaultPolicy === void 0) throw new ProvisioningError(`Cannot remove SNS topic policy ${logicalId} from ${topicArn}: not an SNS topic ARN`, resourceType, logicalId, topicArn);
9039
+ try {
9040
+ await this.setTopicPolicy(topicArn, defaultPolicy);
9041
+ this.logger.debug(mask(safeMsg`Reset the policy of topic ${topicArn} to the default`));
9042
+ } catch (error) {
9043
+ const name = error?.name;
9044
+ if (name === "NotFoundException" || name === "NotFound") {
9045
+ const clientRegion = await getAwsClients().sns.config.region();
9046
+ assertRegionMatch(clientRegion, expectedRegion, resourceType, logicalId, topicArn, phase);
9047
+ this.logger.debug(mask(safeMsg`Topic ${topicArn} not found, skipping policy removal`));
9048
+ return;
9049
+ }
9050
+ throw error;
9051
+ }
9052
+ }
9053
+ async topicsCarryingDocument(candidates, document, logicalId, mask) {
9054
+ if (candidates.length === 0) return [];
9055
+ if (sendsNoPolicy(document)) return [];
9056
+ const sent = sentPolicyDocument(document);
9057
+ let reference;
9058
+ if (typeof sent === "string" && sent.length > 0) reference = canonicalPolicy(sent);
9059
+ else if (sent !== null && typeof sent === "object") reference = canonicalJson$1(sent);
9060
+ if (reference === void 0) {
9061
+ this.logger.warn(mask(safeMsg`The topics ${candidates.join(", ")} listed by ${logicalId} were not checked (no policy document recorded to compare with) and may still carry its policy.`));
9062
+ return [];
9063
+ }
9064
+ const carrying = [];
9065
+ for (const topicArn of candidates) {
9066
+ const current = await this.readPolicyForWidening(topicArn);
9067
+ if (current.kind === "policy" && canonicalPolicy(current.policy) === reference) carrying.push(topicArn);
9068
+ else if (current.kind === "unreadable") this.logger.warn(mask(safeMsg`Could not read the policy of topic ${topicArn} (${current.reason}), so it is not reset: it may still carry the policy of ${logicalId}.`));
9069
+ else this.logger.debug(mask(safeMsg`Topic ${topicArn} does not carry the policy of ${logicalId}; left as is`));
9070
+ }
9071
+ return carrying;
9072
+ }
9073
+ async readPolicyForWidening(topicArn) {
9074
+ try {
9075
+ const policy = (await getAwsClients().sns.send(new GetTopicAttributesCommand({ TopicArn: topicArn }))).Attributes?.["Policy"];
9076
+ return policy ? {
9077
+ kind: "policy",
9078
+ policy
9079
+ } : { kind: "none" };
9080
+ } catch (err) {
9081
+ const name = err.name;
9082
+ if (name === "NotFoundException" || name === "NotFound") return { kind: "gone" };
9083
+ return {
9084
+ kind: "unreadable",
9085
+ reason: name ?? "error"
9086
+ };
9087
+ }
9088
+ }
9089
+ async readCurrentState(physicalId, _logicalId, _resourceType, properties, context) {
9090
+ if (properties !== void 0 && sendsNoPolicy(properties["PolicyDocument"])) {
9091
+ const read = await this.readTopicPolicy(physicalId);
9092
+ return read !== void 0 && read !== RESOURCE_NOT_FOUND && isSnsDefaultPolicy(read["PolicyDocument"]) ? { ...properties } : read;
9093
+ }
9094
+ const declared = context?.afterOwnWrite === true ? declaredPolicyDocument(properties) : void 0;
9095
+ if (declared === void 0) return this.readTopicPolicy(physicalId);
9096
+ const { answer, settled } = await reReadUntilSettled(() => this.readTopicPolicy(physicalId), (read) => read !== void 0 && read !== RESOURCE_NOT_FOUND && policyDocumentMatchesDeclared(read["PolicyDocument"], declared), this.ownWriteRereadDelaysMs);
9097
+ if (settled) return answer;
9098
+ const read = answer === void 0 || answer === RESOURCE_NOT_FOUND ? void 0 : answer["PolicyDocument"];
9099
+ if (read !== void 0 && !isSnsDefaultPolicy(read)) return answer;
9100
+ this.logger.debug(safeMsg`No drift baseline captured for topic policy ${physicalId}: its topic still read back its default policy after the write`);
9101
+ }
9102
+ async readTopicPolicy(physicalId) {
9103
+ const topics = physicalId.split(",").filter((t) => t.length > 0);
9104
+ if (topics.length === 0) return void 0;
9105
+ const firstTopic = topics[0];
9106
+ let policyAttr;
9107
+ try {
9108
+ policyAttr = (await getAwsClients().sns.send(new GetTopicAttributesCommand({ TopicArn: firstTopic }))).Attributes?.["Policy"];
9109
+ } catch (err) {
9110
+ const e = err;
9111
+ if (e.name === "NotFoundException" || e.name === "NotFound") return RESOURCE_NOT_FOUND;
9112
+ throw err;
9113
+ }
9114
+ const result = { Topics: topics };
9115
+ if (policyAttr) try {
9116
+ result["PolicyDocument"] = JSON.parse(policyAttr);
9117
+ } catch {
9118
+ result["PolicyDocument"] = policyAttr;
9119
+ }
9120
+ return result;
9121
+ }
9122
+ async import(input) {
9123
+ if (input.knownPhysicalId && isSnsTopicArnList(input.knownPhysicalId)) return {
9124
+ physicalId: input.knownPhysicalId,
9125
+ attributes: {}
9126
+ };
9127
+ const topics = input.properties["Topics"];
9128
+ if (Array.isArray(topics) && topics.length > 0) {
9129
+ if (topics.every((t) => typeof t === "string" && isSnsTopicArn(t))) return {
9130
+ physicalId: topics.join(","),
9131
+ attributes: {}
9132
+ };
9133
+ }
9134
+ const knownNote = input.knownPhysicalId ? ` Got knownPhysicalId=${isPlainImportValue(input.knownPhysicalId) ? `'${input.knownPhysicalId}'` : VALUE_NOT_SHOWN} (not a comma-joined list of SNS topic ARNs; CloudFormation returns the policy resource NAME for AWS::SNS::TopicPolicy, which is not the operational identifier).` : "";
9135
+ const topicsNote = Array.isArray(topics) && topics.length > 0 ? ` Properties.Topics${isPlainImportJson(topics) ? `=${JSON.stringify(topics)}` : ` ${VALUE_NOT_SHOWN}`} did not resolve to a list of literal topic ARNs (intrinsic-valued entries like {Ref: '<Topic>'} are not resolved at import time).` : " Properties.Topics is missing or empty.";
9136
+ throw new Error(`Cannot determine topic ARNs for ${refusalTypeShown(input.resourceType)} ${logicalIdShown(input.logicalId)}.${knownNote}${topicsNote} Re-run with --resource ${remedyLogicalId(input.logicalId)}=${commandHole("comma-joined-topic-ARNs")} (e.g. arn:aws:sns:${isPasteableIdent(input.region) ? input.region : commandHole("region")}:'<account>':'<topic-name>') to point cdkd at the topic(s) this policy is attached to.`);
9137
+ }
9138
+ async setTopicPolicy(topicArn, policyDoc) {
9139
+ await getAwsClients().sns.send(new SetTopicAttributesCommand({
9140
+ TopicArn: topicArn,
9141
+ AttributeName: "Policy",
9142
+ AttributeValue: policyDoc
9143
+ }));
9144
+ }
9145
+ };
9146
+ function isSnsTopicArnList(value) {
9147
+ const segments = value.split(",");
9148
+ if (segments.length === 0) return false;
9149
+ return segments.every((s) => isSnsTopicArn(s));
9150
+ }
9151
+ function splitTopicArns(physicalId) {
9152
+ return physicalId.split(",").filter((arn) => arn.length > 0);
9153
+ }
9154
+ function listedTopics(bag) {
9155
+ const listed = bag["Topics"];
9156
+ if (!Array.isArray(listed)) return [];
9157
+ const out = [];
9158
+ for (const entry of listed) if (typeof entry === "string" && isSnsTopicArn(entry) && !out.includes(entry)) out.push(entry);
9159
+ return out;
9160
+ }
9096
9161
  function canonicalJson$1(value) {
9097
9162
  const sortKeys = (v) => {
9098
9163
  if (Array.isArray(v)) return v.map(sortKeys);
@@ -10218,7 +10283,7 @@ async function unsettledInTransition$6(physicalId, _logicalId, _resourceType, na
10218
10283
  return names;
10219
10284
  }
10220
10285
  }
10221
- async function readCurrentState$35(physicalId, _logicalId, _resourceType) {
10286
+ async function readCurrentState$36(physicalId, _logicalId, _resourceType) {
10222
10287
  try {
10223
10288
  const resp = await this.lambdaClient.send(new GetFunctionCommand({ FunctionName: physicalId }));
10224
10289
  const cfg = resp.Configuration;
@@ -10517,7 +10582,7 @@ var LambdaFunctionProvider = class {
10517
10582
  return unsettledInTransition$6.call(this, physicalId, _logicalId, _resourceType, names);
10518
10583
  }
10519
10584
  readCurrentState(physicalId, _logicalId, _resourceType) {
10520
- return readCurrentState$35.call(this, physicalId, _logicalId, _resourceType);
10585
+ return readCurrentState$36.call(this, physicalId, _logicalId, _resourceType);
10521
10586
  }
10522
10587
  getDriftUnknownPaths() {
10523
10588
  return [
@@ -10549,6 +10614,7 @@ var LambdaPermissionProvider = class {
10549
10614
  lambdaClient;
10550
10615
  createClient = new LambdaCreateClientCache(() => this.lambdaClient);
10551
10616
  logger = getLogger().child("LambdaPermissionProvider");
10617
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
10552
10618
  handledProperties = /* @__PURE__ */ new Map([["AWS::Lambda::Permission", /* @__PURE__ */ new Set([
10553
10619
  "FunctionName",
10554
10620
  "Action",
@@ -10621,6 +10687,7 @@ var LambdaPermissionProvider = class {
10621
10687
  ...functionNamePairs(properties["FunctionName"])
10622
10688
  ]);
10623
10689
  log.debug(`Updating Lambda permission ${logicalId}: ${physicalId}`);
10690
+ if (isDriftRevert(context)) throw revertReplacementRefusal(resourceType, logicalId, "a Lambda permission has no update API and is changed only by removing and re-adding its statement");
10624
10691
  try {
10625
10692
  const oldFunctionName = previousProperties["FunctionName"] || properties["FunctionName"];
10626
10693
  const oldStatementId = physicalId.includes("|") ? physicalId.split("|").pop() : physicalId;
@@ -10701,7 +10768,13 @@ var LambdaPermissionProvider = class {
10701
10768
  throw error instanceof Error && error.name.includes("NotFound") ? markNotGone(thrown) : thrown;
10702
10769
  }
10703
10770
  }
10704
- async readCurrentState(physicalId, _logicalId, _resourceType, properties) {
10771
+ async readCurrentState(physicalId, _logicalId, _resourceType, properties, context) {
10772
+ if (context?.afterOwnWrite !== true || typeof properties?.["FunctionName"] !== "string") return this.readPermission(physicalId, properties);
10773
+ const { answer, settled } = await reReadUntilSettled(() => this.readPermission(physicalId, properties), (read) => read !== void 0 && read !== RESOURCE_NOT_FOUND && lambdaPermissionMatchesDeclared(read, properties), this.ownWriteRereadDelaysMs);
10774
+ if (settled || answer !== void 0 && answer !== RESOURCE_NOT_FOUND) return answer;
10775
+ this.logger.debug(safeMsg`No drift baseline captured for permission ${physicalId}: its function policy still read back no such statement after the write`);
10776
+ }
10777
+ async readPermission(physicalId, properties) {
10705
10778
  const functionName = properties?.["FunctionName"];
10706
10779
  if (!functionName) return void 0;
10707
10780
  const statementId = physicalId.includes("|") ? physicalId.split("|").pop() : physicalId;
@@ -11481,7 +11554,7 @@ async function deleteImpl$34(logicalId, physicalId, resourceType, properties, co
11481
11554
  }
11482
11555
 
11483
11556
  // src/provisioning/providers/lambda-eventsource/read-state.ts
11484
- async function readCurrentState$34(physicalId, _logicalId, _resourceType, properties) {
11557
+ async function readCurrentState$35(physicalId, _logicalId, _resourceType, properties) {
11485
11558
  let resp;
11486
11559
  try {
11487
11560
  resp = await this.lambdaClient.send(new GetEventSourceMappingCommand({ UUID: physicalId }));
@@ -11691,7 +11764,7 @@ var LambdaEventSourceMappingProvider = class {
11691
11764
  return deleteImpl$34.call(this, logicalId, physicalId, resourceType, properties, context);
11692
11765
  }
11693
11766
  readCurrentState(physicalId, logicalId, resourceType, properties) {
11694
- return readCurrentState$34.call(this, physicalId, logicalId, resourceType, properties);
11767
+ return readCurrentState$35.call(this, physicalId, logicalId, resourceType, properties);
11695
11768
  }
11696
11769
  canonicalizeDriftPair(resourceType, baseline, aws, properties) {
11697
11770
  return canonicalizeDriftPair$5.call(this, resourceType, baseline, aws, properties);
@@ -14966,7 +15039,7 @@ async function waitForKinesisDestinationSettled(tableName, streamArn, expectedPr
14966
15039
  function isTransientStreamReadFailure(err) {
14967
15040
  return isThrottlingError(err) || isTransientServerError(err) || isAmbiguousOutcomeError(err) || err instanceof ResourceNotFoundException$1;
14968
15041
  }
14969
- async function readCurrentState$33(physicalId, _logicalId, _resourceType, properties, context) {
15042
+ async function readCurrentState$34(physicalId, _logicalId, _resourceType, properties, context) {
14970
15043
  try {
14971
15044
  const table = (await this.dynamoDBClient.send(new DescribeTableCommand({ TableName: physicalId }))).Table;
14972
15045
  if (!table) return void 0;
@@ -16131,7 +16204,7 @@ var DynamoDBTableProvider = class {
16131
16204
  return unsettledInTransition$5.call(this, physicalId, _logicalId, _resourceType, names);
16132
16205
  }
16133
16206
  async readCurrentState(physicalId, _logicalId, _resourceType, properties, context) {
16134
- return readCurrentState$33.call(this, physicalId, _logicalId, _resourceType, properties, context);
16207
+ return readCurrentState$34.call(this, physicalId, _logicalId, _resourceType, properties, context);
16135
16208
  }
16136
16209
  readTableTags(...args) {
16137
16210
  return readTableTags.call(this, ...args);
@@ -16593,7 +16666,21 @@ async function getAttribute$13(physicalId, _resourceType, attributeName) {
16593
16666
  if (attributeName !== "Arn") return;
16594
16667
  return this.buildArn(physicalId);
16595
16668
  }
16596
- async function readCurrentState$32(physicalId, _logicalId, _resourceType) {
16669
+ async function readDataProtectionPolicy(physicalId) {
16670
+ let document;
16671
+ try {
16672
+ document = (await this.logsClient.send(new GetDataProtectionPolicyCommand({ logGroupIdentifier: physicalId }))).policyDocument;
16673
+ } catch (err) {
16674
+ return memberReadFailure(err);
16675
+ }
16676
+ if (!document) return "absent";
16677
+ try {
16678
+ return { value: JSON.parse(document) };
16679
+ } catch {
16680
+ return { value: document };
16681
+ }
16682
+ }
16683
+ async function readCurrentState$33(physicalId, logicalId, _resourceType, properties, context) {
16597
16684
  try {
16598
16685
  const found = (await this.logsClient.send(new DescribeLogGroupsCommand({ logGroupNamePrefix: physicalId }))).logGroups?.find((g) => g.logGroupName === physicalId);
16599
16686
  if (!found) return RESOURCE_NOT_FOUND;
@@ -16616,16 +16703,10 @@ async function readCurrentState$32(physicalId, _logicalId, _resourceType) {
16616
16703
  }
16617
16704
  }
16618
16705
  result["Tags"] = tags;
16619
- let dpp = "";
16620
- try {
16621
- const dppResp = await this.logsClient.send(new GetDataProtectionPolicyCommand({ logGroupIdentifier: physicalId }));
16622
- if (dppResp.policyDocument) try {
16623
- dpp = JSON.parse(dppResp.policyDocument);
16624
- } catch {
16625
- dpp = dppResp.policyDocument;
16626
- }
16627
- } catch {}
16628
- result["DataProtectionPolicy"] = dpp;
16706
+ let dpp = await readDataProtectionPolicy.call(this, physicalId);
16707
+ const declared = context?.afterOwnWrite === true ? declaredMemberDocument(properties?.["DataProtectionPolicy"]) : void 0;
16708
+ if (declared !== void 0) dpp = await settleDeclaredMember(dpp, () => readDataProtectionPolicy.call(this, physicalId), (document) => policyDocumentMatchesDeclared(document, declared), declared, this.ownWriteRereadDelaysMs, () => warnUnsettledMember(this.logger, logicalId, "AWS::Logs::LogGroup", "DataProtectionPolicy"));
16709
+ result["DataProtectionPolicy"] = typeof dpp === "object" ? dpp.value : "";
16629
16710
  let fieldIndexPolicies = [];
16630
16711
  try {
16631
16712
  fieldIndexPolicies = ((await this.logsClient.send(new DescribeIndexPoliciesCommand({ logGroupIdentifiers: [physicalId] }))).indexPolicies ?? []).filter((p) => p.source !== "ACCOUNT").map((p) => {
@@ -16665,6 +16746,7 @@ var LogsLogGroupProvider = class {
16665
16746
  logsClient;
16666
16747
  stsClient;
16667
16748
  logger = getLogger().child("LogsLogGroupProvider");
16749
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
16668
16750
  protectionFlips = new ProtectionFlipRegistry();
16669
16751
  handledProperties = /* @__PURE__ */ new Map([["AWS::Logs::LogGroup", /* @__PURE__ */ new Set([
16670
16752
  "LogGroupName",
@@ -16728,8 +16810,8 @@ var LogsLogGroupProvider = class {
16728
16810
  getAttribute(physicalId, _resourceType, attributeName) {
16729
16811
  return getAttribute$13.call(this, physicalId, _resourceType, attributeName);
16730
16812
  }
16731
- readCurrentState(physicalId, _logicalId, _resourceType) {
16732
- return readCurrentState$32.call(this, physicalId, _logicalId, _resourceType);
16813
+ readCurrentState(physicalId, _logicalId, _resourceType, properties, context) {
16814
+ return readCurrentState$33.call(this, physicalId, _logicalId, _resourceType, properties, context);
16733
16815
  }
16734
16816
  import(input) {
16735
16817
  return importImpl$33.call(this, input);
@@ -17005,6 +17087,7 @@ const WHAT$1 = "CloudWatch Logs delivery destination";
17005
17087
  var LogsDeliveryDestinationProvider = class {
17006
17088
  client;
17007
17089
  logger = getLogger().child("LogsDeliveryDestinationProvider");
17090
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
17008
17091
  constructor() {
17009
17092
  this.client = getAwsClients().cloudWatchLogs;
17010
17093
  }
@@ -17112,7 +17195,7 @@ var LogsDeliveryDestinationProvider = class {
17112
17195
  throw error;
17113
17196
  }
17114
17197
  }
17115
- async readCurrentState(physicalId, _logicalId, _resourceType, properties) {
17198
+ async readCurrentState(physicalId, logicalId, _resourceType, properties, context) {
17116
17199
  let destination;
17117
17200
  try {
17118
17201
  destination = (await this.client.send(new GetDeliveryDestinationCommand({ name: physicalId }))).deliveryDestination;
@@ -17127,19 +17210,14 @@ var LogsDeliveryDestinationProvider = class {
17127
17210
  if (destinationArn !== void 0) result["DestinationResourceArn"] = destinationArn;
17128
17211
  if (destination.deliveryDestinationType !== void 0) result["DeliveryDestinationType"] = destination.deliveryDestinationType;
17129
17212
  if (destination.outputFormat !== void 0) result["OutputFormat"] = destination.outputFormat;
17130
- let policy;
17131
- try {
17132
- policy = (await this.client.send(new GetDeliveryDestinationPolicyCommand({ deliveryDestinationName: physicalId }))).policy?.deliveryDestinationPolicy;
17133
- } catch (error) {
17134
- if (!isLogsNotFound(error)) throw error;
17135
- }
17136
- if (policy !== void 0 && policy !== "") {
17137
- const declared = properties?.["DeliveryDestinationPolicy"];
17138
- result["DeliveryDestinationPolicy"] = {
17139
- ...isPlainRecord$3(declared) && declared["DeliveryDestinationName"] !== void 0 && { DeliveryDestinationName: physicalId },
17140
- DeliveryDestinationPolicy: parsePolicy(policy)
17141
- };
17142
- }
17213
+ let policy = await this.readDestinationPolicy(physicalId);
17214
+ const declared = properties?.["DeliveryDestinationPolicy"];
17215
+ const declaredDocument = context?.afterOwnWrite === true && isPlainRecord$3(declared) ? declared["DeliveryDestinationPolicy"] : void 0;
17216
+ if (isPlainRecord$3(declaredDocument)) policy = await settleDeclaredMember(policy, () => this.readDestinationPolicy(physicalId), (document) => policyDocumentMatchesDeclared(document, declaredDocument), declaredDocument, this.ownWriteRereadDelaysMs, () => warnUnsettledMember(this.logger, logicalId, "AWS::Logs::DeliveryDestination", "DeliveryDestinationPolicy"));
17217
+ if (typeof policy === "object") result["DeliveryDestinationPolicy"] = {
17218
+ ...isPlainRecord$3(declared) && declared["DeliveryDestinationName"] !== void 0 && { DeliveryDestinationName: physicalId },
17219
+ DeliveryDestinationPolicy: policy.value
17220
+ };
17143
17221
  try {
17144
17222
  if (destination.arn) result["Tags"] = await readTags$1(this.client, destination.arn);
17145
17223
  } catch (error) {
@@ -17148,6 +17226,15 @@ var LogsDeliveryDestinationProvider = class {
17148
17226
  }
17149
17227
  return result;
17150
17228
  }
17229
+ async readDestinationPolicy(physicalId) {
17230
+ let policy;
17231
+ try {
17232
+ policy = (await this.client.send(new GetDeliveryDestinationPolicyCommand({ deliveryDestinationName: physicalId }))).policy?.deliveryDestinationPolicy;
17233
+ } catch (error) {
17234
+ if (!isLogsNotFound(error)) throw error;
17235
+ }
17236
+ return policy !== void 0 && policy !== "" ? { value: parsePolicy(policy) } : "absent";
17237
+ }
17151
17238
  wrapError(operation, logicalId, resourceType, physicalId, error) {
17152
17239
  if (error instanceof ProvisioningError) return error;
17153
17240
  return wrapLogsError(this.logger, WHAT$1, operation, logicalId, resourceType, physicalId, error);
@@ -18271,7 +18358,7 @@ function generateSecretString(config, options) {
18271
18358
  }
18272
18359
 
18273
18360
  // src/provisioning/providers/secretsmanager-secret/read-state.ts
18274
- async function readCurrentState$31(physicalId, _logicalId, _resourceType) {
18361
+ async function readCurrentState$32(physicalId, _logicalId, _resourceType) {
18275
18362
  try {
18276
18363
  const resp = await this.smClient.send(new DescribeSecretCommand({ SecretId: physicalId }));
18277
18364
  const result = {};
@@ -18394,7 +18481,7 @@ var SecretsManagerSecretProvider = class {
18394
18481
  return generateSecretString.call(this, config, options);
18395
18482
  }
18396
18483
  readCurrentState(physicalId, logicalId, resourceType) {
18397
- return readCurrentState$31.call(this, physicalId, logicalId, resourceType);
18484
+ return readCurrentState$32.call(this, physicalId, logicalId, resourceType);
18398
18485
  }
18399
18486
  getDriftUnknownPaths() {
18400
18487
  return ["SecretString", "GenerateSecretString"];
@@ -18525,7 +18612,7 @@ async function deleteImpl$31(logicalId, physicalId, resourceType, _properties, c
18525
18612
  }
18526
18613
 
18527
18614
  // src/provisioning/providers/ssm-parameter/read-state.ts
18528
- async function readCurrentState$30(physicalId, _logicalId, _resourceType) {
18615
+ async function readCurrentState$31(physicalId, _logicalId, _resourceType) {
18529
18616
  let getResp;
18530
18617
  try {
18531
18618
  getResp = await this.ssmClient.send(new GetParameterCommand({
@@ -18705,7 +18792,7 @@ var SSMParameterProvider = class SSMParameterProvider {
18705
18792
  return deleteImpl$31.call(this, logicalId, physicalId, resourceType, properties, context);
18706
18793
  }
18707
18794
  readCurrentState(physicalId, logicalId, resourceType) {
18708
- return readCurrentState$30.call(this, physicalId, logicalId, resourceType);
18795
+ return readCurrentState$31.call(this, physicalId, logicalId, resourceType);
18709
18796
  }
18710
18797
  refuseUnwritableParameterId(input, explicit) {
18711
18798
  return refuseUnwritableParameterId.call(this, input, explicit);
@@ -20449,7 +20536,7 @@ async function applyUpdate$3(logicalId, physicalId, resourceType, properties, pr
20449
20536
  case "AWS::EC2::Route": return this.updateRoute(logicalId, physicalId, resourceType, properties, previousProperties, context);
20450
20537
  case "AWS::EC2::SubnetRouteTableAssociation": return this.updateSubnetRouteTableAssociation(logicalId, physicalId);
20451
20538
  case "AWS::EC2::SecurityGroup": return this.updateSecurityGroup(logicalId, physicalId, resourceType, properties, previousProperties, context);
20452
- case "AWS::EC2::SecurityGroupIngress": return this.updateSecurityGroupIngress(logicalId, physicalId, resourceType, properties, previousProperties, context?.maskSecrets, context?.replayingState === true, context?.recordedAttributes);
20539
+ case "AWS::EC2::SecurityGroupIngress": return this.updateSecurityGroupIngress(logicalId, physicalId, resourceType, properties, previousProperties, context?.maskSecrets, context?.replayingState === true, context?.recordedAttributes, context?.desiredFromAwsReadback === true);
20453
20540
  case "AWS::EC2::Instance": return this.updateInstance(logicalId, physicalId, resourceType, properties, previousProperties, context);
20454
20541
  case "AWS::EC2::NetworkAclEntry": return this.updateNetworkAclEntry(logicalId, physicalId, resourceType, properties, previousProperties, context);
20455
20542
  case "AWS::EC2::SubnetNetworkAclAssociation": throw new ResourceUpdateNotSupportedError(resourceType, logicalId, `AWS provides no in-place Update API for this EC2 sub-resource type; every property change requires Delete + Create. Re-deploy with ${deployReplaceCommand()}, or destroy + redeploy`);
@@ -22440,6 +22527,7 @@ async function updateRoute$1(logicalId, physicalId, resourceType, properties, pr
22440
22527
  throw this.wrapCaughtError(maskerOrIdentity(maskSecrets), error, (text) => new ProvisioningError(`Failed to update Route ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
22441
22528
  }
22442
22529
  }
22530
+ if (isDriftRevert(context)) throw revertReplacementRefusal(resourceType, logicalId, "its route table or destination differs from the route its physical id names");
22443
22531
  try {
22444
22532
  await this.deleteRoute(logicalId, physicalId, resourceType, maskSecrets ? { maskSecrets } : void 0);
22445
22533
  const createResult = await this.createRoute(logicalId, resourceType, properties, (message) => this.logger.warn(message), maskSecrets);
@@ -23092,7 +23180,7 @@ async function lookupIngressRuleId(logicalId, groupId, properties) {
23092
23180
  return;
23093
23181
  }
23094
23182
  }
23095
- async function updateSecurityGroupIngress(logicalId, physicalId, resourceType, properties, previousProperties, maskSecrets, replayingState = false, recordedAttributes) {
23183
+ async function updateSecurityGroupIngress(logicalId, physicalId, resourceType, properties, previousProperties, maskSecrets, replayingState = false, recordedAttributes, driftRevert = false) {
23096
23184
  this.logger.debug(`Updating SecurityGroupIngress ${logicalId}: ${physicalId}`);
23097
23185
  if (JSON.stringify(properties) === JSON.stringify(previousProperties)) {
23098
23186
  if (!replayingState) return {
@@ -23143,6 +23231,7 @@ async function updateSecurityGroupIngress(logicalId, physicalId, resourceType, p
23143
23231
  ...narrowed !== properties && { effectiveProperties: narrowed }
23144
23232
  };
23145
23233
  }
23234
+ if (driftRevert) throw revertReplacementRefusal(resourceType, logicalId, "the rule cannot reach its record in place (the live rule's protocol, ports or source differ from it, AWS no longer has the rule, or its recorded description is redacted)");
23146
23235
  try {
23147
23236
  if (keptFor !== void 0) this.logger.info(safeMsg`SecurityGroupIngress ${logicalId}: its previous rule is also held by ${keptFor} of this stack, so the update left it in place`);
23148
23237
  const revoked = keptFor !== void 0 ? void 0 : await this.deleteSecurityGroupIngress(logicalId, physicalId, resourceType, previousProperties, recordedAttributes || maskSecrets ? {
@@ -25458,7 +25547,7 @@ function canonicalizeUnsettledProperties$1(resourceType, properties) {
25458
25547
  [key]: canonical
25459
25548
  };
25460
25549
  }
25461
- async function readCurrentState$29(physicalId, logicalId, resourceType, properties, context) {
25550
+ async function readCurrentState$30(physicalId, logicalId, resourceType, properties, context) {
25462
25551
  const attempts = context?.afterOwnWrite === true ? 5 : 1;
25463
25552
  for (let attempt = 1;; attempt++) {
25464
25553
  const read = await this.readCurrentStateOnce(physicalId, logicalId, resourceType, properties, context);
@@ -25579,7 +25668,7 @@ const driftMethods = {
25579
25668
  readUnsettled: readUnsettled$5,
25580
25669
  canonicalizeDriftPair: canonicalizeDriftPair$3,
25581
25670
  canonicalizeUnsettledProperties: canonicalizeUnsettledProperties$1,
25582
- readCurrentState: readCurrentState$29,
25671
+ readCurrentState: readCurrentState$30,
25583
25672
  readCurrentStateOnce,
25584
25673
  getDriftUnknownPaths: getDriftUnknownPaths$10,
25585
25674
  canonicalizeDesiredProperties: canonicalizeDesiredProperties$2
@@ -26797,6 +26886,503 @@ function methodChildCalls(ids, desired, previous) {
26797
26886
  return calls;
26798
26887
  }
26799
26888
 
26889
+ // src/provisioning/providers/apigateway/rest-api.ts
26890
+ const BODY_KEYS = [
26891
+ "Body",
26892
+ "BodyS3Location",
26893
+ "Mode",
26894
+ "FailOnWarnings",
26895
+ "Parameters"
26896
+ ];
26897
+ const SCALAR_FIELDS = [
26898
+ {
26899
+ key: "Name",
26900
+ path: "/name"
26901
+ },
26902
+ {
26903
+ key: "Description",
26904
+ path: "/description"
26905
+ },
26906
+ {
26907
+ key: "Version",
26908
+ path: "/version"
26909
+ },
26910
+ {
26911
+ key: "MinimumCompressionSize",
26912
+ path: "/minimumCompressionSize"
26913
+ },
26914
+ {
26915
+ key: "ApiKeySourceType",
26916
+ path: "/apiKeySource"
26917
+ },
26918
+ {
26919
+ key: "DisableExecuteApiEndpoint",
26920
+ path: "/disableExecuteApiEndpoint"
26921
+ },
26922
+ {
26923
+ key: "SecurityPolicy",
26924
+ path: "/securityPolicy"
26925
+ },
26926
+ {
26927
+ key: "EndpointAccessMode",
26928
+ path: "/endpointAccessMode"
26929
+ }
26930
+ ];
26931
+ function pointerSegment(value) {
26932
+ return value.replace(/~/g, "~0").replace(/\//g, "~1");
26933
+ }
26934
+ function stringList(value) {
26935
+ if (!Array.isArray(value)) return void 0;
26936
+ return value.filter((v) => typeof v === "string");
26937
+ }
26938
+ function asRecord$2(value) {
26939
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
26940
+ }
26941
+ function restApiPolicyString(policy) {
26942
+ if (policy === void 0 || policy === null) return void 0;
26943
+ return typeof policy === "string" ? policy : JSON.stringify(policy);
26944
+ }
26945
+ function parseRestApiPolicy(raw, restApiId, recorded) {
26946
+ if (raw === void 0 || raw === "") return void 0;
26947
+ let text = raw;
26948
+ let parsed;
26949
+ try {
26950
+ parsed = JSON.parse(text);
26951
+ } catch {
26952
+ text = raw.replace(/\\(["\\/])/g, "$1");
26953
+ try {
26954
+ parsed = JSON.parse(text);
26955
+ } catch {
26956
+ return raw;
26957
+ }
26958
+ }
26959
+ const recordedText = restApiPolicyString(recorded);
26960
+ if (recordedText !== void 0 && recordedText.includes("execute-api:/")) {
26961
+ const expanded = new RegExp(`arn:[a-z-]+:execute-api:[a-z0-9-]+:\\d{12}:${restApiId}/`, "g");
26962
+ parsed = JSON.parse(JSON.stringify(parsed).replace(expanded, "execute-api:/"));
26963
+ }
26964
+ return parsed;
26965
+ }
26966
+ function restApiAsCfn(api, recordedPolicy) {
26967
+ const out = {};
26968
+ if (api.name !== void 0) out["Name"] = api.name;
26969
+ if (api.description !== void 0) out["Description"] = api.description;
26970
+ if (api.version !== void 0) out["Version"] = api.version;
26971
+ out["BinaryMediaTypes"] = api.binaryMediaTypes ? [...api.binaryMediaTypes] : [];
26972
+ if (api.minimumCompressionSize !== void 0) out["MinimumCompressionSize"] = api.minimumCompressionSize;
26973
+ if (api.apiKeySource !== void 0) out["ApiKeySourceType"] = api.apiKeySource;
26974
+ if (api.disableExecuteApiEndpoint !== void 0) out["DisableExecuteApiEndpoint"] = api.disableExecuteApiEndpoint;
26975
+ const policy = parseRestApiPolicy(api.policy, api.id ?? "", recordedPolicy);
26976
+ if (policy !== void 0) out["Policy"] = policy;
26977
+ if (api.endpointConfiguration !== void 0) {
26978
+ const ec = {};
26979
+ if (api.endpointConfiguration.types !== void 0) ec["Types"] = [...api.endpointConfiguration.types];
26980
+ if (api.endpointConfiguration.vpcEndpointIds !== void 0) ec["VpcEndpointIds"] = [...api.endpointConfiguration.vpcEndpointIds];
26981
+ if (api.endpointConfiguration.ipAddressType !== void 0) ec["IpAddressType"] = api.endpointConfiguration.ipAddressType;
26982
+ out["EndpointConfiguration"] = ec;
26983
+ }
26984
+ if (api.securityPolicy !== void 0) out["SecurityPolicy"] = api.securityPolicy;
26985
+ if (api.endpointAccessMode !== void 0) out["EndpointAccessMode"] = api.endpointAccessMode;
26986
+ return out;
26987
+ }
26988
+ function definitionBinaryMediaTypes(body) {
26989
+ let definition = body;
26990
+ if (typeof body === "string") try {
26991
+ definition = JSON.parse(body);
26992
+ } catch {
26993
+ return /* @__PURE__ */ new Set();
26994
+ }
26995
+ return new Set(stringList(asRecord$2(definition)?.["x-amazon-apigateway-binary-media-types"]) ?? []);
26996
+ }
26997
+ function isJsonText(text) {
26998
+ try {
26999
+ JSON.parse(text);
27000
+ return true;
27001
+ } catch {
27002
+ return false;
27003
+ }
27004
+ }
27005
+ function endpointType(config) {
27006
+ return stringList(asRecord$2(config)?.["Types"])?.[0];
27007
+ }
27008
+ function restApiPatchOperations(desired, current, previous, bodyPutMode) {
27009
+ const ops = [];
27010
+ for (const { key, path } of SCALAR_FIELDS) {
27011
+ const next = desired[key];
27012
+ if (next === void 0 || next === null) continue;
27013
+ const value = stringifyValue(next);
27014
+ if (value !== (current[key] == null ? "" : stringifyValue(current[key]))) ops.push({
27015
+ op: "replace",
27016
+ path,
27017
+ value
27018
+ });
27019
+ }
27020
+ const nextPolicy = restApiPolicyString(desired["Policy"]);
27021
+ if (nextPolicy !== void 0 && nextPolicy !== restApiPolicyString(current["Policy"])) ops.push({
27022
+ op: "replace",
27023
+ path: "/policy",
27024
+ value: nextPolicy
27025
+ });
27026
+ const targetTypes = stringList(desired["BinaryMediaTypes"]) ?? (previous["BinaryMediaTypes"] !== void 0 ? [] : void 0);
27027
+ if (targetTypes !== void 0) {
27028
+ const live = new Set(stringList(current["BinaryMediaTypes"]) ?? []);
27029
+ const target = new Set(targetTypes);
27030
+ const fromDefinition = definitionBinaryMediaTypes(desired["Body"]);
27031
+ const dropped = bodyPutMode === "overwrite" ? [] : stringList(previous["BinaryMediaTypes"]) ?? [];
27032
+ for (const t of new Set(dropped)) if (live.has(t) && !target.has(t) && !fromDefinition.has(t)) ops.push({
27033
+ op: "remove",
27034
+ path: `/binaryMediaTypes/${pointerSegment(t)}`
27035
+ });
27036
+ for (const t of target) if (!live.has(t)) ops.push({
27037
+ op: "add",
27038
+ path: `/binaryMediaTypes/${pointerSegment(t)}`
27039
+ });
27040
+ }
27041
+ const desiredEc = asRecord$2(desired["EndpointConfiguration"]);
27042
+ const currentEc = asRecord$2(current["EndpointConfiguration"]);
27043
+ const targetType = endpointType(desiredEc) ?? (previous["EndpointConfiguration"] !== void 0 ? "EDGE" : void 0);
27044
+ const currentType = endpointType(currentEc) ?? "EDGE";
27045
+ if (targetType !== void 0 && targetType !== currentType) ops.push({
27046
+ op: "replace",
27047
+ path: `/endpointConfiguration/types/${currentType}`,
27048
+ value: targetType
27049
+ });
27050
+ if (desiredEc !== void 0) {
27051
+ const nextIds = stringList(desiredEc["VpcEndpointIds"]);
27052
+ if (nextIds !== void 0 || targetType === "PRIVATE") {
27053
+ const live = new Set(stringList(currentEc?.["VpcEndpointIds"]) ?? []);
27054
+ const target = new Set(nextIds ?? []);
27055
+ for (const id of target) if (!live.has(id)) ops.push({
27056
+ op: "add",
27057
+ path: "/endpointConfiguration/vpcEndpointIds",
27058
+ value: id
27059
+ });
27060
+ for (const id of live) if (!target.has(id)) ops.push({
27061
+ op: "remove",
27062
+ path: "/endpointConfiguration/vpcEndpointIds",
27063
+ value: id
27064
+ });
27065
+ }
27066
+ const ipType = desiredEc["IpAddressType"];
27067
+ if (typeof ipType === "string" && ipType !== currentEc?.["IpAddressType"]) ops.push({
27068
+ op: "replace",
27069
+ path: "/endpointConfiguration/ipAddressType",
27070
+ value: ipType
27071
+ });
27072
+ }
27073
+ return ops;
27074
+ }
27075
+ function declaresBody(properties) {
27076
+ return properties["Body"] != null || properties["BodyS3Location"] != null;
27077
+ }
27078
+ function restApiBodyChanged(desired, previous, maskSecrets) {
27079
+ if (!declaresBody(desired)) return false;
27080
+ return BODY_KEYS.some((key) => !isDeepStrictEqual(desired[key], previous[key]) && !onlySecretReferencesDiffer(desired[key], previous[key], maskSecrets));
27081
+ }
27082
+ function definitionTitle(body) {
27083
+ try {
27084
+ const info = asRecord$2(asRecord$2(JSON.parse(new TextDecoder().decode(body)))?.["info"]);
27085
+ return typeof info?.["title"] === "string" ? info["title"] : void 0;
27086
+ } catch {
27087
+ return;
27088
+ }
27089
+ }
27090
+ function bodyParameters(value) {
27091
+ const record = asRecord$2(value);
27092
+ if (record === void 0) return void 0;
27093
+ return Object.fromEntries(Object.entries(record).map(([k, v]) => [k, String(v)]));
27094
+ }
27095
+ async function resolveRestApiBody(logicalId, resourceType, properties, mask, physicalId) {
27096
+ const body = properties["Body"];
27097
+ if (body !== void 0 && body !== null) {
27098
+ if (typeof body === "string") return new TextEncoder().encode(body);
27099
+ if (typeof body === "object") return new TextEncoder().encode(JSON.stringify(body));
27100
+ throw new ProvisioningError(`Body of ${resourceType} ${logicalId} must be an OpenAPI definition object or string`, resourceType, logicalId, physicalId);
27101
+ }
27102
+ const location = asRecord$2(properties["BodyS3Location"]);
27103
+ if (properties["BodyS3Location"] == null) return void 0;
27104
+ const bucket = location?.["Bucket"];
27105
+ const key = location?.["Key"];
27106
+ if (typeof bucket !== "string" || typeof key !== "string" || !bucket || !key) throw new ProvisioningError(`BodyS3Location of ${resourceType} ${logicalId} must name a Bucket and a Key`, resourceType, logicalId, physicalId);
27107
+ const version = location?.["Version"];
27108
+ const etag = location?.["ETag"];
27109
+ const resp = await getAwsClients().s3.send(new GetObjectCommand({
27110
+ Bucket: bucket,
27111
+ Key: key,
27112
+ ...typeof version === "string" && version && { VersionId: version },
27113
+ ...typeof etag === "string" && etag && { IfMatch: etag }
27114
+ }));
27115
+ const bytes = resp.Body ? await resp.Body.transformToByteArray() : void 0;
27116
+ if (!bytes || bytes.length === 0) throw new ProvisioningError(`BodyS3Location of ${resourceType} ${logicalId} (s3://${mask(bucket)}/${mask(key)}) holds no definition`, resourceType, logicalId, physicalId);
27117
+ return bytes;
27118
+ }
27119
+ async function restApiArn(restApiId) {
27120
+ const region = await this.apiGatewayClient.config.region();
27121
+ const { partition } = derivePartitionAndUrlSuffix(region);
27122
+ return `arn:${partition}:apigateway:${region}::/restapis/${restApiId}`;
27123
+ }
27124
+ async function createRestApi(logicalId, resourceType, properties, log) {
27125
+ log.debug(safeMsg`Creating API Gateway RestApi ${logicalId}`);
27126
+ const name = typeof properties["Name"] === "string" ? properties["Name"] : void 0;
27127
+ const cloneFrom = typeof properties["CloneFrom"] === "string" ? properties["CloneFrom"] : void 0;
27128
+ const hasBody = declaresBody(properties);
27129
+ if (!name && (!hasBody || cloneFrom)) throw new ProvisioningError(`Name is required for API Gateway RestApi ${logicalId} unless Body or BodyS3Location defines the API`, resourceType, logicalId);
27130
+ const tags = refuseMalformedDesiredTags(properties["Tags"], resourceType, logicalId);
27131
+ let restApiId;
27132
+ try {
27133
+ const body = await resolveRestApiBody.call(this, logicalId, resourceType, properties, log.value);
27134
+ const createdName = body && !cloneFrom ? definitionTitle(body) : name;
27135
+ const desiredEc = asRecord$2(properties["EndpointConfiguration"]);
27136
+ const reportOrphans = async (lookupWindow) => {
27137
+ const aws = pasteableAwsCommand(log.mask);
27138
+ const regionArg = await this.orphanCommandRegionArg(aws);
27139
+ await reportPossibleOrphans(logicalId, lookupWindow, log, {
27140
+ action: body && !cloneFrom ? "ImportRestApi" : "CreateRestApi",
27141
+ listAction: "GetRestApis",
27142
+ subject: createdName ? `a REST API named ${log.value(createdName)}` : "a REST API",
27143
+ noun: "REST API(s)",
27144
+ ...createdName === void 0 && { afterward: "The definition is not JSON, so its title could not be read: every REST API created in that window is listed, which can include another deploy or process. Creating a new one now." },
27145
+ list: () => collectOrphanIds(async (position) => {
27146
+ const page = await this.apiGatewayClient.send(new GetRestApisCommand({
27147
+ limit: 500,
27148
+ ...position && { position }
27149
+ }));
27150
+ return {
27151
+ items: page.items ?? [],
27152
+ next: page.position
27153
+ };
27154
+ }, (a) => a.id && (createdName === void 0 || a.name === createdName) && isInsideWindow(a.createdDate, lookupWindow) && !restApisCreatedByThisProcess.has(a.id) ? a.id : void 0),
27155
+ inspect: (id) => aws`aws apigateway get-rest-api --rest-api-id ${id}${regionArg}`.render(),
27156
+ remove: (id) => aws`aws apigateway delete-rest-api --rest-api-id ${id}${regionArg}`.render()
27157
+ });
27158
+ };
27159
+ const orphanWindow = createRestApiLatch.take(logicalId);
27160
+ if (orphanWindow !== void 0) await reportOrphans(orphanWindow);
27161
+ const createClient = await this.getCreateClient();
27162
+ const attemptStartMs = Date.now();
27163
+ let response;
27164
+ try {
27165
+ if (body && !cloneFrom) {
27166
+ const parameters = bodyParameters(properties["Parameters"]) ?? {};
27167
+ const type = endpointType(desiredEc);
27168
+ if (type !== void 0 && parameters["endpointConfigurationTypes"] === void 0) parameters["endpointConfigurationTypes"] = type;
27169
+ response = await createClient.send(new ImportRestApiCommand({
27170
+ body,
27171
+ failOnWarnings: properties["FailOnWarnings"] === true,
27172
+ ...Object.keys(parameters).length > 0 && { parameters }
27173
+ }));
27174
+ } else response = await createClient.send(new CreateRestApiCommand({
27175
+ name,
27176
+ description: properties["Description"],
27177
+ version: properties["Version"],
27178
+ cloneFrom,
27179
+ binaryMediaTypes: stringList(properties["BinaryMediaTypes"]),
27180
+ minimumCompressionSize: properties["MinimumCompressionSize"],
27181
+ apiKeySource: properties["ApiKeySourceType"],
27182
+ endpointConfiguration: desiredEc ? {
27183
+ types: stringList(desiredEc["Types"]),
27184
+ vpcEndpointIds: stringList(desiredEc["VpcEndpointIds"]),
27185
+ ipAddressType: desiredEc["IpAddressType"]
27186
+ } : void 0,
27187
+ policy: restApiPolicyString(properties["Policy"]),
27188
+ tags: tags.length > 0 ? Object.fromEntries(tags.map((t) => [t.Key, t.Value])) : void 0,
27189
+ disableExecuteApiEndpoint: properties["DisableExecuteApiEndpoint"],
27190
+ securityPolicy: properties["SecurityPolicy"],
27191
+ endpointAccessMode: properties["EndpointAccessMode"]
27192
+ }));
27193
+ } catch (error) {
27194
+ createRestApiLatch.noteFailure(logicalId, error, attemptStartMs, orphanWindow);
27195
+ throw error;
27196
+ }
27197
+ if (!response.id) throw new ProvisioningError(`API Gateway answered no id for RestApi ${logicalId}`, resourceType, logicalId);
27198
+ restApiId = response.id;
27199
+ restApisCreatedByThisProcess.add(restApiId);
27200
+ const replayWindow = replayedSendWindow(response, attemptStartMs);
27201
+ if (replayWindow !== void 0) await reportOrphans(replayWindow);
27202
+ let rootResourceId = response.rootResourceId;
27203
+ if (body) {
27204
+ let live = restApiAsCfn(response, properties["Policy"]);
27205
+ if (cloneFrom) {
27206
+ const put = await this.apiGatewayClient.send(new PutRestApiCommand({
27207
+ restApiId,
27208
+ mode: properties["Mode"] ?? "overwrite",
27209
+ failOnWarnings: properties["FailOnWarnings"] === true,
27210
+ parameters: bodyParameters(properties["Parameters"]),
27211
+ body
27212
+ }));
27213
+ live = restApiAsCfn(put, properties["Policy"]);
27214
+ rootResourceId = put.rootResourceId ?? rootResourceId;
27215
+ }
27216
+ const patchOperations = restApiPatchOperations(properties, live, {}, cloneFrom ? properties["Mode"] ?? "overwrite" : "overwrite");
27217
+ if (patchOperations.length > 0) await this.apiGatewayClient.send(new UpdateRestApiCommand({
27218
+ restApiId,
27219
+ patchOperations
27220
+ }));
27221
+ if (tags.length > 0 && !cloneFrom) await this.apiGatewayClient.send(new TagResourceCommand$3({
27222
+ resourceArn: await restApiArn.call(this, restApiId),
27223
+ tags: Object.fromEntries(tags.map((t) => [t.Key, t.Value]))
27224
+ }));
27225
+ }
27226
+ if (rootResourceId === void 0) rootResourceId = (await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId }))).rootResourceId;
27227
+ log.debug(safeMsg`Successfully created API Gateway RestApi ${logicalId}: ${restApiId}`);
27228
+ return {
27229
+ physicalId: restApiId,
27230
+ attributes: {
27231
+ RestApiId: restApiId,
27232
+ ...rootResourceId !== void 0 ? { RootResourceId: rootResourceId } : {}
27233
+ }
27234
+ };
27235
+ } catch (error) {
27236
+ if (error instanceof CdkdError && restApiId === void 0) throw error;
27237
+ const cause = error instanceof Error ? error : void 0;
27238
+ const survivor = restApiId === void 0 ? "" : await retireFailedRestApi.call(this, restApiId, log);
27239
+ throw this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to create API Gateway RestApi ${logicalId}: ${text}${survivor}`, resourceType, logicalId, void 0, cause));
27240
+ }
27241
+ }
27242
+ async function retireFailedRestApi(restApiId, log) {
27243
+ try {
27244
+ await this.apiGatewayClient.send(new DeleteRestApiCommand({ restApiId }));
27245
+ log.debug(safeMsg`Deleted REST API ${restApiId} left by the failed create`);
27246
+ return "";
27247
+ } catch (cleanupError) {
27248
+ if (cleanupError instanceof NotFoundException$1) return "";
27249
+ const aws = pasteableAwsCommand(log.mask);
27250
+ const regionArg = await this.orphanCommandRegionArg(aws);
27251
+ return ` The REST API ${restApiId} it created could not be deleted (${describeAwsFailure(cleanupError).summary}); delete it with: ` + aws`aws apigateway delete-rest-api --rest-api-id ${restApiId}${regionArg}`.render();
27252
+ }
27253
+ }
27254
+ async function updateRestApi(logicalId, physicalId, resourceType, properties, previousProperties, log, changedProperties, noEchoOnlyChanged, keptNoEchoOnly) {
27255
+ refuseMalformedDesiredTags(properties["Tags"], resourceType, logicalId, physicalId);
27256
+ try {
27257
+ let current = previousProperties;
27258
+ let bodyPutMode;
27259
+ let rootResourceId;
27260
+ let bodyChanged = changedProperties !== void 0 ? declaresBody(properties) && BODY_KEYS.some((key) => changedProperties.has(key)) : restApiBodyChanged(properties, previousProperties, log.mask);
27261
+ if (bodyChanged && changedProperties !== void 0 && noEchoOnlyChanged !== void 0) {
27262
+ const named = BODY_KEYS.filter((key) => changedProperties.has(key));
27263
+ if (named.length > 0 && named.every((key) => noEchoOnlyChanged.has(key))) {
27264
+ bodyChanged = false;
27265
+ for (const key of named) keptNoEchoOnly?.(key);
27266
+ log.warn(safeMsg`${logicalId} (${resourceType}): its Body embeds a NoEcho parameter value that cdkd could not compare with the value it last sent, so the OpenAPI definition is not put again, and a change to that value alone is NOT applied by this deploy. cdkd compares it once a deploy can call kms:GenerateMac on the key 'cdkd bootstrap' creates, the Body reads nothing but NoEcho parameters and literals, and a put has recorded the value's MAC. To apply a change now, change a part of the Body that is not masked (its description or a version field, for example) in the same deploy.`);
27267
+ }
27268
+ }
27269
+ if (bodyChanged) {
27270
+ const body = await resolveRestApiBody.call(this, logicalId, resourceType, properties, log.value, physicalId);
27271
+ const put = await this.apiGatewayClient.send(new PutRestApiCommand({
27272
+ restApiId: physicalId,
27273
+ mode: properties["Mode"] ?? "overwrite",
27274
+ failOnWarnings: properties["FailOnWarnings"] === true,
27275
+ parameters: bodyParameters(properties["Parameters"]),
27276
+ body
27277
+ }));
27278
+ log.debug(safeMsg`Put the OpenAPI definition of API Gateway RestApi ${logicalId}: ${physicalId}`);
27279
+ current = restApiAsCfn(put, properties["Policy"]);
27280
+ bodyPutMode = properties["Mode"] ?? "overwrite";
27281
+ rootResourceId = put.rootResourceId;
27282
+ }
27283
+ const patchOperations = restApiPatchOperations(properties, current, previousProperties, bodyPutMode);
27284
+ if (patchOperations.length > 0) {
27285
+ await this.apiGatewayClient.send(new UpdateRestApiCommand({
27286
+ restApiId: physicalId,
27287
+ patchOperations
27288
+ }));
27289
+ log.debug(safeMsg`Updated API Gateway RestApi ${logicalId} (${patchOperations.length} patch ops)`);
27290
+ }
27291
+ const arn = await restApiArn.call(this, physicalId);
27292
+ await this.applyTagDiff(arn, resourceType, logicalId, previousProperties["Tags"], properties["Tags"], log, arn);
27293
+ return {
27294
+ physicalId,
27295
+ wasReplaced: false,
27296
+ ...rootResourceId !== void 0 ? { attributes: {
27297
+ RestApiId: physicalId,
27298
+ RootResourceId: rootResourceId
27299
+ } } : {}
27300
+ };
27301
+ } catch (error) {
27302
+ if (error instanceof CdkdError) throw error;
27303
+ const cause = error instanceof Error ? error : void 0;
27304
+ throw this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to update API Gateway RestApi ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
27305
+ }
27306
+ }
27307
+ async function deleteRestApi(logicalId, physicalId, resourceType, context) {
27308
+ this.logger.debug(safeMsg`Deleting API Gateway RestApi ${logicalId}: ${physicalId}`);
27309
+ try {
27310
+ await this.apiGatewayClient.send(new DeleteRestApiCommand({ restApiId: physicalId }));
27311
+ this.logger.debug(safeMsg`Successfully deleted API Gateway RestApi ${logicalId}`);
27312
+ } catch (error) {
27313
+ if (error instanceof NotFoundException$1) {
27314
+ const clientRegion = await this.apiGatewayClient.config.region();
27315
+ assertRegionMatch(clientRegion, context?.expectedRegion, resourceType, logicalId, physicalId);
27316
+ this.logger.debug(safeMsg`API Gateway RestApi ${physicalId} does not exist, skipping deletion`);
27317
+ return;
27318
+ }
27319
+ const cause = error instanceof Error ? error : void 0;
27320
+ const thrown = this.wrapMaskedError(context?.maskSecrets ?? ((text) => text), error, (text) => new ProvisioningError(`Failed to delete API Gateway RestApi ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
27321
+ throw error instanceof Error && error.name.includes("NotFound") ? markNotGone(thrown) : thrown;
27322
+ }
27323
+ }
27324
+ async function getRestApiAttribute(physicalId, attributeName) {
27325
+ if (attributeName === "RestApiId") return physicalId;
27326
+ if (attributeName === "RootResourceId") return (await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: physicalId }))).rootResourceId;
27327
+ }
27328
+ async function readCurrentStateRestApi(physicalId, properties) {
27329
+ try {
27330
+ const resp = await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: physicalId }));
27331
+ const result = restApiAsCfn(resp, properties?.["Policy"]);
27332
+ const fromDefinition = definitionBinaryMediaTypes(properties?.["Body"]);
27333
+ const declared = new Set(stringList(properties?.["BinaryMediaTypes"]) ?? []);
27334
+ const unreadable = properties?.["BodyS3Location"] != null || typeof properties?.["Body"] === "string" && !isJsonText(properties["Body"]);
27335
+ result["BinaryMediaTypes"] = result["BinaryMediaTypes"].filter((t) => unreadable ? declared.has(t) : !fromDefinition.has(t) || declared.has(t));
27336
+ result["Tags"] = Object.entries(resp.tags ?? {}).filter(([key]) => !key.startsWith("aws:")).map(([Key, Value]) => ({
27337
+ Key,
27338
+ Value
27339
+ }));
27340
+ return result;
27341
+ } catch (err) {
27342
+ if (err instanceof NotFoundException$1) return RESOURCE_NOT_FOUND;
27343
+ throw err;
27344
+ }
27345
+ }
27346
+ const REST_API_WRITE_ONLY_PATHS = [
27347
+ "Body",
27348
+ "BodyS3Location",
27349
+ "CloneFrom",
27350
+ "FailOnWarnings",
27351
+ "Mode",
27352
+ "Parameters"
27353
+ ];
27354
+ async function importRestApi(input) {
27355
+ if (!input.knownPhysicalId) return null;
27356
+ try {
27357
+ const resp = await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: input.knownPhysicalId }));
27358
+ return {
27359
+ physicalId: input.knownPhysicalId,
27360
+ attributes: {
27361
+ RestApiId: input.knownPhysicalId,
27362
+ ...resp.rootResourceId !== void 0 ? { RootResourceId: resp.rootResourceId } : {}
27363
+ }
27364
+ };
27365
+ } catch (err) {
27366
+ if (err instanceof NotFoundException$1) return null;
27367
+ throw err;
27368
+ }
27369
+ }
27370
+
27371
+ // src/provisioning/providers/apigateway/rest-api-own-write.ts
27372
+ async function settleRestApiPolicy(physicalId, logicalId, read, properties) {
27373
+ const declared = declaredMemberDocument(properties?.["Policy"]);
27374
+ if (declared === void 0 || read === void 0 || read === RESOURCE_NOT_FOUND) return read;
27375
+ const asMember = (policy) => policy === void 0 ? "absent" : { value: policy };
27376
+ const policy = await settleDeclaredMember(asMember(read["Policy"]), async () => {
27377
+ const resp = await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: physicalId }));
27378
+ return asMember(restApiAsCfn(resp, properties?.["Policy"])["Policy"]);
27379
+ }, (value) => policyDocumentMatchesDeclared(value, declared), declared, this.ownWriteRereadDelaysMs, () => warnUnsettledMember(this.logger, logicalId, "AWS::ApiGateway::RestApi", "Policy"));
27380
+ return typeof policy === "object" ? {
27381
+ ...read,
27382
+ Policy: policy.value
27383
+ } : read;
27384
+ }
27385
+
26800
27386
  // src/provisioning/providers/apigateway/core.ts
26801
27387
  function getCreateClient$7() {
26802
27388
  this.createClient ??= this.apiGatewayClient.config.region().then((region) => withoutServerErrorRetries(withApiGatewayPacing(new APIGatewayClient({
@@ -26846,7 +27432,7 @@ async function update$30(logicalId, physicalId, resourceType, properties, previo
26846
27432
  properties = withRemovalDefaults(this.removalDefaults, resourceType, properties, previousProperties, context);
26847
27433
  return this.updateAccount(logicalId, physicalId, resourceType, properties, log);
26848
27434
  case "AWS::ApiGateway::Authorizer": return this.updateAuthorizer(logicalId, physicalId, resourceType, properties, previousProperties, log);
26849
- case "AWS::ApiGateway::Resource": return this.updateResource(logicalId, physicalId, resourceType, properties, previousProperties, log);
27435
+ case "AWS::ApiGateway::Resource": return this.updateResource(logicalId, physicalId, resourceType, properties, previousProperties, log, context?.desiredFromAwsReadback === true);
26850
27436
  case "AWS::ApiGateway::Deployment": return this.updateDeployment(logicalId, physicalId, resourceType, properties, previousProperties, log);
26851
27437
  case "AWS::ApiGateway::Stage": return this.updateStage(logicalId, physicalId, resourceType, properties, previousProperties, stageSinks$1(this.logger, context, [[properties["StageName"], physicalId], [previousProperties["StageName"], physicalId]]));
26852
27438
  case "AWS::ApiGateway::Method": return this.updateMethod(logicalId, physicalId, resourceType, properties, previousProperties, log, context?.desiredFromAwsReadback === true);
@@ -27174,11 +27760,12 @@ async function createResource(logicalId, resourceType, properties, log) {
27174
27760
  throw this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to create API Gateway Resource ${logicalId}: ${text}`, resourceType, logicalId, void 0, cause));
27175
27761
  }
27176
27762
  }
27177
- async function updateResource(logicalId, physicalId, resourceType, properties, previousProperties, log) {
27763
+ async function updateResource(logicalId, physicalId, resourceType, properties, previousProperties, log, driftRevert = false) {
27178
27764
  log.debug(`Updating API Gateway Resource ${logicalId}: ${physicalId}`);
27179
27765
  const newPathPart = properties["PathPart"];
27180
27766
  const oldPathPart = previousProperties["PathPart"];
27181
27767
  if (newPathPart !== oldPathPart) {
27768
+ if (driftRevert) throw revertReplacementRefusal(resourceType, logicalId, "its PathPart differs from the live resource's, and cdkd would re-create the resource to revert it");
27182
27769
  log.debug(`PathPart changed from "${log.value(oldPathPart)}" to "${log.value(newPathPart)}", replacing resource`);
27183
27770
  const createResult = await this.createResource(logicalId, resourceType, properties, log);
27184
27771
  let orphanReason;
@@ -27624,715 +28211,233 @@ async function createMethod(logicalId, resourceType, properties, log, context) {
27624
28211
  const authorizationScopes = declaredScopes ? [...new Set(declaredScopes)] : void 0;
27625
28212
  if (!restApiId || !resourceId || !httpMethod) throw new ProvisioningError(`RestApiId, ResourceId, and HttpMethod are required for API Gateway Method ${logicalId}`, resourceType, logicalId);
27626
28213
  const physicalId = packCompositeId(resourceType, logicalId, [
27627
- {
27628
- name: "restApiId",
27629
- value: restApiId
27630
- },
27631
- {
27632
- name: "resourceId",
27633
- value: resourceId
27634
- },
27635
- {
27636
- name: "httpMethod",
27637
- value: httpMethod
27638
- }
27639
- ], {
27640
- maskSecrets: log.mask,
27641
- ...context?.replayingState === true && { onRefusal: (message) => log.warn(message) }
27642
- });
27643
- const maskedIds = [
27644
- restApiId,
27645
- resourceId,
27646
- httpMethod
27647
- ].map((id) => log.value(id));
27648
- const methodPath = maskedIds.join("/");
27649
- let methodLeftBehind = false;
27650
- try {
27651
- const putMethod = () => this.apiGatewayClient.send(new PutMethodCommand({
27652
- restApiId,
27653
- resourceId,
27654
- httpMethod,
27655
- authorizationType,
27656
- authorizerId,
27657
- apiKeyRequired,
27658
- operationName,
27659
- requestParameters: methodRequestParameters,
27660
- requestModels,
27661
- requestValidatorId,
27662
- authorizationScopes
27663
- }));
27664
- try {
27665
- await putMethod();
27666
- } catch (putError) {
27667
- if (!isMethodAlreadyExists(putError) || !await this.priorAttemptLeftMethod(logicalId, physicalId, log)) throw putError;
27668
- log.warn(`Replacing API Gateway Method ${logicalId} (${methodPath}), which an earlier failed attempt of it left behind`);
27669
- try {
27670
- await this.apiGatewayClient.send(new DeleteMethodCommand({
27671
- restApiId,
27672
- resourceId,
27673
- httpMethod
27674
- }));
27675
- } catch (deleteError) {
27676
- if (!(deleteError instanceof NotFoundException$1)) throw deleteError;
27677
- }
27678
- await putMethod();
27679
- }
27680
- reportCreatedResource(logicalId, resourceType, physicalId);
27681
- try {
27682
- const integration = properties["Integration"];
27683
- if (integration) await this.apiGatewayClient.send(new PutIntegrationCommand(putIntegrationInput({
27684
- restApiId,
27685
- resourceId,
27686
- httpMethod
27687
- }, integration)));
27688
- const methodResponses = properties["MethodResponses"];
27689
- if (methodResponses) for (const resp of methodResponses) await this.apiGatewayClient.send(new PutMethodResponseCommand(putMethodResponseInput({
27690
- restApiId,
27691
- resourceId,
27692
- httpMethod
27693
- }, resp)));
27694
- if (integration) {
27695
- const integrationResponses = integration["IntegrationResponses"];
27696
- if (integrationResponses) for (const ir of integrationResponses) await this.apiGatewayClient.send(new PutIntegrationResponseCommand(putIntegrationResponseInput({
27697
- restApiId,
27698
- resourceId,
27699
- httpMethod
27700
- }, ir)));
27701
- }
27702
- } catch (innerError) {
27703
- try {
27704
- await this.apiGatewayClient.send(new DeleteMethodCommand({
27705
- restApiId,
27706
- resourceId,
27707
- httpMethod
27708
- }));
27709
- retractCreatedResource(logicalId, resourceType, physicalId);
27710
- log.debug(`Cleaned up partially-created API Gateway Method ${logicalId} (${methodPath}) after wiring failure`);
27711
- } catch (cleanupError) {
27712
- methodLeftBehind = true;
27713
- getPriorAttempts(logicalId)?.notePossiblyLanded();
27714
- const cleanupFailure = describeAwsFailure(cleanupError);
27715
- const cleanupHead = `Failed to clean up partially-created API Gateway Method ${logicalId} (${methodPath}): `;
27716
- if (cleanupFailure.redacted) log.debug(`${cleanupHead}${cleanupFailure.detail}`);
27717
- log.warn(`${cleanupHead}${cleanupFailure.redacted ? `${cleanupFailure.summary} ` : `${cleanupFailure.detail}. `}Manual deletion may be required before the next deploy: ${pasteableAwsCommand(log.mask)`aws apigateway delete-method --rest-api-id ${restApiId} --resource-id ${resourceId} --http-method ${httpMethod}`.render()}`);
27718
- }
27719
- throw markAuxiliaryFailure(innerError, logicalId);
27720
- }
27721
- log.debug(`Successfully created API Gateway Method ${logicalId}: ${maskedIds.join("|")}`);
27722
- return {
27723
- physicalId,
27724
- attributes: {}
27725
- };
27726
- } catch (error) {
27727
- const cause = error instanceof Error ? error : void 0;
27728
- const thrown = this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to create API Gateway Method ${logicalId}: ${text}`, resourceType, logicalId, void 0, cause));
27729
- if (methodLeftBehind) markCreatedBeforeFailure(thrown, logicalId, resourceType, physicalId);
27730
- throw thrown;
27731
- }
27732
- }
27733
- async function priorAttemptLeftMethod(logicalId, physicalId, log) {
27734
- const lookup = getPriorAttempts(logicalId);
27735
- if (lookup === void 0) return false;
27736
- if (lookup.possiblyLanded()) return true;
27737
- if (lookup.provenOrphanIds === void 0) return false;
27738
- try {
27739
- return (await lookup.provenOrphanIds()).includes(physicalId);
27740
- } catch (error) {
27741
- log.debug(`API Gateway Method ${logicalId}: rollback journal read failed: ${describeAwsFailure(error).detail}`);
27742
- return false;
27743
- }
27744
- }
27745
- async function updateMethod(logicalId, physicalId, resourceType, properties, previousProperties, log, previousIsLiveReadback = false) {
27746
- const parts = physicalId.split("|");
27747
- const maskedId = parts.map((p) => log.value(p)).join("|");
27748
- log.debug(`Updating API Gateway Method ${logicalId}: ${maskedId}`);
27749
- if (parts.length !== 3) throw new ProvisioningError(compositeIdFormatMessage(APIGW_METHOD_ID_FORMAT, logicalId, maskedId), resourceType, logicalId, physicalId);
27750
- const [restApiId, resourceId, httpMethod] = parts;
27751
- const patchOperations = [];
27752
- for (const { key, path } of [
27753
- {
27754
- key: "AuthorizationType",
27755
- path: "/authorizationType"
27756
- },
27757
- {
27758
- key: "AuthorizerId",
27759
- path: "/authorizerId"
27760
- },
27761
- {
27762
- key: "ApiKeyRequired",
27763
- path: "/apiKeyRequired"
27764
- },
27765
- {
27766
- key: "OperationName",
27767
- path: "/operationName"
27768
- },
27769
- {
27770
- key: "RequestValidatorId",
27771
- path: "/requestValidatorId"
27772
- }
27773
- ]) {
27774
- const newVal = properties[key];
27775
- if (newVal !== previousProperties[key]) patchOperations.push({
27776
- op: "replace",
27777
- path,
27778
- value: newVal !== void 0 ? stringifyValue(newVal) : ""
27779
- });
27780
- }
27781
- appendMapPatchOps(patchOperations, "/requestParameters", properties["RequestParameters"] ?? {}, previousProperties["RequestParameters"] ?? {});
27782
- appendMapPatchOps(patchOperations, "/requestModels", properties["RequestModels"] ?? {}, previousProperties["RequestModels"] ?? {});
27783
- const scopeOps = listPatchOps("/authorizationScopes", properties["AuthorizationScopes"], previousProperties["AuthorizationScopes"], {
27784
- asSet: true,
27785
- removeEveryPrevOccurrence: previousIsLiveReadback
27786
- });
27787
- patchOperations.push(...scopeOps.adds, ...scopeOps.removes);
27788
- const childCalls = methodChildCalls({
27789
- restApiId,
27790
- resourceId,
27791
- httpMethod
27792
- }, properties, previousProperties);
27793
- if (patchOperations.length === 0 && childCalls.length === 0) {
27794
- log.debug(`No changes detected for API Gateway Method ${logicalId}`);
27795
- return {
27796
- physicalId,
27797
- wasReplaced: false
27798
- };
27799
- }
27800
- try {
27801
- if (patchOperations.length > 0) await this.apiGatewayClient.send(new UpdateMethodCommand({
27802
- restApiId,
27803
- resourceId,
27804
- httpMethod,
27805
- patchOperations
27806
- }));
27807
- for (const call of childCalls) try {
27808
- await this.apiGatewayClient.send(call.command);
27809
- } catch (error) {
27810
- if (!(call.kind === "delete" && error instanceof NotFoundException$1)) throw error;
27811
- }
27812
- log.debug(`Successfully updated API Gateway Method ${logicalId} (${patchOperations.length} patch ops, ${childCalls.length} sub-resource calls)`);
27813
- return {
27814
- physicalId,
27815
- wasReplaced: false
27816
- };
27817
- } catch (error) {
27818
- const cause = error instanceof Error ? error : void 0;
27819
- throw this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to update API Gateway Method ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
27820
- }
27821
- }
27822
- async function deleteMethod(logicalId, physicalId, resourceType, context) {
27823
- this.logger.debug(`Deleting API Gateway Method ${logicalId}: ${physicalId}`);
27824
- const parts = physicalId.split("|");
27825
- if (parts.length !== 3) throw new ProvisioningError(compositeIdFormatMessage(APIGW_METHOD_ID_FORMAT, logicalId, physicalId), resourceType, logicalId, physicalId);
27826
- const [restApiId, resourceId, httpMethod] = parts;
27827
- try {
27828
- await this.apiGatewayClient.send(new DeleteMethodCommand({
27829
- restApiId,
27830
- resourceId,
27831
- httpMethod
27832
- }));
27833
- this.logger.debug(`Successfully deleted API Gateway Method ${logicalId}`);
27834
- } catch (error) {
27835
- if (error instanceof NotFoundException$1) {
27836
- const clientRegion = await this.apiGatewayClient.config.region();
27837
- assertRegionMatch(clientRegion, context?.expectedRegion, resourceType, logicalId, physicalId);
27838
- this.logger.debug(`API Gateway Method ${physicalId} does not exist, skipping deletion`);
27839
- return;
27840
- }
27841
- const cause = error instanceof Error ? error : void 0;
27842
- const thrown = this.wrapMaskedError(context?.maskSecrets ?? ((text) => text), error, (text) => new ProvisioningError(`Failed to delete API Gateway Method ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
27843
- throw error instanceof Error && error.name.includes("NotFound") ? markNotGone(thrown) : thrown;
27844
- }
27845
- }
27846
- function getMethodAttribute(physicalId, attributeName) {
27847
- const parts = physicalId.split("|");
27848
- if (parts.length === 3) {
27849
- if (attributeName === "RestApiId") return Promise.resolve(parts[0]);
27850
- if (attributeName === "ResourceId") return Promise.resolve(parts[1]);
27851
- if (attributeName === "HttpMethod") return Promise.resolve(parts[2]);
27852
- }
27853
- return Promise.resolve(void 0);
27854
- }
27855
-
27856
- // src/provisioning/providers/apigateway/rest-api.ts
27857
- const BODY_KEYS = [
27858
- "Body",
27859
- "BodyS3Location",
27860
- "Mode",
27861
- "FailOnWarnings",
27862
- "Parameters"
27863
- ];
27864
- const SCALAR_FIELDS = [
27865
- {
27866
- key: "Name",
27867
- path: "/name"
27868
- },
27869
- {
27870
- key: "Description",
27871
- path: "/description"
27872
- },
27873
- {
27874
- key: "Version",
27875
- path: "/version"
27876
- },
27877
- {
27878
- key: "MinimumCompressionSize",
27879
- path: "/minimumCompressionSize"
27880
- },
27881
- {
27882
- key: "ApiKeySourceType",
27883
- path: "/apiKeySource"
27884
- },
27885
- {
27886
- key: "DisableExecuteApiEndpoint",
27887
- path: "/disableExecuteApiEndpoint"
27888
- },
27889
- {
27890
- key: "SecurityPolicy",
27891
- path: "/securityPolicy"
27892
- },
27893
- {
27894
- key: "EndpointAccessMode",
27895
- path: "/endpointAccessMode"
27896
- }
27897
- ];
27898
- function pointerSegment(value) {
27899
- return value.replace(/~/g, "~0").replace(/\//g, "~1");
27900
- }
27901
- function stringList(value) {
27902
- if (!Array.isArray(value)) return void 0;
27903
- return value.filter((v) => typeof v === "string");
27904
- }
27905
- function asRecord$2(value) {
27906
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
27907
- }
27908
- function restApiPolicyString(policy) {
27909
- if (policy === void 0 || policy === null) return void 0;
27910
- return typeof policy === "string" ? policy : JSON.stringify(policy);
27911
- }
27912
- function parseRestApiPolicy(raw, restApiId, recorded) {
27913
- if (raw === void 0 || raw === "") return void 0;
27914
- let text = raw;
27915
- let parsed;
27916
- try {
27917
- parsed = JSON.parse(text);
27918
- } catch {
27919
- text = raw.replace(/\\(["\\/])/g, "$1");
27920
- try {
27921
- parsed = JSON.parse(text);
27922
- } catch {
27923
- return raw;
27924
- }
27925
- }
27926
- const recordedText = restApiPolicyString(recorded);
27927
- if (recordedText !== void 0 && recordedText.includes("execute-api:/")) {
27928
- const expanded = new RegExp(`arn:[a-z-]+:execute-api:[a-z0-9-]+:\\d{12}:${restApiId}/`, "g");
27929
- parsed = JSON.parse(JSON.stringify(parsed).replace(expanded, "execute-api:/"));
27930
- }
27931
- return parsed;
27932
- }
27933
- function restApiAsCfn(api, recordedPolicy) {
27934
- const out = {};
27935
- if (api.name !== void 0) out["Name"] = api.name;
27936
- if (api.description !== void 0) out["Description"] = api.description;
27937
- if (api.version !== void 0) out["Version"] = api.version;
27938
- out["BinaryMediaTypes"] = api.binaryMediaTypes ? [...api.binaryMediaTypes] : [];
27939
- if (api.minimumCompressionSize !== void 0) out["MinimumCompressionSize"] = api.minimumCompressionSize;
27940
- if (api.apiKeySource !== void 0) out["ApiKeySourceType"] = api.apiKeySource;
27941
- if (api.disableExecuteApiEndpoint !== void 0) out["DisableExecuteApiEndpoint"] = api.disableExecuteApiEndpoint;
27942
- const policy = parseRestApiPolicy(api.policy, api.id ?? "", recordedPolicy);
27943
- if (policy !== void 0) out["Policy"] = policy;
27944
- if (api.endpointConfiguration !== void 0) {
27945
- const ec = {};
27946
- if (api.endpointConfiguration.types !== void 0) ec["Types"] = [...api.endpointConfiguration.types];
27947
- if (api.endpointConfiguration.vpcEndpointIds !== void 0) ec["VpcEndpointIds"] = [...api.endpointConfiguration.vpcEndpointIds];
27948
- if (api.endpointConfiguration.ipAddressType !== void 0) ec["IpAddressType"] = api.endpointConfiguration.ipAddressType;
27949
- out["EndpointConfiguration"] = ec;
27950
- }
27951
- if (api.securityPolicy !== void 0) out["SecurityPolicy"] = api.securityPolicy;
27952
- if (api.endpointAccessMode !== void 0) out["EndpointAccessMode"] = api.endpointAccessMode;
27953
- return out;
27954
- }
27955
- function definitionBinaryMediaTypes(body) {
27956
- let definition = body;
27957
- if (typeof body === "string") try {
27958
- definition = JSON.parse(body);
27959
- } catch {
27960
- return /* @__PURE__ */ new Set();
27961
- }
27962
- return new Set(stringList(asRecord$2(definition)?.["x-amazon-apigateway-binary-media-types"]) ?? []);
27963
- }
27964
- function isJsonText(text) {
27965
- try {
27966
- JSON.parse(text);
27967
- return true;
27968
- } catch {
27969
- return false;
27970
- }
27971
- }
27972
- function endpointType(config) {
27973
- return stringList(asRecord$2(config)?.["Types"])?.[0];
27974
- }
27975
- function restApiPatchOperations(desired, current, previous, bodyPutMode) {
27976
- const ops = [];
27977
- for (const { key, path } of SCALAR_FIELDS) {
27978
- const next = desired[key];
27979
- if (next === void 0 || next === null) continue;
27980
- const value = stringifyValue(next);
27981
- if (value !== (current[key] == null ? "" : stringifyValue(current[key]))) ops.push({
27982
- op: "replace",
27983
- path,
27984
- value
27985
- });
27986
- }
27987
- const nextPolicy = restApiPolicyString(desired["Policy"]);
27988
- if (nextPolicy !== void 0 && nextPolicy !== restApiPolicyString(current["Policy"])) ops.push({
27989
- op: "replace",
27990
- path: "/policy",
27991
- value: nextPolicy
27992
- });
27993
- const targetTypes = stringList(desired["BinaryMediaTypes"]) ?? (previous["BinaryMediaTypes"] !== void 0 ? [] : void 0);
27994
- if (targetTypes !== void 0) {
27995
- const live = new Set(stringList(current["BinaryMediaTypes"]) ?? []);
27996
- const target = new Set(targetTypes);
27997
- const fromDefinition = definitionBinaryMediaTypes(desired["Body"]);
27998
- const dropped = bodyPutMode === "overwrite" ? [] : stringList(previous["BinaryMediaTypes"]) ?? [];
27999
- for (const t of new Set(dropped)) if (live.has(t) && !target.has(t) && !fromDefinition.has(t)) ops.push({
28000
- op: "remove",
28001
- path: `/binaryMediaTypes/${pointerSegment(t)}`
28002
- });
28003
- for (const t of target) if (!live.has(t)) ops.push({
28004
- op: "add",
28005
- path: `/binaryMediaTypes/${pointerSegment(t)}`
28006
- });
28007
- }
28008
- const desiredEc = asRecord$2(desired["EndpointConfiguration"]);
28009
- const currentEc = asRecord$2(current["EndpointConfiguration"]);
28010
- const targetType = endpointType(desiredEc) ?? (previous["EndpointConfiguration"] !== void 0 ? "EDGE" : void 0);
28011
- const currentType = endpointType(currentEc) ?? "EDGE";
28012
- if (targetType !== void 0 && targetType !== currentType) ops.push({
28013
- op: "replace",
28014
- path: `/endpointConfiguration/types/${currentType}`,
28015
- value: targetType
28016
- });
28017
- if (desiredEc !== void 0) {
28018
- const nextIds = stringList(desiredEc["VpcEndpointIds"]);
28019
- if (nextIds !== void 0 || targetType === "PRIVATE") {
28020
- const live = new Set(stringList(currentEc?.["VpcEndpointIds"]) ?? []);
28021
- const target = new Set(nextIds ?? []);
28022
- for (const id of target) if (!live.has(id)) ops.push({
28023
- op: "add",
28024
- path: "/endpointConfiguration/vpcEndpointIds",
28025
- value: id
28026
- });
28027
- for (const id of live) if (!target.has(id)) ops.push({
28028
- op: "remove",
28029
- path: "/endpointConfiguration/vpcEndpointIds",
28030
- value: id
28031
- });
28032
- }
28033
- const ipType = desiredEc["IpAddressType"];
28034
- if (typeof ipType === "string" && ipType !== currentEc?.["IpAddressType"]) ops.push({
28035
- op: "replace",
28036
- path: "/endpointConfiguration/ipAddressType",
28037
- value: ipType
28038
- });
28039
- }
28040
- return ops;
28041
- }
28042
- function declaresBody(properties) {
28043
- return properties["Body"] != null || properties["BodyS3Location"] != null;
28044
- }
28045
- function restApiBodyChanged(desired, previous, maskSecrets) {
28046
- if (!declaresBody(desired)) return false;
28047
- return BODY_KEYS.some((key) => !isDeepStrictEqual(desired[key], previous[key]) && !onlySecretReferencesDiffer(desired[key], previous[key], maskSecrets));
28048
- }
28049
- function definitionTitle(body) {
28050
- try {
28051
- const info = asRecord$2(asRecord$2(JSON.parse(new TextDecoder().decode(body)))?.["info"]);
28052
- return typeof info?.["title"] === "string" ? info["title"] : void 0;
28053
- } catch {
28054
- return;
28055
- }
28056
- }
28057
- function bodyParameters(value) {
28058
- const record = asRecord$2(value);
28059
- if (record === void 0) return void 0;
28060
- return Object.fromEntries(Object.entries(record).map(([k, v]) => [k, String(v)]));
28061
- }
28062
- async function resolveRestApiBody(logicalId, resourceType, properties, mask, physicalId) {
28063
- const body = properties["Body"];
28064
- if (body !== void 0 && body !== null) {
28065
- if (typeof body === "string") return new TextEncoder().encode(body);
28066
- if (typeof body === "object") return new TextEncoder().encode(JSON.stringify(body));
28067
- throw new ProvisioningError(`Body of ${resourceType} ${logicalId} must be an OpenAPI definition object or string`, resourceType, logicalId, physicalId);
28068
- }
28069
- const location = asRecord$2(properties["BodyS3Location"]);
28070
- if (properties["BodyS3Location"] == null) return void 0;
28071
- const bucket = location?.["Bucket"];
28072
- const key = location?.["Key"];
28073
- if (typeof bucket !== "string" || typeof key !== "string" || !bucket || !key) throw new ProvisioningError(`BodyS3Location of ${resourceType} ${logicalId} must name a Bucket and a Key`, resourceType, logicalId, physicalId);
28074
- const version = location?.["Version"];
28075
- const etag = location?.["ETag"];
28076
- const resp = await getAwsClients().s3.send(new GetObjectCommand({
28077
- Bucket: bucket,
28078
- Key: key,
28079
- ...typeof version === "string" && version && { VersionId: version },
28080
- ...typeof etag === "string" && etag && { IfMatch: etag }
28081
- }));
28082
- const bytes = resp.Body ? await resp.Body.transformToByteArray() : void 0;
28083
- if (!bytes || bytes.length === 0) throw new ProvisioningError(`BodyS3Location of ${resourceType} ${logicalId} (s3://${mask(bucket)}/${mask(key)}) holds no definition`, resourceType, logicalId, physicalId);
28084
- return bytes;
28085
- }
28086
- async function restApiArn(restApiId) {
28087
- const region = await this.apiGatewayClient.config.region();
28088
- const { partition } = derivePartitionAndUrlSuffix(region);
28089
- return `arn:${partition}:apigateway:${region}::/restapis/${restApiId}`;
28090
- }
28091
- async function createRestApi(logicalId, resourceType, properties, log) {
28092
- log.debug(safeMsg`Creating API Gateway RestApi ${logicalId}`);
28093
- const name = typeof properties["Name"] === "string" ? properties["Name"] : void 0;
28094
- const cloneFrom = typeof properties["CloneFrom"] === "string" ? properties["CloneFrom"] : void 0;
28095
- const hasBody = declaresBody(properties);
28096
- if (!name && (!hasBody || cloneFrom)) throw new ProvisioningError(`Name is required for API Gateway RestApi ${logicalId} unless Body or BodyS3Location defines the API`, resourceType, logicalId);
28097
- const tags = refuseMalformedDesiredTags(properties["Tags"], resourceType, logicalId);
28098
- let restApiId;
28214
+ {
28215
+ name: "restApiId",
28216
+ value: restApiId
28217
+ },
28218
+ {
28219
+ name: "resourceId",
28220
+ value: resourceId
28221
+ },
28222
+ {
28223
+ name: "httpMethod",
28224
+ value: httpMethod
28225
+ }
28226
+ ], {
28227
+ maskSecrets: log.mask,
28228
+ ...context?.replayingState === true && { onRefusal: (message) => log.warn(message) }
28229
+ });
28230
+ const maskedIds = [
28231
+ restApiId,
28232
+ resourceId,
28233
+ httpMethod
28234
+ ].map((id) => log.value(id));
28235
+ const methodPath = maskedIds.join("/");
28236
+ let methodLeftBehind = false;
28099
28237
  try {
28100
- const body = await resolveRestApiBody.call(this, logicalId, resourceType, properties, log.value);
28101
- const createdName = body && !cloneFrom ? definitionTitle(body) : name;
28102
- const desiredEc = asRecord$2(properties["EndpointConfiguration"]);
28103
- const reportOrphans = async (lookupWindow) => {
28104
- const aws = pasteableAwsCommand(log.mask);
28105
- const regionArg = await this.orphanCommandRegionArg(aws);
28106
- await reportPossibleOrphans(logicalId, lookupWindow, log, {
28107
- action: body && !cloneFrom ? "ImportRestApi" : "CreateRestApi",
28108
- listAction: "GetRestApis",
28109
- subject: createdName ? `a REST API named ${log.value(createdName)}` : "a REST API",
28110
- noun: "REST API(s)",
28111
- ...createdName === void 0 && { afterward: "The definition is not JSON, so its title could not be read: every REST API created in that window is listed, which can include another deploy or process. Creating a new one now." },
28112
- list: () => collectOrphanIds(async (position) => {
28113
- const page = await this.apiGatewayClient.send(new GetRestApisCommand({
28114
- limit: 500,
28115
- ...position && { position }
28116
- }));
28117
- return {
28118
- items: page.items ?? [],
28119
- next: page.position
28120
- };
28121
- }, (a) => a.id && (createdName === void 0 || a.name === createdName) && isInsideWindow(a.createdDate, lookupWindow) && !restApisCreatedByThisProcess.has(a.id) ? a.id : void 0),
28122
- inspect: (id) => aws`aws apigateway get-rest-api --rest-api-id ${id}${regionArg}`.render(),
28123
- remove: (id) => aws`aws apigateway delete-rest-api --rest-api-id ${id}${regionArg}`.render()
28124
- });
28125
- };
28126
- const orphanWindow = createRestApiLatch.take(logicalId);
28127
- if (orphanWindow !== void 0) await reportOrphans(orphanWindow);
28128
- const createClient = await this.getCreateClient();
28129
- const attemptStartMs = Date.now();
28130
- let response;
28238
+ const putMethod = () => this.apiGatewayClient.send(new PutMethodCommand({
28239
+ restApiId,
28240
+ resourceId,
28241
+ httpMethod,
28242
+ authorizationType,
28243
+ authorizerId,
28244
+ apiKeyRequired,
28245
+ operationName,
28246
+ requestParameters: methodRequestParameters,
28247
+ requestModels,
28248
+ requestValidatorId,
28249
+ authorizationScopes
28250
+ }));
28131
28251
  try {
28132
- if (body && !cloneFrom) {
28133
- const parameters = bodyParameters(properties["Parameters"]) ?? {};
28134
- const type = endpointType(desiredEc);
28135
- if (type !== void 0 && parameters["endpointConfigurationTypes"] === void 0) parameters["endpointConfigurationTypes"] = type;
28136
- response = await createClient.send(new ImportRestApiCommand({
28137
- body,
28138
- failOnWarnings: properties["FailOnWarnings"] === true,
28139
- ...Object.keys(parameters).length > 0 && { parameters }
28252
+ await putMethod();
28253
+ } catch (putError) {
28254
+ if (!isMethodAlreadyExists(putError) || !await this.priorAttemptLeftMethod(logicalId, physicalId, log)) throw putError;
28255
+ log.warn(`Replacing API Gateway Method ${logicalId} (${methodPath}), which an earlier failed attempt of it left behind`);
28256
+ try {
28257
+ await this.apiGatewayClient.send(new DeleteMethodCommand({
28258
+ restApiId,
28259
+ resourceId,
28260
+ httpMethod
28140
28261
  }));
28141
- } else response = await createClient.send(new CreateRestApiCommand({
28142
- name,
28143
- description: properties["Description"],
28144
- version: properties["Version"],
28145
- cloneFrom,
28146
- binaryMediaTypes: stringList(properties["BinaryMediaTypes"]),
28147
- minimumCompressionSize: properties["MinimumCompressionSize"],
28148
- apiKeySource: properties["ApiKeySourceType"],
28149
- endpointConfiguration: desiredEc ? {
28150
- types: stringList(desiredEc["Types"]),
28151
- vpcEndpointIds: stringList(desiredEc["VpcEndpointIds"]),
28152
- ipAddressType: desiredEc["IpAddressType"]
28153
- } : void 0,
28154
- policy: restApiPolicyString(properties["Policy"]),
28155
- tags: tags.length > 0 ? Object.fromEntries(tags.map((t) => [t.Key, t.Value])) : void 0,
28156
- disableExecuteApiEndpoint: properties["DisableExecuteApiEndpoint"],
28157
- securityPolicy: properties["SecurityPolicy"],
28158
- endpointAccessMode: properties["EndpointAccessMode"]
28159
- }));
28160
- } catch (error) {
28161
- createRestApiLatch.noteFailure(logicalId, error, attemptStartMs, orphanWindow);
28162
- throw error;
28262
+ } catch (deleteError) {
28263
+ if (!(deleteError instanceof NotFoundException$1)) throw deleteError;
28264
+ }
28265
+ await putMethod();
28163
28266
  }
28164
- if (!response.id) throw new ProvisioningError(`API Gateway answered no id for RestApi ${logicalId}`, resourceType, logicalId);
28165
- restApiId = response.id;
28166
- restApisCreatedByThisProcess.add(restApiId);
28167
- const replayWindow = replayedSendWindow(response, attemptStartMs);
28168
- if (replayWindow !== void 0) await reportOrphans(replayWindow);
28169
- let rootResourceId = response.rootResourceId;
28170
- if (body) {
28171
- let live = restApiAsCfn(response, properties["Policy"]);
28172
- if (cloneFrom) {
28173
- const put = await this.apiGatewayClient.send(new PutRestApiCommand({
28267
+ reportCreatedResource(logicalId, resourceType, physicalId);
28268
+ try {
28269
+ const integration = properties["Integration"];
28270
+ if (integration) await this.apiGatewayClient.send(new PutIntegrationCommand(putIntegrationInput({
28271
+ restApiId,
28272
+ resourceId,
28273
+ httpMethod
28274
+ }, integration)));
28275
+ const methodResponses = properties["MethodResponses"];
28276
+ if (methodResponses) for (const resp of methodResponses) await this.apiGatewayClient.send(new PutMethodResponseCommand(putMethodResponseInput({
28277
+ restApiId,
28278
+ resourceId,
28279
+ httpMethod
28280
+ }, resp)));
28281
+ if (integration) {
28282
+ const integrationResponses = integration["IntegrationResponses"];
28283
+ if (integrationResponses) for (const ir of integrationResponses) await this.apiGatewayClient.send(new PutIntegrationResponseCommand(putIntegrationResponseInput({
28174
28284
  restApiId,
28175
- mode: properties["Mode"] ?? "overwrite",
28176
- failOnWarnings: properties["FailOnWarnings"] === true,
28177
- parameters: bodyParameters(properties["Parameters"]),
28178
- body
28285
+ resourceId,
28286
+ httpMethod
28287
+ }, ir)));
28288
+ }
28289
+ } catch (innerError) {
28290
+ try {
28291
+ await this.apiGatewayClient.send(new DeleteMethodCommand({
28292
+ restApiId,
28293
+ resourceId,
28294
+ httpMethod
28179
28295
  }));
28180
- live = restApiAsCfn(put, properties["Policy"]);
28181
- rootResourceId = put.rootResourceId ?? rootResourceId;
28296
+ retractCreatedResource(logicalId, resourceType, physicalId);
28297
+ log.debug(`Cleaned up partially-created API Gateway Method ${logicalId} (${methodPath}) after wiring failure`);
28298
+ } catch (cleanupError) {
28299
+ methodLeftBehind = true;
28300
+ getPriorAttempts(logicalId)?.notePossiblyLanded();
28301
+ const cleanupFailure = describeAwsFailure(cleanupError);
28302
+ const cleanupHead = `Failed to clean up partially-created API Gateway Method ${logicalId} (${methodPath}): `;
28303
+ if (cleanupFailure.redacted) log.debug(`${cleanupHead}${cleanupFailure.detail}`);
28304
+ log.warn(`${cleanupHead}${cleanupFailure.redacted ? `${cleanupFailure.summary} ` : `${cleanupFailure.detail}. `}Manual deletion may be required before the next deploy: ${pasteableAwsCommand(log.mask)`aws apigateway delete-method --rest-api-id ${restApiId} --resource-id ${resourceId} --http-method ${httpMethod}`.render()}`);
28182
28305
  }
28183
- const patchOperations = restApiPatchOperations(properties, live, {}, cloneFrom ? properties["Mode"] ?? "overwrite" : "overwrite");
28184
- if (patchOperations.length > 0) await this.apiGatewayClient.send(new UpdateRestApiCommand({
28185
- restApiId,
28186
- patchOperations
28187
- }));
28188
- if (tags.length > 0 && !cloneFrom) await this.apiGatewayClient.send(new TagResourceCommand$3({
28189
- resourceArn: await restApiArn.call(this, restApiId),
28190
- tags: Object.fromEntries(tags.map((t) => [t.Key, t.Value]))
28191
- }));
28306
+ throw markAuxiliaryFailure(innerError, logicalId);
28192
28307
  }
28193
- if (rootResourceId === void 0) rootResourceId = (await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId }))).rootResourceId;
28194
- log.debug(safeMsg`Successfully created API Gateway RestApi ${logicalId}: ${restApiId}`);
28308
+ log.debug(`Successfully created API Gateway Method ${logicalId}: ${maskedIds.join("|")}`);
28195
28309
  return {
28196
- physicalId: restApiId,
28197
- attributes: {
28198
- RestApiId: restApiId,
28199
- ...rootResourceId !== void 0 ? { RootResourceId: rootResourceId } : {}
28200
- }
28310
+ physicalId,
28311
+ attributes: {}
28201
28312
  };
28202
28313
  } catch (error) {
28203
- if (error instanceof CdkdError && restApiId === void 0) throw error;
28204
28314
  const cause = error instanceof Error ? error : void 0;
28205
- const survivor = restApiId === void 0 ? "" : await retireFailedRestApi.call(this, restApiId, log);
28206
- throw this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to create API Gateway RestApi ${logicalId}: ${text}${survivor}`, resourceType, logicalId, void 0, cause));
28315
+ const thrown = this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to create API Gateway Method ${logicalId}: ${text}`, resourceType, logicalId, void 0, cause));
28316
+ if (methodLeftBehind) markCreatedBeforeFailure(thrown, logicalId, resourceType, physicalId);
28317
+ throw thrown;
28207
28318
  }
28208
28319
  }
28209
- async function retireFailedRestApi(restApiId, log) {
28320
+ async function priorAttemptLeftMethod(logicalId, physicalId, log) {
28321
+ const lookup = getPriorAttempts(logicalId);
28322
+ if (lookup === void 0) return false;
28323
+ if (lookup.possiblyLanded()) return true;
28324
+ if (lookup.provenOrphanIds === void 0) return false;
28210
28325
  try {
28211
- await this.apiGatewayClient.send(new DeleteRestApiCommand({ restApiId }));
28212
- log.debug(safeMsg`Deleted REST API ${restApiId} left by the failed create`);
28213
- return "";
28214
- } catch (cleanupError) {
28215
- if (cleanupError instanceof NotFoundException$1) return "";
28216
- const aws = pasteableAwsCommand(log.mask);
28217
- const regionArg = await this.orphanCommandRegionArg(aws);
28218
- return ` The REST API ${restApiId} it created could not be deleted (${describeAwsFailure(cleanupError).summary}); delete it with: ` + aws`aws apigateway delete-rest-api --rest-api-id ${restApiId}${regionArg}`.render();
28326
+ return (await lookup.provenOrphanIds()).includes(physicalId);
28327
+ } catch (error) {
28328
+ log.debug(`API Gateway Method ${logicalId}: rollback journal read failed: ${describeAwsFailure(error).detail}`);
28329
+ return false;
28219
28330
  }
28220
28331
  }
28221
- async function updateRestApi(logicalId, physicalId, resourceType, properties, previousProperties, log, changedProperties, noEchoOnlyChanged, keptNoEchoOnly) {
28222
- refuseMalformedDesiredTags(properties["Tags"], resourceType, logicalId, physicalId);
28223
- try {
28224
- let current = previousProperties;
28225
- let bodyPutMode;
28226
- let rootResourceId;
28227
- let bodyChanged = changedProperties !== void 0 ? declaresBody(properties) && BODY_KEYS.some((key) => changedProperties.has(key)) : restApiBodyChanged(properties, previousProperties, log.mask);
28228
- if (bodyChanged && changedProperties !== void 0 && noEchoOnlyChanged !== void 0) {
28229
- const named = BODY_KEYS.filter((key) => changedProperties.has(key));
28230
- if (named.length > 0 && named.every((key) => noEchoOnlyChanged.has(key))) {
28231
- bodyChanged = false;
28232
- for (const key of named) keptNoEchoOnly?.(key);
28233
- log.warn(safeMsg`${logicalId} (${resourceType}): its Body embeds a NoEcho parameter value that cdkd could not compare with the value it last sent, so the OpenAPI definition is not put again, and a change to that value alone is NOT applied by this deploy. cdkd compares it once a deploy can call kms:GenerateMac on the key 'cdkd bootstrap' creates, the Body reads nothing but NoEcho parameters and literals, and a put has recorded the value's MAC. To apply a change now, change a part of the Body that is not masked (its description or a version field, for example) in the same deploy.`);
28234
- }
28235
- }
28236
- if (bodyChanged) {
28237
- const body = await resolveRestApiBody.call(this, logicalId, resourceType, properties, log.value, physicalId);
28238
- const put = await this.apiGatewayClient.send(new PutRestApiCommand({
28239
- restApiId: physicalId,
28240
- mode: properties["Mode"] ?? "overwrite",
28241
- failOnWarnings: properties["FailOnWarnings"] === true,
28242
- parameters: bodyParameters(properties["Parameters"]),
28243
- body
28244
- }));
28245
- log.debug(safeMsg`Put the OpenAPI definition of API Gateway RestApi ${logicalId}: ${physicalId}`);
28246
- current = restApiAsCfn(put, properties["Policy"]);
28247
- bodyPutMode = properties["Mode"] ?? "overwrite";
28248
- rootResourceId = put.rootResourceId;
28332
+ async function updateMethod(logicalId, physicalId, resourceType, properties, previousProperties, log, previousIsLiveReadback = false) {
28333
+ const parts = physicalId.split("|");
28334
+ const maskedId = parts.map((p) => log.value(p)).join("|");
28335
+ log.debug(`Updating API Gateway Method ${logicalId}: ${maskedId}`);
28336
+ if (parts.length !== 3) throw new ProvisioningError(compositeIdFormatMessage(APIGW_METHOD_ID_FORMAT, logicalId, maskedId), resourceType, logicalId, physicalId);
28337
+ const [restApiId, resourceId, httpMethod] = parts;
28338
+ const patchOperations = [];
28339
+ for (const { key, path } of [
28340
+ {
28341
+ key: "AuthorizationType",
28342
+ path: "/authorizationType"
28343
+ },
28344
+ {
28345
+ key: "AuthorizerId",
28346
+ path: "/authorizerId"
28347
+ },
28348
+ {
28349
+ key: "ApiKeyRequired",
28350
+ path: "/apiKeyRequired"
28351
+ },
28352
+ {
28353
+ key: "OperationName",
28354
+ path: "/operationName"
28355
+ },
28356
+ {
28357
+ key: "RequestValidatorId",
28358
+ path: "/requestValidatorId"
28249
28359
  }
28250
- const patchOperations = restApiPatchOperations(properties, current, previousProperties, bodyPutMode);
28251
- if (patchOperations.length > 0) {
28252
- await this.apiGatewayClient.send(new UpdateRestApiCommand({
28253
- restApiId: physicalId,
28254
- patchOperations
28255
- }));
28256
- log.debug(safeMsg`Updated API Gateway RestApi ${logicalId} (${patchOperations.length} patch ops)`);
28360
+ ]) {
28361
+ const newVal = properties[key];
28362
+ if (newVal !== previousProperties[key]) patchOperations.push({
28363
+ op: "replace",
28364
+ path,
28365
+ value: newVal !== void 0 ? stringifyValue(newVal) : ""
28366
+ });
28367
+ }
28368
+ appendMapPatchOps(patchOperations, "/requestParameters", properties["RequestParameters"] ?? {}, previousProperties["RequestParameters"] ?? {});
28369
+ appendMapPatchOps(patchOperations, "/requestModels", properties["RequestModels"] ?? {}, previousProperties["RequestModels"] ?? {});
28370
+ const scopeOps = listPatchOps("/authorizationScopes", properties["AuthorizationScopes"], previousProperties["AuthorizationScopes"], {
28371
+ asSet: true,
28372
+ removeEveryPrevOccurrence: previousIsLiveReadback
28373
+ });
28374
+ patchOperations.push(...scopeOps.adds, ...scopeOps.removes);
28375
+ const childCalls = methodChildCalls({
28376
+ restApiId,
28377
+ resourceId,
28378
+ httpMethod
28379
+ }, properties, previousProperties);
28380
+ if (patchOperations.length === 0 && childCalls.length === 0) {
28381
+ log.debug(`No changes detected for API Gateway Method ${logicalId}`);
28382
+ return {
28383
+ physicalId,
28384
+ wasReplaced: false
28385
+ };
28386
+ }
28387
+ try {
28388
+ if (patchOperations.length > 0) await this.apiGatewayClient.send(new UpdateMethodCommand({
28389
+ restApiId,
28390
+ resourceId,
28391
+ httpMethod,
28392
+ patchOperations
28393
+ }));
28394
+ for (const call of childCalls) try {
28395
+ await this.apiGatewayClient.send(call.command);
28396
+ } catch (error) {
28397
+ if (!(call.kind === "delete" && error instanceof NotFoundException$1)) throw error;
28257
28398
  }
28258
- const arn = await restApiArn.call(this, physicalId);
28259
- await this.applyTagDiff(arn, resourceType, logicalId, previousProperties["Tags"], properties["Tags"], log, arn);
28399
+ log.debug(`Successfully updated API Gateway Method ${logicalId} (${patchOperations.length} patch ops, ${childCalls.length} sub-resource calls)`);
28260
28400
  return {
28261
28401
  physicalId,
28262
- wasReplaced: false,
28263
- ...rootResourceId !== void 0 ? { attributes: {
28264
- RestApiId: physicalId,
28265
- RootResourceId: rootResourceId
28266
- } } : {}
28402
+ wasReplaced: false
28267
28403
  };
28268
28404
  } catch (error) {
28269
- if (error instanceof CdkdError) throw error;
28270
28405
  const cause = error instanceof Error ? error : void 0;
28271
- throw this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to update API Gateway RestApi ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
28406
+ throw this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to update API Gateway Method ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
28272
28407
  }
28273
28408
  }
28274
- async function deleteRestApi(logicalId, physicalId, resourceType, context) {
28275
- this.logger.debug(safeMsg`Deleting API Gateway RestApi ${logicalId}: ${physicalId}`);
28409
+ async function deleteMethod(logicalId, physicalId, resourceType, context) {
28410
+ this.logger.debug(`Deleting API Gateway Method ${logicalId}: ${physicalId}`);
28411
+ const parts = physicalId.split("|");
28412
+ if (parts.length !== 3) throw new ProvisioningError(compositeIdFormatMessage(APIGW_METHOD_ID_FORMAT, logicalId, physicalId), resourceType, logicalId, physicalId);
28413
+ const [restApiId, resourceId, httpMethod] = parts;
28276
28414
  try {
28277
- await this.apiGatewayClient.send(new DeleteRestApiCommand({ restApiId: physicalId }));
28278
- this.logger.debug(safeMsg`Successfully deleted API Gateway RestApi ${logicalId}`);
28415
+ await this.apiGatewayClient.send(new DeleteMethodCommand({
28416
+ restApiId,
28417
+ resourceId,
28418
+ httpMethod
28419
+ }));
28420
+ this.logger.debug(`Successfully deleted API Gateway Method ${logicalId}`);
28279
28421
  } catch (error) {
28280
28422
  if (error instanceof NotFoundException$1) {
28281
28423
  const clientRegion = await this.apiGatewayClient.config.region();
28282
28424
  assertRegionMatch(clientRegion, context?.expectedRegion, resourceType, logicalId, physicalId);
28283
- this.logger.debug(safeMsg`API Gateway RestApi ${physicalId} does not exist, skipping deletion`);
28425
+ this.logger.debug(`API Gateway Method ${physicalId} does not exist, skipping deletion`);
28284
28426
  return;
28285
28427
  }
28286
28428
  const cause = error instanceof Error ? error : void 0;
28287
- const thrown = this.wrapMaskedError(context?.maskSecrets ?? ((text) => text), error, (text) => new ProvisioningError(`Failed to delete API Gateway RestApi ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
28429
+ const thrown = this.wrapMaskedError(context?.maskSecrets ?? ((text) => text), error, (text) => new ProvisioningError(`Failed to delete API Gateway Method ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
28288
28430
  throw error instanceof Error && error.name.includes("NotFound") ? markNotGone(thrown) : thrown;
28289
28431
  }
28290
28432
  }
28291
- async function getRestApiAttribute(physicalId, attributeName) {
28292
- if (attributeName === "RestApiId") return physicalId;
28293
- if (attributeName === "RootResourceId") return (await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: physicalId }))).rootResourceId;
28294
- }
28295
- async function readCurrentStateRestApi(physicalId, properties) {
28296
- try {
28297
- const resp = await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: physicalId }));
28298
- const result = restApiAsCfn(resp, properties?.["Policy"]);
28299
- const fromDefinition = definitionBinaryMediaTypes(properties?.["Body"]);
28300
- const declared = new Set(stringList(properties?.["BinaryMediaTypes"]) ?? []);
28301
- const unreadable = properties?.["BodyS3Location"] != null || typeof properties?.["Body"] === "string" && !isJsonText(properties["Body"]);
28302
- result["BinaryMediaTypes"] = result["BinaryMediaTypes"].filter((t) => unreadable ? declared.has(t) : !fromDefinition.has(t) || declared.has(t));
28303
- result["Tags"] = Object.entries(resp.tags ?? {}).filter(([key]) => !key.startsWith("aws:")).map(([Key, Value]) => ({
28304
- Key,
28305
- Value
28306
- }));
28307
- return result;
28308
- } catch (err) {
28309
- if (err instanceof NotFoundException$1) return RESOURCE_NOT_FOUND;
28310
- throw err;
28311
- }
28312
- }
28313
- const REST_API_WRITE_ONLY_PATHS = [
28314
- "Body",
28315
- "BodyS3Location",
28316
- "CloneFrom",
28317
- "FailOnWarnings",
28318
- "Mode",
28319
- "Parameters"
28320
- ];
28321
- async function importRestApi(input) {
28322
- if (!input.knownPhysicalId) return null;
28323
- try {
28324
- const resp = await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: input.knownPhysicalId }));
28325
- return {
28326
- physicalId: input.knownPhysicalId,
28327
- attributes: {
28328
- RestApiId: input.knownPhysicalId,
28329
- ...resp.rootResourceId !== void 0 ? { RootResourceId: resp.rootResourceId } : {}
28330
- }
28331
- };
28332
- } catch (err) {
28333
- if (err instanceof NotFoundException$1) return null;
28334
- throw err;
28433
+ function getMethodAttribute(physicalId, attributeName) {
28434
+ const parts = physicalId.split("|");
28435
+ if (parts.length === 3) {
28436
+ if (attributeName === "RestApiId") return Promise.resolve(parts[0]);
28437
+ if (attributeName === "ResourceId") return Promise.resolve(parts[1]);
28438
+ if (attributeName === "HttpMethod") return Promise.resolve(parts[2]);
28335
28439
  }
28440
+ return Promise.resolve(void 0);
28336
28441
  }
28337
28442
 
28338
28443
  // src/provisioning/providers/apigateway/read-state.ts
@@ -28367,7 +28472,7 @@ function getDriftUnorderedPaths$6(resourceType) {
28367
28472
  if (resourceType === "AWS::ApiGateway::RestApi") return ["BinaryMediaTypes"];
28368
28473
  return [];
28369
28474
  }
28370
- async function readCurrentState$28(physicalId, _logicalId, resourceType, properties) {
28475
+ async function readCurrentState$29(physicalId, _logicalId, resourceType, properties) {
28371
28476
  switch (resourceType) {
28372
28477
  case "AWS::ApiGateway::Account": return this.readCurrentStateAccount();
28373
28478
  case "AWS::ApiGateway::Method": return this.readCurrentStateMethod(physicalId);
@@ -28539,6 +28644,7 @@ async function importImpl$30(input) {
28539
28644
  var ApiGatewayProvider = class {
28540
28645
  apiGatewayClient;
28541
28646
  logger = getLogger().child("ApiGatewayProvider");
28647
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
28542
28648
  handledProperties = /* @__PURE__ */ new Map([
28543
28649
  ["AWS::ApiGateway::Account", /* @__PURE__ */ new Set(["CloudWatchRoleArn"])],
28544
28650
  ["AWS::ApiGateway::Authorizer", /* @__PURE__ */ new Set([
@@ -28672,8 +28778,8 @@ var ApiGatewayProvider = class {
28672
28778
  createResource(logicalId, resourceType, properties, log) {
28673
28779
  return createResource.call(this, logicalId, resourceType, properties, log);
28674
28780
  }
28675
- updateResource(logicalId, physicalId, resourceType, properties, previousProperties, log) {
28676
- return updateResource.call(this, logicalId, physicalId, resourceType, properties, previousProperties, log);
28781
+ updateResource(logicalId, physicalId, resourceType, properties, previousProperties, log, driftRevert = false) {
28782
+ return updateResource.call(this, logicalId, physicalId, resourceType, properties, previousProperties, log, driftRevert);
28677
28783
  }
28678
28784
  deleteResource(logicalId, physicalId, resourceType, properties, context) {
28679
28785
  return deleteResource.call(this, logicalId, physicalId, resourceType, properties, context);
@@ -28732,8 +28838,9 @@ var ApiGatewayProvider = class {
28732
28838
  getRestApiAttribute(physicalId, attributeName) {
28733
28839
  return getRestApiAttribute.call(this, physicalId, attributeName);
28734
28840
  }
28735
- readCurrentStateRestApi(physicalId, properties) {
28736
- return readCurrentStateRestApi.call(this, physicalId, properties);
28841
+ async readCurrentStateRestApi(physicalId, properties, context, logicalId = physicalId) {
28842
+ const read = await readCurrentStateRestApi.call(this, physicalId, properties);
28843
+ return context?.afterOwnWrite === true ? settleRestApiPolicy.call(this, physicalId, logicalId, read, properties) : read;
28737
28844
  }
28738
28845
  importRestApi(input) {
28739
28846
  return importRestApi.call(this, input);
@@ -28756,8 +28863,9 @@ var ApiGatewayProvider = class {
28756
28863
  getDriftUnorderedPaths(resourceType) {
28757
28864
  return getDriftUnorderedPaths$6.call(this, resourceType);
28758
28865
  }
28759
- readCurrentState(physicalId, _logicalId, resourceType, properties) {
28760
- return readCurrentState$28.call(this, physicalId, _logicalId, resourceType, properties);
28866
+ readCurrentState(physicalId, _logicalId, resourceType, properties, context) {
28867
+ if (resourceType === "AWS::ApiGateway::RestApi") return this.readCurrentStateRestApi(physicalId, properties, context, _logicalId);
28868
+ return readCurrentState$29.call(this, physicalId, _logicalId, resourceType, properties);
28761
28869
  }
28762
28870
  readCurrentStateAuthorizer(physicalId, properties) {
28763
28871
  return readCurrentStateAuthorizer.call(this, physicalId, properties);
@@ -28918,7 +29026,7 @@ async function canonicalizeDriftPair$2(resourceType, baseline, aws, properties =
28918
29026
  aws
28919
29027
  };
28920
29028
  }
28921
- async function readCurrentState$27(physicalId, _logicalId, resourceType, properties) {
29029
+ async function readCurrentState$28(physicalId, _logicalId, resourceType, properties) {
28922
29030
  switch (resourceType) {
28923
29031
  case "AWS::ApiGatewayV2::Api": return this.readApi(physicalId);
28924
29032
  case "AWS::ApiGatewayV2::Stage": return this.readStage(physicalId, properties);
@@ -30333,7 +30441,7 @@ var ApiGatewayV2Provider = class {
30333
30441
  return canonicalizeDriftPair$2.call(this, resourceType, baseline, aws, properties);
30334
30442
  }
30335
30443
  readCurrentState(physicalId, _logicalId, resourceType, properties) {
30336
- return readCurrentState$27.call(this, physicalId, _logicalId, resourceType, properties);
30444
+ return readCurrentState$28.call(this, physicalId, _logicalId, resourceType, properties);
30337
30445
  }
30338
30446
  readApi(physicalId) {
30339
30447
  return readApi.call(this, physicalId);
@@ -31013,7 +31121,7 @@ async function waitForDistributionStable(distributionId, expectedEnabled) {
31013
31121
  }
31014
31122
 
31015
31123
  // src/provisioning/providers/cloudfront-distribution/read-state.ts
31016
- async function readCurrentState$26(physicalId, _logicalId, resourceType, _properties) {
31124
+ async function readCurrentState$27(physicalId, _logicalId, resourceType, _properties) {
31017
31125
  if (resourceType !== "AWS::CloudFront::Distribution") return void 0;
31018
31126
  let config;
31019
31127
  try {
@@ -31504,7 +31612,7 @@ var CloudFrontDistributionProvider = class {
31504
31612
  return deleteImpl$27.call(this, logicalId, physicalId, resourceType, _properties, context);
31505
31613
  }
31506
31614
  readCurrentState(physicalId, _logicalId, resourceType, _properties) {
31507
- return readCurrentState$26.call(this, physicalId, _logicalId, resourceType, _properties);
31615
+ return readCurrentState$27.call(this, physicalId, _logicalId, resourceType, _properties);
31508
31616
  }
31509
31617
  getDriftUnknownPaths(resourceType) {
31510
31618
  return getDriftUnknownPaths$7.call(this, resourceType);
@@ -31607,7 +31715,7 @@ function isUserTagKey(key) {
31607
31715
  }
31608
31716
 
31609
31717
  // src/provisioning/providers/agentcore-runtime/read-state.ts
31610
- async function readCurrentState$25(physicalId, _logicalId, _resourceType) {
31718
+ async function readCurrentState$26(physicalId, _logicalId, _resourceType) {
31611
31719
  let resp;
31612
31720
  try {
31613
31721
  resp = await this.client.send(new GetAgentRuntimeCommand({ agentRuntimeId: physicalId }));
@@ -31634,6 +31742,8 @@ async function readCurrentState$25(physicalId, _logicalId, _resourceType) {
31634
31742
  result["FilesystemConfigurations"] = resp.filesystemConfigurations !== void 0 ? camelToPascalCaseKeys(resp.filesystemConfigurations, SDK_MAP_KEYS) : [];
31635
31743
  result["CapacityProviderConfiguration"] = resp.capacityProviderConfiguration !== void 0 ? camelToPascalCaseKeys(resp.capacityProviderConfiguration, SDK_MAP_KEYS) : {};
31636
31744
  result["PlatformVersion"] = resp.platformVersion ?? "";
31745
+ result["HooksConfiguration"] = resp.hooksConfiguration !== void 0 ? camelToPascalCaseKeys(resp.hooksConfiguration, SDK_MAP_KEYS) : {};
31746
+ result["ResourceConfigurations"] = resp.resourceConfigurations !== void 0 ? camelToPascalCaseKeys(resp.resourceConfigurations, SDK_MAP_KEYS) : [];
31637
31747
  if (resp.agentRuntimeArn) try {
31638
31748
  const tagsResp = await this.client.send(new ListTagsForResourceCommand$6({ resourceArn: resp.agentRuntimeArn }));
31639
31749
  result["Tags"] = Object.fromEntries(Object.entries(tagsResp.tags ?? {}).filter(([k]) => isUserTagKey(k)));
@@ -31768,6 +31878,10 @@ function writeSharedRuntimeMembers(input, properties) {
31768
31878
  if (isNonEmptyObject(capacityProvider)) input["capacityProviderConfiguration"] = pascalToCamelCaseKeys(capacityProvider, CFN_MAP_KEYS);
31769
31879
  const platformVersion = properties["PlatformVersion"];
31770
31880
  if (platformVersion !== void 0 && platformVersion !== null && platformVersion !== "") input["platformVersion"] = platformVersion;
31881
+ const hooks = properties["HooksConfiguration"];
31882
+ if (isNonEmptyObject(hooks)) input["hooksConfiguration"] = pascalToCamelCaseKeys(hooks, CFN_MAP_KEYS);
31883
+ const resources = properties["ResourceConfigurations"];
31884
+ if (Array.isArray(resources) && resources.length > 0) input["resourceConfigurations"] = pascalToCamelCaseKeys(resources, CFN_MAP_KEYS);
31771
31885
  }
31772
31886
  var AgentCoreRuntimeProvider = class {
31773
31887
  client;
@@ -31820,6 +31934,8 @@ var AgentCoreRuntimeProvider = class {
31820
31934
  "FilesystemConfigurations",
31821
31935
  "CapacityProviderConfiguration",
31822
31936
  "PlatformVersion",
31937
+ "HooksConfiguration",
31938
+ "ResourceConfigurations",
31823
31939
  "Tags"
31824
31940
  ])]]);
31825
31941
  constructor() {
@@ -32015,7 +32131,7 @@ var AgentCoreRuntimeProvider = class {
32015
32131
  }
32016
32132
  }
32017
32133
  readCurrentState(physicalId, logicalId, resourceType) {
32018
- return readCurrentState$25.call(this, physicalId, logicalId, resourceType);
32134
+ return readCurrentState$26.call(this, physicalId, logicalId, resourceType);
32019
32135
  }
32020
32136
  import(input) {
32021
32137
  return importImpl$27.call(this, input);
@@ -32510,7 +32626,7 @@ async function applyTagDiff$12(stateMachineArn, resourceType, logicalId, oldTags
32510
32626
  }
32511
32627
 
32512
32628
  // src/provisioning/providers/stepfunctions/read-state.ts
32513
- async function readCurrentState$24(physicalId, _logicalId, _resourceType) {
32629
+ async function readCurrentState$25(physicalId, _logicalId, _resourceType) {
32514
32630
  let resp;
32515
32631
  try {
32516
32632
  resp = await this.getClient().send(new DescribeStateMachineCommand({ stateMachineArn: physicalId }));
@@ -32748,7 +32864,7 @@ var StepFunctionsProvider = class {
32748
32864
  return [...new Set(aliases)];
32749
32865
  }
32750
32866
  readCurrentState(physicalId, _logicalId, _resourceType) {
32751
- return readCurrentState$24.call(this, physicalId, _logicalId, _resourceType);
32867
+ return readCurrentState$25.call(this, physicalId, _logicalId, _resourceType);
32752
32868
  }
32753
32869
  generatedCreateName(_resourceType, logicalId, properties) {
32754
32870
  if (properties["StateMachineName"]) return void 0;
@@ -33404,13 +33520,13 @@ function createServiceOutcomeUnknown(error) {
33404
33520
  }
33405
33521
  async function settleAmbiguousCreateService(attempt, log) {
33406
33522
  try {
33407
- return await settle.call(this, attempt, log);
33523
+ return await settle$1.call(this, attempt, log);
33408
33524
  } catch (error) {
33409
33525
  log.debug(`Looking for ECS service ${attempt.logicalId} after its ambiguous CreateService failure failed: ${describeAwsFailure(error).detail}`);
33410
33526
  return;
33411
33527
  }
33412
33528
  }
33413
- async function settle(attempt, log) {
33529
+ async function settle$1(attempt, log) {
33414
33530
  const { logicalId, cluster, serviceName, createError } = attempt;
33415
33531
  if (!createServiceOutcomeUnknown(createError)) return void 0;
33416
33532
  if (attempt.heldBefore === "held") {
@@ -34456,7 +34572,7 @@ function getDriftUnknownPaths$6(resourceType) {
34456
34572
  ];
34457
34573
  return [];
34458
34574
  }
34459
- async function readCurrentState$23(physicalId, _logicalId, resourceType) {
34575
+ async function readCurrentState$24(physicalId, _logicalId, resourceType) {
34460
34576
  switch (resourceType) {
34461
34577
  case "AWS::ECS::Cluster": return this.readCurrentStateCluster(physicalId);
34462
34578
  case "AWS::ECS::Service": return this.readCurrentStateService(physicalId);
@@ -34983,7 +35099,7 @@ var ECSProvider = class {
34983
35099
  return getDriftUnknownPaths$6.call(this, resourceType);
34984
35100
  }
34985
35101
  readCurrentState(physicalId, _logicalId, resourceType) {
34986
- return readCurrentState$23.call(this, physicalId, _logicalId, resourceType);
35102
+ return readCurrentState$24.call(this, physicalId, _logicalId, resourceType);
34987
35103
  }
34988
35104
  readCurrentStateCluster(physicalId) {
34989
35105
  return readCurrentStateCluster.call(this, physicalId);
@@ -36130,7 +36246,7 @@ function convertCertificates(certificates) {
36130
36246
  }
36131
36247
 
36132
36248
  // src/provisioning/providers/elbv2/read-state.ts
36133
- async function readCurrentState$22(physicalId, _logicalId, resourceType) {
36249
+ async function readCurrentState$23(physicalId, _logicalId, resourceType) {
36134
36250
  switch (resourceType) {
36135
36251
  case "AWS::ElasticLoadBalancingV2::LoadBalancer": return this.readLoadBalancer(physicalId);
36136
36252
  case "AWS::ElasticLoadBalancingV2::TargetGroup": return this.readTargetGroup(physicalId);
@@ -36644,7 +36760,7 @@ var ELBv2Provider = class {
36644
36760
  return convertCertificates.call(this, certificates);
36645
36761
  }
36646
36762
  readCurrentState(physicalId, _logicalId, resourceType) {
36647
- return readCurrentState$22.call(this, physicalId, _logicalId, resourceType);
36763
+ return readCurrentState$23.call(this, physicalId, _logicalId, resourceType);
36648
36764
  }
36649
36765
  readLoadBalancer(physicalId) {
36650
36766
  return readLoadBalancer.call(this, physicalId);
@@ -37039,7 +37155,7 @@ async function importImpl$23(input) {
37039
37155
  if (explicit) return this.buildImportResult(explicit);
37040
37156
  return null;
37041
37157
  }
37042
- async function readCurrentState$21(physicalId) {
37158
+ async function readCurrentState$22(physicalId) {
37043
37159
  const client = this.getClient();
37044
37160
  let proxy;
37045
37161
  try {
@@ -37164,7 +37280,7 @@ var RDSDBProxyProvider = class {
37164
37280
  return importImpl$23.call(this, input);
37165
37281
  }
37166
37282
  readCurrentState(physicalId) {
37167
- return readCurrentState$21.call(this, physicalId);
37283
+ return readCurrentState$22.call(this, physicalId);
37168
37284
  }
37169
37285
  applyTagDiff(physicalId, oldTags, newTags, resourceType, logicalId, maskSecrets) {
37170
37286
  return applyTagDiff$9.call(this, physicalId, oldTags, newTags, resourceType, logicalId, maskSecrets);
@@ -37885,7 +38001,7 @@ async function importImpl$22(input) {
37885
38001
  };
37886
38002
  return null;
37887
38003
  }
37888
- async function readCurrentState$20(physicalId, _logicalId, _resourceType, properties) {
38004
+ async function readCurrentState$21(physicalId, _logicalId, _resourceType, properties) {
37889
38005
  const dbProxyName = readProxyName(properties["DBProxyName"]);
37890
38006
  const targetGroupName = requireConfigString(properties["TargetGroupName"], "default", "AWS::RDS::DBProxyTargetGroup TargetGroupName", { onUnusable: (message) => this.logger.warn(message) });
37891
38007
  if (!dbProxyName) return;
@@ -37976,7 +38092,7 @@ var RDSDBProxyTargetGroupProvider = class {
37976
38092
  return importImpl$22.call(this, input);
37977
38093
  }
37978
38094
  readCurrentState(physicalId, _logicalId, _resourceType, properties) {
37979
- return readCurrentState$20.call(this, physicalId, _logicalId, _resourceType, properties);
38095
+ return readCurrentState$21.call(this, physicalId, _logicalId, _resourceType, properties);
37980
38096
  }
37981
38097
  async retireRegistrationAfterFailedCreate(original, dbProxyName, targetGroupName, dbClusterIdentifiers, dbInstanceIdentifiers, maskSecrets, leftBehind) {
37982
38098
  const clusters = dbClusterIdentifiers?.length ? dbClusterIdentifiers : void 0;
@@ -39402,7 +39518,7 @@ async function unsettledInTransition$3(physicalId, _logicalId, resourceType, nam
39402
39518
  return names;
39403
39519
  }
39404
39520
  }
39405
- async function readCurrentState$19(physicalId, _logicalId, resourceType) {
39521
+ async function readCurrentState$20(physicalId, _logicalId, resourceType) {
39406
39522
  switch (resourceType) {
39407
39523
  case "AWS::DocDB::DBInstance": return this.readCurrentStateDBInstance(physicalId);
39408
39524
  case "AWS::DocDB::DBCluster": return this.readCurrentStateDBCluster(physicalId);
@@ -39737,7 +39853,7 @@ var DocDBProvider = class {
39737
39853
  return importImpl$21.call(this, input);
39738
39854
  }
39739
39855
  readCurrentState(physicalId, _logicalId, resourceType) {
39740
- return readCurrentState$19.call(this, physicalId, _logicalId, resourceType);
39856
+ return readCurrentState$20.call(this, physicalId, _logicalId, resourceType);
39741
39857
  }
39742
39858
  readCurrentStateDBInstance(physicalId) {
39743
39859
  return readCurrentStateDBInstance.call(this, physicalId);
@@ -40777,7 +40893,7 @@ async function updateRecordSet(logicalId, physicalId, resourceType, properties,
40777
40893
  }));
40778
40894
  this.logger.debug(`Successfully updated record set ${logicalId}`);
40779
40895
  return {
40780
- physicalId: compositeId,
40896
+ physicalId: context?.desiredFromAwsReadback === true ? physicalId : compositeId,
40781
40897
  wasReplaced: identityChanged,
40782
40898
  attributes: {}
40783
40899
  };
@@ -41545,7 +41661,7 @@ async function resolveRecordSetIdentity(physicalId, properties, options) {
41545
41661
  }
41546
41662
 
41547
41663
  // src/provisioning/providers/route53/read-state.ts
41548
- async function readCurrentState$18(physicalId, _logicalId, resourceType, properties) {
41664
+ async function readCurrentState$19(physicalId, _logicalId, resourceType, properties) {
41549
41665
  switch (resourceType) {
41550
41666
  case "AWS::Route53::HostedZone": return this.readHostedZone(physicalId, properties);
41551
41667
  case "AWS::Route53::RecordSet": return this.readRecordSet(physicalId, properties);
@@ -41957,7 +42073,7 @@ var Route53Provider = class {
41957
42073
  return resolveRecordSetIdentity.call(this, physicalId, properties, options);
41958
42074
  }
41959
42075
  readCurrentState(physicalId, _logicalId, resourceType, properties) {
41960
- return readCurrentState$18.call(this, physicalId, _logicalId, resourceType, properties);
42076
+ return readCurrentState$19.call(this, physicalId, _logicalId, resourceType, properties);
41961
42077
  }
41962
42078
  readUnsettled(physicalId, logicalId, resourceType, names, recordedProperties, desiredProperties, attemptedItems) {
41963
42079
  return readUnsettled$3.call(this, physicalId, logicalId, resourceType, names, recordedProperties, desiredProperties, attemptedItems);
@@ -42358,7 +42474,7 @@ async function deleteImpl$20(logicalId, physicalId, resourceType, _properties, c
42358
42474
  }
42359
42475
 
42360
42476
  // src/provisioning/providers/wafv2/read-state.ts
42361
- async function readCurrentState$17(physicalId, _logicalId, _resourceType, properties) {
42477
+ async function readCurrentState$18(physicalId, _logicalId, _resourceType, properties) {
42362
42478
  const { id, name, scope } = parseWebACLArn(physicalId);
42363
42479
  if (!id || !name) return void 0;
42364
42480
  let webACL;
@@ -42485,7 +42601,7 @@ var WAFv2WebACLProvider = class {
42485
42601
  return applyTagDiff$8.call(this, arn, resourceType, logicalId, oldTagsRaw, newTagsRaw);
42486
42602
  }
42487
42603
  readCurrentState(physicalId, logicalId, resourceType, properties) {
42488
- return readCurrentState$17.call(this, physicalId, logicalId, resourceType, properties);
42604
+ return readCurrentState$18.call(this, physicalId, logicalId, resourceType, properties);
42489
42605
  }
42490
42606
  import(input) {
42491
42607
  return importImpl$19.call(this, input);
@@ -42750,7 +42866,7 @@ function canonicalizeDesiredProperties$1(resourceType, properties) {
42750
42866
  if (resourceType !== "AWS::Cognito::UserPool") return properties;
42751
42867
  return narrowMfaConfiguration(properties);
42752
42868
  }
42753
- async function readCurrentState$16(physicalId, _logicalId, resourceType) {
42869
+ async function readCurrentState$17(physicalId, _logicalId, resourceType) {
42754
42870
  if (resourceType !== "AWS::Cognito::UserPool") return void 0;
42755
42871
  let resp;
42756
42872
  try {
@@ -42792,6 +42908,7 @@ async function readCurrentState$16(physicalId, _logicalId, resourceType) {
42792
42908
  result["UserPoolTier"] = pool.UserPoolTier ?? "ESSENTIALS";
42793
42909
  if (pool.KeyConfiguration) result["KeyConfiguration"] = pool.KeyConfiguration;
42794
42910
  if (pool.IssuerConfiguration) result["IssuerConfiguration"] = pool.IssuerConfiguration;
42911
+ if (pool.DcrConfiguration) result["DcrConfiguration"] = pool.DcrConfiguration;
42795
42912
  try {
42796
42913
  const mfa = await this.getClient().send(new GetUserPoolMfaConfigCommand({ UserPoolId: physicalId }));
42797
42914
  const enabledMfas = [];
@@ -43075,6 +43192,7 @@ async function create$19(logicalId, resourceType, properties, context) {
43075
43192
  if (properties["UserPoolTier"]) createParams.UserPoolTier = properties["UserPoolTier"];
43076
43193
  if (properties["KeyConfiguration"]) createParams.KeyConfiguration = properties["KeyConfiguration"];
43077
43194
  if (properties["IssuerConfiguration"]) createParams.IssuerConfiguration = properties["IssuerConfiguration"];
43195
+ if (properties["DcrConfiguration"]) createParams.DcrConfiguration = properties["DcrConfiguration"];
43078
43196
  const orphanWindow = createUserPoolLatch.take(logicalId);
43079
43197
  if (orphanWindow !== void 0) await this.reportPossibleOrphanPools(logicalId, poolName, orphanWindow, createMaskedLogSinks(this.logger, context?.maskSecrets));
43080
43198
  let created;
@@ -43195,6 +43313,9 @@ function warnOnUnremovablePoliciesSubKeys(physicalId, properties, previousProper
43195
43313
  this.logger.warn(`UserPool ${physicalId}: the desired configuration no longer declares Policies.${subKey}, and no UpdateUserPool input can express that removal — omitting the sub-key PRESERVES the live value, so the pool keeps its current ${label}. CloudFormation is the same no-op on the identical template edit, so cdkd deliberately sends no reset. To change the live value, declare Policies.${subKey} explicitly with the intended configuration (${reset}).`);
43196
43314
  }
43197
43315
  }
43316
+ function sendsMessageMember(value) {
43317
+ return value !== void 0 && value !== "";
43318
+ }
43198
43319
  function warnOnKeptRemovedMembers(logicalId, physicalId, properties, previousProperties) {
43199
43320
  for (const [member, unset] of Object.entries(KEPT_ON_REMOVAL_MEMBERS)) {
43200
43321
  if (!declaresMember(previousProperties[member], unset)) continue;
@@ -43202,6 +43323,10 @@ function warnOnKeptRemovedMembers(logicalId, physicalId, properties, previousPro
43202
43323
  this.logger.warn(safeMsg`Cognito User Pool ${logicalId} (${physicalId}): the template no longer declares ` + safeMsg`${member}, and UpdateUserPool keeps a member it omits, so the pool keeps its ` + safeMsg`current ${member}. CloudFormation keeps it on the same edit too, so cdkd sends ` + safeMsg`no reset. To change it, declare ${member} with the value you want.`);
43203
43324
  }
43204
43325
  }
43326
+ function dcrConfigurationUpdate(properties, previousProperties) {
43327
+ if (properties["DcrConfiguration"]) return properties["DcrConfiguration"];
43328
+ if (previousProperties["DcrConfiguration"]) return { EnableStatus: "Disabled" };
43329
+ }
43205
43330
  async function update$19(logicalId, physicalId, resourceType, properties, previousProperties, context) {
43206
43331
  this.logger.debug(`Updating Cognito User Pool ${logicalId}: ${physicalId}`);
43207
43332
  const stateBorneDesired = context?.replayingState === true || context?.desiredFromAwsReadback === true;
@@ -43255,13 +43380,15 @@ async function update$19(logicalId, physicalId, resourceType, properties, previo
43255
43380
  if (properties["VerificationMessageTemplate"]) updateParams.VerificationMessageTemplate = properties["VerificationMessageTemplate"];
43256
43381
  if (properties["DeviceConfiguration"]) updateParams.DeviceConfiguration = properties["DeviceConfiguration"];
43257
43382
  if (properties["UserPoolAddOns"] && !isEmptyObjectPlaceholder(properties["UserPoolAddOns"])) updateParams.UserPoolAddOns = properties["UserPoolAddOns"];
43258
- if (properties["EmailVerificationMessage"] !== void 0) updateParams.EmailVerificationMessage = properties["EmailVerificationMessage"];
43259
- if (properties["EmailVerificationSubject"] !== void 0) updateParams.EmailVerificationSubject = properties["EmailVerificationSubject"];
43260
- if (properties["SmsAuthenticationMessage"] !== void 0) updateParams.SmsAuthenticationMessage = properties["SmsAuthenticationMessage"];
43261
- if (properties["SmsVerificationMessage"] !== void 0) updateParams.SmsVerificationMessage = properties["SmsVerificationMessage"];
43383
+ if (sendsMessageMember(properties["EmailVerificationMessage"])) updateParams.EmailVerificationMessage = properties["EmailVerificationMessage"];
43384
+ if (sendsMessageMember(properties["EmailVerificationSubject"])) updateParams.EmailVerificationSubject = properties["EmailVerificationSubject"];
43385
+ if (sendsMessageMember(properties["SmsAuthenticationMessage"])) updateParams.SmsAuthenticationMessage = properties["SmsAuthenticationMessage"];
43386
+ if (sendsMessageMember(properties["SmsVerificationMessage"])) updateParams.SmsVerificationMessage = properties["SmsVerificationMessage"];
43262
43387
  if (properties["UserPoolTier"]) updateParams.UserPoolTier = properties["UserPoolTier"];
43263
43388
  if (properties["KeyConfiguration"]) updateParams.KeyConfiguration = properties["KeyConfiguration"];
43264
43389
  if (properties["IssuerConfiguration"]) updateParams.IssuerConfiguration = properties["IssuerConfiguration"];
43390
+ const dcr = dcrConfigurationUpdate(properties, previousProperties);
43391
+ if (dcr) updateParams.DcrConfiguration = dcr;
43265
43392
  const mfaOptions = {
43266
43393
  ...liveMfa?.value !== void 0 ? { liveMfaConfiguration: liveMfa.value } : {},
43267
43394
  ...liveMfa?.failed === true ? { liveReadFailed: true } : {},
@@ -43674,6 +43801,7 @@ var CognitoUserPoolProvider = class {
43674
43801
  "UserPoolTier",
43675
43802
  "KeyConfiguration",
43676
43803
  "IssuerConfiguration",
43804
+ "DcrConfiguration",
43677
43805
  "EnabledMfas",
43678
43806
  "EmailAuthenticationMessage",
43679
43807
  "EmailAuthenticationSubject",
@@ -43778,7 +43906,7 @@ var CognitoUserPoolProvider = class {
43778
43906
  return warnGuardLeftOn.call(this, physicalId, pool, mask, error, echoError);
43779
43907
  }
43780
43908
  readCurrentState(physicalId, _logicalId, resourceType) {
43781
- return readCurrentState$16.call(this, physicalId, _logicalId, resourceType);
43909
+ return readCurrentState$17.call(this, physicalId, _logicalId, resourceType);
43782
43910
  }
43783
43911
  userPoolAttributes(userPoolId, arn) {
43784
43912
  return userPoolAttributes.call(this, userPoolId, arn);
@@ -44257,7 +44385,7 @@ async function applyTagDiff$7(arn, resourceType, logicalId, oldTagsRaw, newTagsR
44257
44385
  }
44258
44386
 
44259
44387
  // src/provisioning/providers/elasticache/read-state.ts
44260
- async function readCurrentState$15(physicalId, _logicalId, resourceType) {
44388
+ async function readCurrentState$16(physicalId, _logicalId, resourceType) {
44261
44389
  switch (resourceType) {
44262
44390
  case "AWS::ElastiCache::CacheCluster": return this.readCacheCluster(physicalId);
44263
44391
  case "AWS::ElastiCache::SubnetGroup": return this.readSubnetGroup(physicalId);
@@ -44513,7 +44641,7 @@ var ElastiCacheProvider = class {
44513
44641
  return resourceType === "AWS::ElastiCache::CacheCluster" ? ["SnapshotArns", "SnapshotName"] : [];
44514
44642
  }
44515
44643
  readCurrentState(physicalId, _logicalId, resourceType) {
44516
- return readCurrentState$15.call(this, physicalId, _logicalId, resourceType);
44644
+ return readCurrentState$16.call(this, physicalId, _logicalId, resourceType);
44517
44645
  }
44518
44646
  readCacheCluster(physicalId) {
44519
44647
  return readCacheCluster.call(this, physicalId);
@@ -45314,7 +45442,7 @@ async function readServiceIdForIdentity(serviceId) {
45314
45442
  if (typeof response.Service?.Id !== "string") throw new Error("GetService did not return the service asked for");
45315
45443
  return response.Service.Id;
45316
45444
  }
45317
- async function readCurrentState$14(physicalId, _logicalId, resourceType) {
45445
+ async function readCurrentState$15(physicalId, _logicalId, resourceType) {
45318
45446
  switch (resourceType) {
45319
45447
  case "AWS::ServiceDiscovery::PrivateDnsNamespace":
45320
45448
  case "AWS::ServiceDiscovery::PublicDnsNamespace": return this.readNamespace(physicalId, { includeProperties: true });
@@ -45608,7 +45736,7 @@ var ServiceDiscoveryProvider = class {
45608
45736
  return readServiceIdForIdentity.call(this, serviceId);
45609
45737
  }
45610
45738
  readCurrentState(physicalId, _logicalId, resourceType) {
45611
- return readCurrentState$14.call(this, physicalId, _logicalId, resourceType);
45739
+ return readCurrentState$15.call(this, physicalId, _logicalId, resourceType);
45612
45740
  }
45613
45741
  getDriftUnknownPaths(resourceType) {
45614
45742
  return getDriftUnknownPaths$3.call(this, resourceType);
@@ -46965,7 +47093,7 @@ function isNotFoundError(error) {
46965
47093
  }
46966
47094
 
46967
47095
  // src/provisioning/providers/appsync/read-state.ts
46968
- async function readCurrentState$13(physicalId, _logicalId, resourceType, properties) {
47096
+ async function readCurrentState$14(physicalId, _logicalId, resourceType, properties) {
46969
47097
  switch (resourceType) {
46970
47098
  case "AWS::AppSync::GraphQLApi": return this.readGraphQLApi(physicalId);
46971
47099
  case "AWS::AppSync::DataSource": return this.readDataSource(physicalId);
@@ -47527,7 +47655,7 @@ var AppSyncProvider = class {
47527
47655
  return isNotFoundError.call(this, error);
47528
47656
  }
47529
47657
  readCurrentState(physicalId, _logicalId, resourceType, properties) {
47530
- return readCurrentState$13.call(this, physicalId, _logicalId, resourceType, properties);
47658
+ return readCurrentState$14.call(this, physicalId, _logicalId, resourceType, properties);
47531
47659
  }
47532
47660
  canonicalizeSdl(sdl, source) {
47533
47661
  return canonicalizeSdl.call(this, sdl, source);
@@ -50663,7 +50791,26 @@ async function updateAlias(logicalId, physicalId, resourceType, properties, mask
50663
50791
  }
50664
50792
 
50665
50793
  // src/provisioning/providers/kms/read-state.ts
50666
- async function readCurrentStateKey(physicalId) {
50794
+ async function readKeyPolicy(keyId) {
50795
+ const policyResp = await this.getClient().send(new GetKeyPolicyCommand({
50796
+ KeyId: keyId,
50797
+ PolicyName: "default"
50798
+ }));
50799
+ if (!policyResp.Policy) return "failed";
50800
+ try {
50801
+ return { value: JSON.parse(policyResp.Policy) };
50802
+ } catch {
50803
+ return { value: policyResp.Policy };
50804
+ }
50805
+ }
50806
+ async function settleKeyPolicy(keyId, logicalId, first, declared) {
50807
+ const asMember = (answer) => typeof answer === "object" && !policyDocumentMatchesDeclared(answer.value, declared) && isKmsDefaultKeyPolicy(answer.value) ? "absent" : answer;
50808
+ return settleDeclaredMember(asMember(first), async () => asMember(await readKeyPolicy.call(this, keyId)), (value) => policyDocumentMatchesDeclared(value, declared), declared, this.ownWriteRereadDelaysMs, () => warnUnsettledMember(this.logger, logicalId, "AWS::KMS::Key", "KeyPolicy"));
50809
+ }
50810
+ function isKmsDefaultKeyPolicy(policy) {
50811
+ return typeof policy === "object" && policy !== null && policy["Id"] === "key-default-1";
50812
+ }
50813
+ async function readCurrentStateKey(physicalId, properties, context, logicalId = physicalId) {
50667
50814
  let resp;
50668
50815
  try {
50669
50816
  resp = await this.getClient().send(new DescribeKeyCommand({ KeyId: physicalId }));
@@ -50681,19 +50828,16 @@ async function readCurrentStateKey(physicalId) {
50681
50828
  if (md.MultiRegion !== void 0) result["MultiRegion"] = md.MultiRegion;
50682
50829
  if (md.Origin !== void 0) result["Origin"] = md.Origin;
50683
50830
  if (md.KeyId) {
50831
+ let keyPolicy;
50684
50832
  try {
50685
- const policyResp = await this.getClient().send(new GetKeyPolicyCommand({
50686
- KeyId: md.KeyId,
50687
- PolicyName: "default"
50688
- }));
50689
- if (policyResp.Policy) try {
50690
- result["KeyPolicy"] = JSON.parse(policyResp.Policy);
50691
- } catch {
50692
- result["KeyPolicy"] = policyResp.Policy;
50693
- }
50833
+ keyPolicy = await readKeyPolicy.call(this, md.KeyId);
50694
50834
  } catch (err) {
50695
50835
  if (err instanceof NotFoundException$2) return RESOURCE_NOT_FOUND;
50836
+ keyPolicy = memberReadFailure(err);
50696
50837
  }
50838
+ const declared = context?.afterOwnWrite === true ? declaredMemberDocument(properties?.["KeyPolicy"]) : void 0;
50839
+ if (declared !== void 0) keyPolicy = await settleKeyPolicy.call(this, md.KeyId, logicalId, keyPolicy, declared);
50840
+ if (typeof keyPolicy === "object") result["KeyPolicy"] = keyPolicy.value;
50697
50841
  if (md.KeySpec === void 0 || md.KeySpec === "SYMMETRIC_DEFAULT") try {
50698
50842
  const rotationResp = await this.getClient().send(new GetKeyRotationStatusCommand({ KeyId: md.KeyId }));
50699
50843
  result["EnableKeyRotation"] = rotationResp.KeyRotationEnabled ?? false;
@@ -50764,6 +50908,7 @@ var KMSProvider = class {
50764
50908
  createClient;
50765
50909
  providerRegion = ambientRegion();
50766
50910
  logger = getLogger().child("KMSProvider");
50911
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
50767
50912
  wrapCaughtError(mask, error, build) {
50768
50913
  const failure = describeAwsFailure(error);
50769
50914
  if (!(error instanceof Error) || !failure.redacted) return build(failure.detail);
@@ -50861,15 +51006,15 @@ var KMSProvider = class {
50861
51006
  deleteAlias(logicalId, physicalId, resourceType, context) {
50862
51007
  return deleteAlias.call(this, logicalId, physicalId, resourceType, context);
50863
51008
  }
50864
- async readCurrentState(physicalId, _logicalId, resourceType) {
51009
+ async readCurrentState(physicalId, _logicalId, resourceType, properties, context) {
50865
51010
  switch (resourceType) {
50866
- case "AWS::KMS::Key": return this.readCurrentStateKey(physicalId);
51011
+ case "AWS::KMS::Key": return this.readCurrentStateKey(physicalId, properties, context, _logicalId);
50867
51012
  case "AWS::KMS::Alias": return this.readCurrentStateAlias(physicalId);
50868
51013
  default: return;
50869
51014
  }
50870
51015
  }
50871
- readCurrentStateKey(physicalId) {
50872
- return readCurrentStateKey.call(this, physicalId);
51016
+ readCurrentStateKey(physicalId, properties, context, logicalId) {
51017
+ return readCurrentStateKey.call(this, physicalId, properties, context, logicalId);
50873
51018
  }
50874
51019
  getDriftUnknownPaths(resourceType) {
50875
51020
  if (resourceType === "AWS::KMS::Key") return ["BypassPolicyLockoutSafetyCheck", "PendingWindowInDays"];
@@ -51288,7 +51433,7 @@ async function deleteImpl$15(logicalId, physicalId, resourceType, _properties, c
51288
51433
  }
51289
51434
 
51290
51435
  // src/provisioning/providers/budgets-budget/read-state.ts
51291
- async function readCurrentState$12(physicalId, _logicalId, resourceType, properties) {
51436
+ async function readCurrentState$13(physicalId, _logicalId, resourceType, properties) {
51292
51437
  if (resourceType !== "AWS::Budgets::Budget") return void 0;
51293
51438
  const accountId = await this.resolveAccountId();
51294
51439
  const client = this.getClient();
@@ -51639,7 +51784,7 @@ var BudgetsBudgetProvider = class {
51639
51784
  }
51640
51785
  }
51641
51786
  readCurrentState(physicalId, logicalId, resourceType, properties) {
51642
- return readCurrentState$12.call(this, physicalId, logicalId, resourceType, properties);
51787
+ return readCurrentState$13.call(this, physicalId, logicalId, resourceType, properties);
51643
51788
  }
51644
51789
  listNotifications(accountId, budgetName) {
51645
51790
  return listNotifications.call(this, accountId, budgetName);
@@ -52291,7 +52436,7 @@ async function unsettledInTransition$2(physicalId, _logicalId, _resourceType, na
52291
52436
  return names;
52292
52437
  }
52293
52438
  }
52294
- async function readCurrentState$11(physicalId, _logicalId, resourceType, _properties) {
52439
+ async function readCurrentState$12(physicalId, _logicalId, resourceType, _properties) {
52295
52440
  if (resourceType !== "AWS::Kinesis::Stream") return void 0;
52296
52441
  let stream;
52297
52442
  try {
@@ -52422,7 +52567,7 @@ var KinesisStreamProvider = class {
52422
52567
  return unsettledInTransition$2.call(this, physicalId, _logicalId, _resourceType, names);
52423
52568
  }
52424
52569
  readCurrentState(physicalId, _logicalId, resourceType, _properties) {
52425
- return readCurrentState$11.call(this, physicalId, _logicalId, resourceType, _properties);
52570
+ return readCurrentState$12.call(this, physicalId, _logicalId, resourceType, _properties);
52426
52571
  }
52427
52572
  import(input) {
52428
52573
  return importImpl$12.call(this, input);
@@ -53022,7 +53167,7 @@ async function getAttribute$4(physicalId, resourceType, attributeName, logicalId
53022
53167
  throw this.wrapCaughtError(void 0, error, (text) => new ProvisioningError(`Failed to resolve Arn for Schedule ${physicalId}: ${text}${text.endsWith(".") ? "" : "."}${customGroupHint}`, resourceType, logicalId, physicalId, cause));
53023
53168
  }
53024
53169
  }
53025
- async function readCurrentState$10(physicalId, _logicalId, _resourceType, properties) {
53170
+ async function readCurrentState$11(physicalId, _logicalId, _resourceType, properties) {
53026
53171
  const groupName = this.groupNameOf(properties);
53027
53172
  try {
53028
53173
  const response = await this.getClient().send(new GetScheduleCommand({
@@ -53152,7 +53297,7 @@ var SchedulerScheduleProvider = class {
53152
53297
  return getAttribute$4.call(this, physicalId, resourceType, attributeName, logicalId);
53153
53298
  }
53154
53299
  readCurrentState(physicalId, _logicalId, _resourceType, properties) {
53155
- return readCurrentState$10.call(this, physicalId, _logicalId, _resourceType, properties);
53300
+ return readCurrentState$11.call(this, physicalId, _logicalId, _resourceType, properties);
53156
53301
  }
53157
53302
  import(input) {
53158
53303
  return importImpl$11.call(this, input);
@@ -53667,7 +53812,7 @@ async function getAttribute$3(physicalId, resourceType, attributeName, logicalId
53667
53812
  }
53668
53813
  return this.attributesOf(response)[attributeName];
53669
53814
  }
53670
- async function readCurrentState$9(physicalId, _logicalId, _resourceType) {
53815
+ async function readCurrentState$10(physicalId, _logicalId, _resourceType) {
53671
53816
  let r;
53672
53817
  try {
53673
53818
  r = await this.describe(physicalId);
@@ -53820,7 +53965,7 @@ var PipesPipeProvider = class {
53820
53965
  return getAttribute$3.call(this, physicalId, resourceType, attributeName, logicalId);
53821
53966
  }
53822
53967
  readCurrentState(physicalId, _logicalId, _resourceType) {
53823
- return readCurrentState$9.call(this, physicalId, _logicalId, _resourceType);
53968
+ return readCurrentState$10.call(this, physicalId, _logicalId, _resourceType);
53824
53969
  }
53825
53970
  getDriftUnknownPaths() {
53826
53971
  return ["SourceParameters", "TargetParameters"];
@@ -53961,7 +54106,7 @@ async function retryOnTransientControlPlane(op, label, log, maxAttempts = 8) {
53961
54106
  delayMs = Math.min(delayMs * 2, 3e4);
53962
54107
  }
53963
54108
  }
53964
- async function readCurrentState$8(physicalId, _logicalId, resourceType) {
54109
+ async function readCurrentState$9(physicalId, _logicalId, resourceType) {
53965
54110
  switch (resourceType) {
53966
54111
  case "AWS::EFS::FileSystem": return this.readFileSystem(physicalId);
53967
54112
  case "AWS::EFS::AccessPoint": return this.readAccessPoint(physicalId);
@@ -54568,7 +54713,22 @@ async function deleteAccessPoint(logicalId, physicalId, resourceType, context) {
54568
54713
  }
54569
54714
 
54570
54715
  // src/provisioning/providers/efs/read-state.ts
54571
- async function readFileSystem(physicalId) {
54716
+ async function readFileSystemPolicy(physicalId) {
54717
+ let policy;
54718
+ try {
54719
+ policy = (await this.getClient().send(new DescribeFileSystemPolicyCommand({ FileSystemId: physicalId }))).Policy;
54720
+ } catch (err) {
54721
+ if (err.name === "PolicyNotFound") return "absent";
54722
+ throw err;
54723
+ }
54724
+ if (policy === void 0) return "failed";
54725
+ try {
54726
+ return { value: JSON.parse(policy) };
54727
+ } catch {
54728
+ return { value: policy };
54729
+ }
54730
+ }
54731
+ async function readFileSystem(physicalId, properties, context, logicalId = physicalId) {
54572
54732
  let fs;
54573
54733
  let listed;
54574
54734
  try {
@@ -54607,16 +54767,16 @@ async function readFileSystem(physicalId) {
54607
54767
  } catch (err) {
54608
54768
  if (err instanceof FileSystemNotFound) return RESOURCE_NOT_FOUND;
54609
54769
  }
54770
+ let policy;
54610
54771
  try {
54611
- const resp = await this.getClient().send(new DescribeFileSystemPolicyCommand({ FileSystemId: physicalId }));
54612
- if (resp.Policy !== void 0) try {
54613
- result["FileSystemPolicy"] = JSON.parse(resp.Policy);
54614
- } catch {
54615
- result["FileSystemPolicy"] = resp.Policy;
54616
- }
54772
+ policy = await readFileSystemPolicy.call(this, physicalId);
54617
54773
  } catch (err) {
54618
54774
  if (err instanceof FileSystemNotFound) return RESOURCE_NOT_FOUND;
54775
+ policy = memberReadFailure(err);
54619
54776
  }
54777
+ const declared = context?.afterOwnWrite === true ? declaredMemberDocument(properties?.["FileSystemPolicy"]) : void 0;
54778
+ if (declared !== void 0) policy = await settleDeclaredMember(policy, () => readFileSystemPolicy.call(this, physicalId), (document) => efsPolicyMatchesDeclared(document, declared, physicalId), declared, this.ownWriteRereadDelaysMs, () => warnUnsettledMember(this.logger, logicalId, "AWS::EFS::FileSystem", "FileSystemPolicy"));
54779
+ if (typeof policy === "object") result["FileSystemPolicy"] = policy.value;
54620
54780
  result["FileSystemTags"] = normalizeAwsTagsToCfn(fs.Tags);
54621
54781
  return result;
54622
54782
  }
@@ -54731,6 +54891,7 @@ var EFSProvider = class {
54731
54891
  mountTargetCreateClient;
54732
54892
  providerRegion = ambientRegion();
54733
54893
  logger = getLogger().child("EFSProvider");
54894
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
54734
54895
  unconfirmedCreationTokens = /* @__PURE__ */ new Map();
54735
54896
  removalDefaults = /* @__PURE__ */ new Map([["AWS::EFS::FileSystem", /* @__PURE__ */ new Map([["BackupPolicy", { Status: "DISABLED" }], ["FileSystemProtection", { ReplicationOverwriteProtection: "ENABLED" }]])]]);
54736
54897
  handledProperties = /* @__PURE__ */ new Map([
@@ -54857,11 +55018,12 @@ var EFSProvider = class {
54857
55018
  deleteAccessPoint(logicalId, physicalId, resourceType, context) {
54858
55019
  return deleteAccessPoint.call(this, logicalId, physicalId, resourceType, context);
54859
55020
  }
54860
- readCurrentState(physicalId, _logicalId, resourceType) {
54861
- return readCurrentState$8.call(this, physicalId, _logicalId, resourceType);
55021
+ readCurrentState(physicalId, _logicalId, resourceType, properties, context) {
55022
+ if (resourceType === "AWS::EFS::FileSystem") return this.readFileSystem(physicalId, properties, context, _logicalId);
55023
+ return readCurrentState$9.call(this, physicalId, _logicalId, resourceType);
54862
55024
  }
54863
- readFileSystem(physicalId) {
54864
- return readFileSystem.call(this, physicalId);
55025
+ readFileSystem(physicalId, properties, context, logicalId) {
55026
+ return readFileSystem.call(this, physicalId, properties, context, logicalId);
54865
55027
  }
54866
55028
  readAccessPoint(physicalId) {
54867
55029
  return readAccessPoint.call(this, physicalId);
@@ -56036,7 +56198,7 @@ function getDriftUnorderedPaths(resourceType) {
56036
56198
  if (resourceType !== "AWS::FSx::FileSystem") return [];
56037
56199
  return ["WindowsConfiguration.Aliases"];
56038
56200
  }
56039
- async function readCurrentState$7(physicalId, _logicalId, resourceType) {
56201
+ async function readCurrentState$8(physicalId, _logicalId, resourceType) {
56040
56202
  if (resourceType !== "AWS::FSx::FileSystem") return void 0;
56041
56203
  let fs;
56042
56204
  let listed;
@@ -56281,7 +56443,7 @@ var FSxFileSystemProvider = class {
56281
56443
  return getDriftUnorderedPaths.call(this, resourceType);
56282
56444
  }
56283
56445
  readCurrentState(physicalId, _logicalId, resourceType) {
56284
- return readCurrentState$7.call(this, physicalId, _logicalId, resourceType);
56446
+ return readCurrentState$8.call(this, physicalId, _logicalId, resourceType);
56285
56447
  }
56286
56448
  import(input) {
56287
56449
  return importImpl$8.call(this, input);
@@ -57933,7 +58095,7 @@ async function describeClusterOrUndefined(clusterId) {
57933
58095
  throw err;
57934
58096
  }
57935
58097
  }
57936
- async function readCurrentState$6(physicalId, _logicalId, _resourceType) {
58098
+ async function readCurrentState$7(physicalId, _logicalId, _resourceType) {
57937
58099
  const cluster = await this.describeClusterOrUndefined(physicalId);
57938
58100
  if (!cluster) return void 0;
57939
58101
  if (cluster.Status?.State && TERMINAL_STATES.has(cluster.Status.State)) return RESOURCE_NOT_FOUND;
@@ -58196,7 +58358,7 @@ var EMRClusterProvider = class {
58196
58358
  return describeClusterOrUndefined.call(this, clusterId);
58197
58359
  }
58198
58360
  readCurrentState(physicalId, _logicalId, _resourceType) {
58199
- return readCurrentState$6.call(this, physicalId, _logicalId, _resourceType);
58361
+ return readCurrentState$7.call(this, physicalId, _logicalId, _resourceType);
58200
58362
  }
58201
58363
  getDriftUnknownPaths(_resourceType) {
58202
58364
  return [
@@ -59371,7 +59533,7 @@ async function unsettledInTransition(physicalId, _logicalId, _resourceType, name
59371
59533
  return /* @__PURE__ */ new Set([ENCRYPTION_KEY]);
59372
59534
  }
59373
59535
  }
59374
- async function readCurrentState$5(physicalId, _logicalId, _resourceType, properties) {
59536
+ async function readCurrentState$6(physicalId, _logicalId, _resourceType, properties) {
59375
59537
  let desc;
59376
59538
  try {
59377
59539
  desc = (await this.getClient().send(new DescribeDeliveryStreamCommand({ DeliveryStreamName: physicalId }))).DeliveryStreamDescription;
@@ -59579,7 +59741,7 @@ var FirehoseProvider = class {
59579
59741
  return unsettledInTransition.call(this, physicalId, _logicalId, _resourceType, names);
59580
59742
  }
59581
59743
  readCurrentState(physicalId, _logicalId, _resourceType, properties) {
59582
- return readCurrentState$5.call(this, physicalId, _logicalId, _resourceType, properties);
59744
+ return readCurrentState$6.call(this, physicalId, _logicalId, _resourceType, properties);
59583
59745
  }
59584
59746
  getDriftUnknownPaths() {
59585
59747
  return getDriftUnknownPaths.call(this);
@@ -60048,7 +60210,7 @@ async function applyTagDiff(trailArn, resourceType, logicalId, oldTagsRaw, newTa
60048
60210
  }
60049
60211
 
60050
60212
  // src/provisioning/providers/cloudtrail/read-state.ts
60051
- async function readCurrentState$4(physicalId, _logicalId, _resourceType) {
60213
+ async function readCurrentState$5(physicalId, _logicalId, _resourceType) {
60052
60214
  let trail;
60053
60215
  try {
60054
60216
  trail = (await this.getClient().send(new GetTrailCommand({ Name: physicalId }))).Trail;
@@ -60205,7 +60367,7 @@ var CloudTrailProvider = class {
60205
60367
  return applyTagDiff.call(this, trailArn, resourceType, logicalId, oldTagsRaw, newTagsRaw);
60206
60368
  }
60207
60369
  readCurrentState(physicalId, _logicalId, _resourceType) {
60208
- return readCurrentState$4.call(this, physicalId, _logicalId, _resourceType);
60370
+ return readCurrentState$5.call(this, physicalId, _logicalId, _resourceType);
60209
60371
  }
60210
60372
  import(input) {
60211
60373
  return importImpl$5.call(this, input);
@@ -60646,7 +60808,15 @@ async function deleteImpl$5(logicalId, physicalId, resourceType, _properties, co
60646
60808
  }
60647
60809
 
60648
60810
  // src/provisioning/providers/codebuild/read-state.ts
60649
- async function readCurrentState$3(physicalId, _logicalId, _resourceType) {
60811
+ async function readCurrentState$4(physicalId, logicalId, _resourceType, properties, context) {
60812
+ const read = await readProject.call(this, physicalId);
60813
+ const declared = context?.afterOwnWrite === true ? properties?.["Visibility"] : void 0;
60814
+ if (typeof declared !== "string" || declared === "" || read === RESOURCE_NOT_FOUND) return read;
60815
+ const asMember = (answer) => answer === RESOURCE_NOT_FOUND ? "failed" : { value: answer };
60816
+ const settled = await settleDeclaredMember(asMember(read), async () => asMember(await readProject.call(this, physicalId)), (project) => project["Visibility"] === declared, read, this.ownWriteRereadDelaysMs, () => warnUnsettledMember(this.logger, logicalId, "AWS::CodeBuild::Project", "Visibility"));
60817
+ return typeof settled === "object" ? settled.value : read;
60818
+ }
60819
+ async function readProject(physicalId) {
60650
60820
  let project;
60651
60821
  try {
60652
60822
  project = (await this.getClient().send(new BatchGetProjectsCommand({ names: [physicalId] }))).projects?.[0];
@@ -60838,6 +61008,7 @@ var CodeBuildProvider = class {
60838
61008
  createClient;
60839
61009
  providerRegion = ambientRegion();
60840
61010
  logger = getLogger().child("CodeBuildProvider");
61011
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
60841
61012
  disableCcApiFallback = true;
60842
61013
  handledProperties = /* @__PURE__ */ new Map([["AWS::CodeBuild::Project", /* @__PURE__ */ new Set([
60843
61014
  "Name",
@@ -60926,8 +61097,8 @@ var CodeBuildProvider = class {
60926
61097
  getAttribute(_physicalId, _resourceType, attributeName) {
60927
61098
  return Promise.resolve(attributeName);
60928
61099
  }
60929
- readCurrentState(physicalId, _logicalId, _resourceType) {
60930
- return readCurrentState$3.call(this, physicalId, _logicalId, _resourceType);
61100
+ readCurrentState(physicalId, _logicalId, _resourceType, properties, context) {
61101
+ return readCurrentState$4.call(this, physicalId, _logicalId, _resourceType, properties, context);
60931
61102
  }
60932
61103
  getDriftUnknownPaths() {
60933
61104
  return ["Source.Auth", "Triggers"];
@@ -61367,7 +61538,7 @@ function proceedUnconfirmed(logicalId, reason) {
61367
61538
  }
61368
61539
 
61369
61540
  // src/provisioning/providers/codecommit-repository/read-state.ts
61370
- async function readCurrentState$2(physicalId, _logicalId, _resourceType) {
61541
+ async function readCurrentState$3(physicalId, _logicalId, _resourceType) {
61371
61542
  let metadata;
61372
61543
  try {
61373
61544
  metadata = await this.getRepositoryMetadata(physicalId);
@@ -61509,7 +61680,7 @@ var CodeCommitRepositoryProvider = class {
61509
61680
  }
61510
61681
  }
61511
61682
  readCurrentState(physicalId, _logicalId, _resourceType) {
61512
- return readCurrentState$2.call(this, physicalId, _logicalId, _resourceType);
61683
+ return readCurrentState$3.call(this, physicalId, _logicalId, _resourceType);
61513
61684
  }
61514
61685
  getDriftUnknownPaths(_resourceType) {
61515
61686
  return ["Code", "Triggers"];
@@ -63731,7 +63902,7 @@ async function lookupTableArn(tableBucketARN, namespace, name) {
63731
63902
  }
63732
63903
 
63733
63904
  // src/provisioning/providers/s3-tables/read-state.ts
63734
- async function readCurrentState$1(physicalId, logicalId, resourceType) {
63905
+ async function readCurrentState$2(physicalId, logicalId, resourceType) {
63735
63906
  switch (resourceType) {
63736
63907
  case "AWS::S3Tables::TableBucket": return this.readTableBucketCurrentState(physicalId);
63737
63908
  case "AWS::S3Tables::Namespace": return this.readNamespaceCurrentState(physicalId);
@@ -64283,7 +64454,7 @@ var S3TablesProvider = class {
64283
64454
  return createTable.call(this, logicalId, resourceType, properties, context);
64284
64455
  }
64285
64456
  readCurrentState(physicalId, logicalId, resourceType) {
64286
- return readCurrentState$1.call(this, physicalId, logicalId, resourceType);
64457
+ return readCurrentState$2.call(this, physicalId, logicalId, resourceType);
64287
64458
  }
64288
64459
  readTableBucketCurrentState(physicalId) {
64289
64460
  return readTableBucketCurrentState.call(this, physicalId);
@@ -64347,12 +64518,117 @@ var S3TablesProvider = class {
64347
64518
  }
64348
64519
  };
64349
64520
 
64521
+ // src/provisioning/providers/ecr/read-state.ts
64522
+ const REPOSITORY_TYPE = "AWS::ECR::Repository";
64523
+ function toCfnTagMutabilityExclusionFilters(sdk) {
64524
+ if (!sdk || sdk.length === 0) return void 0;
64525
+ return sdk.map((f) => ({
64526
+ ...f.filterType !== void 0 && { ImageTagMutabilityExclusionFilterType: f.filterType },
64527
+ ...f.filter !== void 0 && { ImageTagMutabilityExclusionFilterValue: f.filter }
64528
+ }));
64529
+ }
64530
+ async function readRepositoryPolicy(repositoryName) {
64531
+ let policyText;
64532
+ try {
64533
+ policyText = (await this.getClient().send(new GetRepositoryPolicyCommand({ repositoryName }))).policyText;
64534
+ } catch (err) {
64535
+ if (err instanceof RepositoryPolicyNotFoundException) return "absent";
64536
+ throw err;
64537
+ }
64538
+ if (!policyText) return "absent";
64539
+ try {
64540
+ return { value: JSON.parse(policyText) };
64541
+ } catch {
64542
+ return { value: policyText };
64543
+ }
64544
+ }
64545
+ async function readPolicyMember(repositoryName, logicalId, properties, context) {
64546
+ const declared = declaredMemberDocument(properties?.["RepositoryPolicyText"]);
64547
+ if (declared === void 0) return void 0;
64548
+ if (context?.afterOwnWrite !== true) {
64549
+ const read = await readRepositoryPolicy.call(this, repositoryName);
64550
+ return typeof read === "object" ? read : void 0;
64551
+ }
64552
+ let firstError;
64553
+ let first;
64554
+ try {
64555
+ first = await readRepositoryPolicy.call(this, repositoryName);
64556
+ } catch (err) {
64557
+ if (err instanceof RepositoryNotFoundException) throw err;
64558
+ firstError = err;
64559
+ first = memberReadFailure(err);
64560
+ }
64561
+ const settled = await settleDeclaredMember(first, () => readRepositoryPolicy.call(this, repositoryName), (document) => policyDocumentMatchesDeclared(document, declared), declared, this.ownWriteRereadDelaysMs, () => warnUnsettledMember(this.logger, logicalId, REPOSITORY_TYPE, "RepositoryPolicyText"));
64562
+ if (settled === "failed" || settled === "refused") throw firstError;
64563
+ return typeof settled === "object" ? settled : void 0;
64564
+ }
64565
+ function settle(promise) {
64566
+ return promise.then((value) => ({
64567
+ ok: true,
64568
+ value
64569
+ }), (error) => ({
64570
+ ok: false,
64571
+ error
64572
+ }));
64573
+ }
64574
+ async function readCurrentState$1(physicalId, logicalId, properties, context) {
64575
+ let repo;
64576
+ try {
64577
+ repo = await this.getClient().send(new DescribeRepositoriesCommand({ repositoryNames: [physicalId] }));
64578
+ } catch (err) {
64579
+ if (err instanceof RepositoryNotFoundException) return RESOURCE_NOT_FOUND;
64580
+ throw err;
64581
+ }
64582
+ const r = repo.repositories?.[0];
64583
+ if (!r) return RESOURCE_NOT_FOUND;
64584
+ const result = {};
64585
+ if (r.repositoryName !== void 0) result["RepositoryName"] = r.repositoryName;
64586
+ if (r.imageTagMutability !== void 0) result["ImageTagMutability"] = r.imageTagMutability;
64587
+ const cfnExclusionFilters = toCfnTagMutabilityExclusionFilters(r.imageTagMutabilityExclusionFilters);
64588
+ if (cfnExclusionFilters) result["ImageTagMutabilityExclusionFilters"] = cfnExclusionFilters;
64589
+ result["ImageScanningConfiguration"] = { ScanOnPush: r.imageScanningConfiguration?.scanOnPush ?? false };
64590
+ {
64591
+ const encType = r.encryptionConfiguration?.encryptionType ?? "AES256";
64592
+ const enc = { EncryptionType: encType };
64593
+ if (encType === "KMS" && r.encryptionConfiguration?.kmsKey) enc["KmsKey"] = r.encryptionConfiguration.kmsKey;
64594
+ result["EncryptionConfiguration"] = enc;
64595
+ }
64596
+ const client = this.getClient();
64597
+ const readLifecycle = async () => {
64598
+ try {
64599
+ return (await client.send(new GetLifecyclePolicyCommand({ repositoryName: physicalId }))).lifecyclePolicyText;
64600
+ } catch (err) {
64601
+ if (err instanceof LifecyclePolicyNotFoundException) return void 0;
64602
+ throw err;
64603
+ }
64604
+ };
64605
+ const arn = r.repositoryArn;
64606
+ const readTags = async () => arn === void 0 || arn === "" ? void 0 : normalizeAwsTagsToCfn((await client.send(new ListTagsForResourceCommand$9({ resourceArn: arn }))).tags);
64607
+ const [lifecycle, policy, tags] = await Promise.all([
64608
+ settle(readLifecycle()),
64609
+ settle(readPolicyMember.call(this, physicalId, logicalId, properties, context)),
64610
+ settle(readTags())
64611
+ ]);
64612
+ const reads = [
64613
+ lifecycle,
64614
+ policy,
64615
+ tags
64616
+ ];
64617
+ if (reads.some((s) => !s.ok && s.error instanceof RepositoryNotFoundException)) return RESOURCE_NOT_FOUND;
64618
+ for (const s of reads) if (!s.ok) throw s.error;
64619
+ if (lifecycle.ok && lifecycle.value) result["LifecyclePolicy"] = { LifecyclePolicyText: lifecycle.value };
64620
+ if (policy.ok && policy.value !== void 0) result["RepositoryPolicyText"] = policy.value.value;
64621
+ if (tags.ok && tags.value !== void 0) result["Tags"] = tags.value;
64622
+ return result;
64623
+ }
64624
+
64350
64625
  // src/provisioning/providers/ecr-provider.ts
64351
64626
  var ECRProvider = class {
64352
64627
  client;
64353
64628
  createClient;
64354
64629
  providerRegion = ambientRegion();
64355
64630
  logger = getLogger().child("ECRProvider");
64631
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
64356
64632
  handledProperties = /* @__PURE__ */ new Map([["AWS::ECR::Repository", /* @__PURE__ */ new Set([
64357
64633
  "RepositoryName",
64358
64634
  "ImageScanningConfiguration",
@@ -64400,13 +64676,6 @@ var ECRProvider = class {
64400
64676
  };
64401
64677
  });
64402
64678
  }
64403
- toCfnTagMutabilityExclusionFilters(sdk) {
64404
- if (!sdk || sdk.length === 0) return void 0;
64405
- return sdk.map((f) => ({
64406
- ...f.filterType !== void 0 && { ImageTagMutabilityExclusionFilterType: f.filterType },
64407
- ...f.filter !== void 0 && { ImageTagMutabilityExclusionFilterValue: f.filter }
64408
- }));
64409
- }
64410
64679
  async create(logicalId, resourceType, properties, context) {
64411
64680
  this.logger.debug(`Creating ECR Repository ${logicalId}`);
64412
64681
  const desiredTags = refuseMalformedDesiredTags(properties["Tags"], resourceType, logicalId);
@@ -64587,43 +64856,22 @@ var ECRProvider = class {
64587
64856
  throw error instanceof Error && error.name.includes("NotFound") ? markNotGone(thrown) : thrown;
64588
64857
  }
64589
64858
  }
64590
- async readCurrentState(physicalId, _logicalId, _resourceType) {
64591
- let repo;
64592
- try {
64593
- repo = await this.getClient().send(new DescribeRepositoriesCommand({ repositoryNames: [physicalId] }));
64594
- } catch (err) {
64595
- if (err instanceof RepositoryNotFoundException) return RESOURCE_NOT_FOUND;
64596
- throw err;
64597
- }
64598
- const r = repo.repositories?.[0];
64599
- if (!r) return RESOURCE_NOT_FOUND;
64600
- const result = {};
64601
- if (r.repositoryName !== void 0) result["RepositoryName"] = r.repositoryName;
64602
- if (r.imageTagMutability !== void 0) result["ImageTagMutability"] = r.imageTagMutability;
64603
- const cfnExclusionFilters = this.toCfnTagMutabilityExclusionFilters(r.imageTagMutabilityExclusionFilters);
64604
- if (cfnExclusionFilters) result["ImageTagMutabilityExclusionFilters"] = cfnExclusionFilters;
64605
- result["ImageScanningConfiguration"] = { ScanOnPush: r.imageScanningConfiguration?.scanOnPush ?? false };
64606
- {
64607
- const encType = r.encryptionConfiguration?.encryptionType ?? "AES256";
64608
- const enc = { EncryptionType: encType };
64609
- if (encType === "KMS" && r.encryptionConfiguration?.kmsKey) enc["KmsKey"] = r.encryptionConfiguration.kmsKey;
64610
- result["EncryptionConfiguration"] = enc;
64611
- }
64612
- try {
64613
- const lp = await this.getClient().send(new GetLifecyclePolicyCommand({ repositoryName: physicalId }));
64614
- if (lp.lifecyclePolicyText) result["LifecyclePolicy"] = { LifecyclePolicyText: lp.lifecyclePolicyText };
64615
- } catch (err) {
64616
- if (err instanceof RepositoryNotFoundException) return RESOURCE_NOT_FOUND;
64617
- if (!(err instanceof LifecyclePolicyNotFoundException)) throw err;
64618
- }
64619
- if (r.repositoryArn) try {
64620
- const tagsResp = await this.getClient().send(new ListTagsForResourceCommand$9({ resourceArn: r.repositoryArn }));
64621
- result["Tags"] = normalizeAwsTagsToCfn(tagsResp.tags);
64622
- } catch (err) {
64623
- if (err instanceof RepositoryNotFoundException) return RESOURCE_NOT_FOUND;
64624
- throw err;
64625
- }
64626
- return result;
64859
+ readCurrentState(physicalId, logicalId, _resourceType, properties, context) {
64860
+ return readCurrentState$1.call(this, physicalId, logicalId, properties, context);
64861
+ }
64862
+ getDriftUnknownPaths(resourceType) {
64863
+ return resourceType === "AWS::ECR::Repository" ? ["EmptyOnDelete"] : [];
64864
+ }
64865
+ canonicalizeDriftProperties(resourceType, properties) {
64866
+ if (resourceType !== "AWS::ECR::Repository") return properties;
64867
+ const policy = properties["RepositoryPolicyText"];
64868
+ if (typeof policy !== "string") return properties;
64869
+ const parsed = declaredMemberDocument(policy);
64870
+ if (typeof parsed !== "object" || parsed === null) return properties;
64871
+ return {
64872
+ ...properties,
64873
+ RepositoryPolicyText: parsed
64874
+ };
64627
64875
  }
64628
64876
  async import(input) {
64629
64877
  const explicit = resolveExplicitPhysicalId(input, "RepositoryName");
@@ -65233,6 +65481,12 @@ async function cleanupRequestedCertificate(certificateArn, logicalId, idempotenc
65233
65481
  }
65234
65482
 
65235
65483
  // src/provisioning/providers/acm-certificate/update.ts
65484
+ function sameNamesWithDomain(properties) {
65485
+ const sans = properties["SubjectAlternativeNames"];
65486
+ const names = new Set(Array.isArray(sans) ? sans : sans === void 0 ? [] : [sans]);
65487
+ names.add(properties["DomainName"]);
65488
+ return JSON.stringify([...names].map((n) => JSON.stringify(n)).sort());
65489
+ }
65236
65490
  async function update(logicalId, physicalId, resourceType, properties, previousProperties, context) {
65237
65491
  this.logger.debug(`Updating ACM certificate ${logicalId}: ${physicalId}`);
65238
65492
  properties = withRemovalDefaults(this.removalDefaults, resourceType, properties, previousProperties, context);
@@ -65249,6 +65503,7 @@ async function update(logicalId, physicalId, resourceType, properties, previousP
65249
65503
  let changedImmutable;
65250
65504
  for (const k of immutableFields) {
65251
65505
  if (JSON.stringify(properties[k]) === JSON.stringify(previousProperties[k])) continue;
65506
+ if (k === "SubjectAlternativeNames" && isDriftRevert(context) && sameNamesWithDomain(properties) === sameNamesWithDomain(previousProperties)) continue;
65252
65507
  if (k === "CertificateExport" && (properties[k] ?? "DISABLED") === (previousProperties[k] ?? "DISABLED")) continue;
65253
65508
  if (await unchangedBehindSecretReference({
65254
65509
  resourceType,
@@ -65261,6 +65516,7 @@ async function update(logicalId, physicalId, resourceType, properties, previousP
65261
65516
  break;
65262
65517
  }
65263
65518
  if (changedImmutable) {
65519
+ if (isDriftRevert(context)) throw revertReplacementRefusal(resourceType, logicalId, `its ${changedImmutable} differs from the live certificate's and cannot change in place`);
65264
65520
  this.logger.debug(`${changedImmutable} changed, replacing ACM certificate: ${physicalId}`);
65265
65521
  const createResult = await this.create(logicalId, resourceType, properties, context?.maskSecrets ? { maskSecrets: context.maskSecrets } : void 0);
65266
65522
  let orphanReason;
@@ -65561,4 +65817,4 @@ var ACMCertificateProvider = class {
65561
65817
  };
65562
65818
 
65563
65819
  export { ACMCertificateProvider, ASGProvider, AgentCoreBrowserProvider, AgentCoreCodeInterpreterProvider, AgentCoreEvaluatorProvider, AgentCoreRuntimeProvider, ApiGatewayProvider, ApiGatewayV2Provider, AppConfigEnvironmentProvider, AppSyncProvider, BudgetsBudgetProvider, CloudFrontDistributionProvider, CloudFrontOACProvider, CloudFrontOAIProvider, CloudTrailProvider, CloudWatchAlarmProvider, CloudWatchAnomalyDetectorProvider, CodeBuildProvider, CodeCommitRepositoryProvider, CognitoUserPoolProvider, DLMLifecyclePolicyProvider, DocDBProvider, DocDBSubnetGroupProvider, DynamoDBGlobalTableProvider, DynamoDBTableProvider, EC2Provider, ECRProvider, ECSProvider, EFSProvider, ELBv2Provider, EMRClusterProvider, EMRInstanceFleetConfigProvider, EMRInstanceGroupConfigProvider, ElastiCacheProvider, EventBridgeArchiveProvider, EventBridgeBusProvider, EventBridgeRuleProvider, FSxFileSystemProvider, FirehoseProvider, GlueConnectionProvider, GlueCrawlerProvider, GlueJobProvider, GlueProvider, GlueSecurityConfigurationProvider, GlueTriggerProvider, GlueWorkflowProvider, IAMAccessKeyProvider, IAMInstanceProfileProvider, IAMManagedPolicyProvider, IAMPolicyProvider, IAMRoleProvider, IAMUserGroupProvider, KMSProvider, KinesisStreamConsumerProvider, KinesisStreamProvider, LambdaEventInvokeConfigProvider, LambdaEventSourceMappingProvider, LambdaFunctionProvider, LambdaLayerVersionProvider, LambdaMicrovmImageProvider, LambdaNetworkConnectorProvider, LambdaPermissionProvider, LambdaUrlProvider, LambdaWebFunctionEndpointProvider, LambdaWebFunctionRevisionProvider, LogsDeliveryDestinationProvider, LogsDeliveryProvider, LogsDeliverySourceProvider, LogsLogGroupProvider, NeptuneProvider, NestedStackProvider, PipesPipeProvider, RDSDBProxyEndpointProvider, RDSDBProxyProvider, RDSDBProxyTargetGroupProvider, RDSProvider, Route53Provider, S3BucketPolicyProvider, S3BucketProvider, S3DirectoryBucketProvider, S3TablesProvider, S3VectorsProvider, SNSSubscriptionProvider, SNSTopicPolicyProvider, SNSTopicProvider, SQSQueuePolicyProvider, SQSQueueProvider, SSMParameterProvider, SchedulerScheduleProvider, SecretsManagerSecretProvider, ServiceDiscoveryProvider, StepFunctionsProvider, WAFv2WebACLProvider, WaitConditionHandleProvider };
65564
- //# sourceMappingURL=provider-classes-CwFJ4uJU.js.map
65820
+ //# sourceMappingURL=provider-classes-ZbdmR8mu.js.map