@cdkd/cli 0.358.2 → 0.358.4

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 (55) hide show
  1. package/dist/{ambient-client-defaults-ov4YgebP.js → ambient-client-defaults-CcCQuSZx.js} +4 -3
  2. package/dist/ambient-client-defaults-CcCQuSZx.js.map +1 -0
  3. package/dist/{asg-provider-B3SM2Pb6.js → asg-provider-BYsZoqmF.js} +6 -6
  4. package/dist/{asg-provider-B3SM2Pb6.js.map → asg-provider-BYsZoqmF.js.map} +1 -1
  5. package/dist/cli.js +3 -3
  6. package/dist/{custom-resource-runtime-C2L70Uvt.js → custom-resource-runtime-vUQQgT6M.js} +6 -6
  7. package/dist/{custom-resource-runtime-C2L70Uvt.js.map → custom-resource-runtime-vUQQgT6M.js.map} +1 -1
  8. package/dist/{db-associated-roles-BtFMDSS8.js → db-associated-roles-D1kkpP0k.js} +2 -2
  9. package/dist/{db-associated-roles-BtFMDSS8.js.map → db-associated-roles-D1kkpP0k.js.map} +1 -1
  10. package/dist/{delete-started-D6-EOWNl.js → delete-started-joCwegKq.js} +4 -4
  11. package/dist/{delete-started-D6-EOWNl.js.map → delete-started-joCwegKq.js.map} +1 -1
  12. package/dist/{deploy-engine-C7WHVVa_.js → deploy-engine-CilA7v8d.js} +977 -84
  13. package/dist/deploy-engine-CilA7v8d.js.map +1 -0
  14. package/dist/{diff-calculator-CfIvxdWW.js → diff-calculator-Bjr0sh-h.js} +12 -12
  15. package/dist/{diff-calculator-CfIvxdWW.js.map → diff-calculator-Bjr0sh-h.js.map} +1 -1
  16. package/dist/{ec2-termination-protection-BftAVRVj.js → ec2-termination-protection-Gdl3Djvt.js} +6 -6
  17. package/dist/{ec2-termination-protection-BftAVRVj.js.map → ec2-termination-protection-Gdl3Djvt.js.map} +1 -1
  18. package/dist/{ecr-uri-BcxKuVtg.js → ecr-uri-BhoeLkz2.js} +2 -2
  19. package/dist/{ecr-uri-BcxKuVtg.js.map → ecr-uri-BhoeLkz2.js.map} +1 -1
  20. package/dist/{expected-bucket-owner-DF9akR1A.js → expected-bucket-owner-CIiqUDil.js} +2 -2
  21. package/dist/{expected-bucket-owner-DF9akR1A.js.map → expected-bucket-owner-CIiqUDil.js.map} +1 -1
  22. package/dist/{iam-role-provider-D83igvxU.js → iam-role-provider-gS0g_h2H.js} +8 -8
  23. package/dist/{iam-role-provider-D83igvxU.js.map → iam-role-provider-gS0g_h2H.js.map} +1 -1
  24. package/dist/{image-plan-CX0jARAo.js → image-plan-hSzmMXmK.js} +8 -8
  25. package/dist/{image-plan-CX0jARAo.js.map → image-plan-hSzmMXmK.js.map} +1 -1
  26. package/dist/index.d.ts +1 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +5 -5
  29. package/dist/{logger-BOyzi_bp.js → logger-ZjhMP0A2.js} +2 -2
  30. package/dist/{logger-BOyzi_bp.js.map → logger-ZjhMP0A2.js.map} +1 -1
  31. package/dist/{neptune-provider-LICtrjZA.js → neptune-provider-D3O8Y0lx.js} +7 -7
  32. package/dist/{neptune-provider-LICtrjZA.js.map → neptune-provider-D3O8Y0lx.js.map} +1 -1
  33. package/dist/{program-CNXtBZfo.js → program-MndcrrWf.js} +476 -47
  34. package/dist/program-MndcrrWf.js.map +1 -0
  35. package/dist/{provider-classes-DTrcboTq.js → provider-classes-KrOpD8Sp.js} +846 -748
  36. package/dist/provider-classes-KrOpD8Sp.js.map +1 -0
  37. package/dist/{rds-provider-CBmrdoyi.js → rds-provider-Q_PZr6mn.js} +10 -10
  38. package/dist/{rds-provider-CBmrdoyi.js.map → rds-provider-Q_PZr6mn.js.map} +1 -1
  39. package/dist/{read-replica-BCcgBJRn.js → read-replica-DyQpEv77.js} +3 -3
  40. package/dist/{read-replica-BCcgBJRn.js.map → read-replica-DyQpEv77.js.map} +1 -1
  41. package/dist/{replacement-rules-BfJK4-AO.js → replacement-rules-BdvFwhmu.js} +3 -3
  42. package/dist/{replacement-rules-BfJK4-AO.js.map → replacement-rules-BdvFwhmu.js.map} +1 -1
  43. package/dist/{resource-deadline-C8ZUmToQ.js → resource-deadline-CKaftDB_.js} +8 -5
  44. package/dist/{resource-deadline-C8ZUmToQ.js.map → resource-deadline-CKaftDB_.js.map} +1 -1
  45. package/dist/{restore-source-guard-VsAsPwf6.js → restore-source-guard-eOILAZqS.js} +4 -4
  46. package/dist/{restore-source-guard-VsAsPwf6.js.map → restore-source-guard-eOILAZqS.js.map} +1 -1
  47. package/dist/{run-cli-Cauimq5Y.js → run-cli-PZtAEtYO.js} +2 -2
  48. package/dist/{run-cli-Cauimq5Y.js.map → run-cli-PZtAEtYO.js.map} +1 -1
  49. package/dist/{version-DWD1DsuN.js → version-DiwszmmI.js} +2 -2
  50. package/dist/{version-DWD1DsuN.js.map → version-DiwszmmI.js.map} +1 -1
  51. package/package.json +1 -1
  52. package/dist/ambient-client-defaults-ov4YgebP.js.map +0 -1
  53. package/dist/deploy-engine-C7WHVVa_.js.map +0 -1
  54. package/dist/program-CNXtBZfo.js.map +0 -1
  55. package/dist/provider-classes-DTrcboTq.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-D83igvxU.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-BOyzi_bp.js";
1
+ import { a as IamCreateClientCache, i as isEntityAlreadyExists, n as collectInlinePolicyNamesManagedBySiblings, r as iamEntityLeftByThisCreate, t as IAMRoleProvider } from "./iam-role-provider-gS0g_h2H.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-ZjhMP0A2.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-ov4YgebP.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-C8ZUmToQ.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-DWD1DsuN.js";
7
- import { gt as slowCcOperationTimeoutMs, n as isRefusedByName, r as markDeleteStarted } from "./delete-started-D6-EOWNl.js";
8
- import { a as resolveSecretDerivedPrincipals, i as isResolvableSecretPrincipalList, n as runDestroyForStack, r as holdsUnprovenSecretPrincipalToken, t as canonicalizeIpv4Cidr } from "./program-CNXtBZfo.js";
9
- import { $ as planVectorIndexUpdates, At as hasCdkAutoDeleteTag, B as declaredStreamTagsMember, Ba as waitForGoneAfterDelete, Cc as refuseMalformedNestedChildOutputs, Cl as listNestedTemplateRows, Ct as TABLE_INDEX_NOUN, Do as s3BucketDualStackDomainName, Dt as waitForIndexesSettled, Eo as s3BucketDomainName, Et as relayedIndexBusyDelete, Fr as redactedDeleteAddressFields, G as streamMemberRefusals, Ga as deleteSkipReason, Gt as isAccessDeniedError, H as reverseMapStreamPolicy, I as DynamoDBGlobalTableProvider, Ir as redactedDeleteAddressSkip, J as isTtlAlreadyDisabled, K as streamPolicyMatchesDeclared, Ka as withIndeterminateGuard, Kt as lookupEachName, L as STREAM_POLICY_KEY, Nc as refuseMalformedResourcesForDestroy, Nr as REDACTED_DELETE_ADDRESS_SKIP_REASON, Oa as getCurrentResourceSecrets, Oo as s3BucketRegionalDomainName, Os as passedParameterClassesOf, Ot as ECR_AUTO_DELETE_IMAGES_TAG, Pr as isRedactedRecordedValue, Q as sendTtlWaitingOutRateLimit, Qn as canonicalizeIpProtocolValue, R as STREAM_TAGS_KEY, Ra as waitForLambdaFunctionActive, Rc as accountArgs, Sl as isAbsoluteAssetPath, St as INDEX_SETTLE_POLL_INTERVAL_MS, To as s3BucketArn, Tt as maskedLogger, U as streamDeclaresPolicy, Ul as rewriteTemplateAssetReferences, Uo as outputReferenceProvenanceOf, V as planStreamMemberOps, W as streamDeclaresTags, Wt as chunks, X as planTimeToLive, Xc as withoutSdkUnwiredProperties, Xn as cfnIngressPortValue, Y as isTtlRateLimited, Ya as markWaitAbandoned, Yi as secretNamedAttributeNamesOf, Yn as withoutSiblingOwnedSgRules, Yo as getAccountInfo, Z as readTtlSpec, Zn as sgProtocolKey, _i as awaitInFlightSibling, _s as isWarmThroughputDecrease, _t as compensateRemovedDeletionProtection, _u as describeFileReadFailure, at as contributorInsightsRefusals, bt as resolveDynamoDbDeleteBudgetMs, bu as renderAssemblyPathEscape, cn as withNestedStackContext, ct as planIndexContributorInsightsOps, da as collectManagedPolicyArnsAttachedBySiblings, dt as reverseMapTableContributorInsights, en as getNestedRevertRun, et as readbackVectorIndexes, fa as collectPrincipalsAttachingPolicy, ft as stripIndexContributorInsights, gr as reserveStackCreateToken, gs as coerceWarmThroughput$1, gt as beginDeleteWait, ha as withoutSiblingOwned, hs as WARM_THROUGHPUT_MEMBERS, ht as DYNAMODB_DELETE_POLL_COST_MS, it as CONTRIBUTOR_INSIGHTS_KEY, jl as decodeListingKey, jt as isTruthyCfnBoolean, ko as s3BucketWebsiteUrl, kt as S3_AUTO_DELETE_OBJECTS_TAG, lt as readContributorInsightsSpec, ma as withoutSiblingAttachedArns, mr as earliestDefined, mt as DYNAMODB_DELETE_MIN_RESOURCE_TIMEOUT_MS, no as APPSYNC_APIKEY_ARN_RESOURCE_PATH, nt as vectorIndexesSettled, ot as indexDeclaresContributorInsights, pt as DYNAMODB_DELETE_DEADLINE_MARGIN_MS, q as streamTagsMatchDeclared, qc as findSdkUnwiredProperties, qn as siblingOwnedSgRuleIdentities, qr as getCurrentProducerRegions, qt as withApiLimit, rn as revertNestedChildFromJournal, ro as maskedSecretSegment, rt as vectorIndexesShapeDetail, sn as getCurrentNestedStackContext, st as planContributorInsightsOp, t as DeployEngine, to as isSettledInstanceState, tt as vectorIndexesForCreate, ua as collectGroupsAddedBySiblings, ut as reverseMapIndexContributorInsights, vr as acquireIdempotencyToken, vs as toCfnInteger, vt as deleteBudgetKey, vu as displayAssemblyPath, wl as renderNestedTemplateTreeDefect, wt as deleteTableWithIndexBusyRetry, xi as replacedDeleteFailureVerdict, xl as findNestedTemplateTreeDefect, xt as DELETE_INDEX_WAIT_PROCEED_NOTE, xu as resolveAssemblyPath, yi as getStackRecords, yl as stringifyValue, ys as toFiniteNumber, yt as resolveDynamoDbDeleteBudgetClock, z as declaredStreamPolicyMember, zc as withheldAccountClause, zo as parseWebACLArn } from "./deploy-engine-C7WHVVa_.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-VsAsPwf6.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-BftAVRVj.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-CcCQuSZx.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-CKaftDB_.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-DiwszmmI.js";
7
+ import { gt as slowCcOperationTimeoutMs, n as isRefusedByName, r as markDeleteStarted } from "./delete-started-joCwegKq.js";
8
+ import { _ as warnUnsettledMember, a as resolveSecretDerivedPrincipals, b as verbatimEchoDriftKeys, 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-MndcrrWf.js";
9
+ import { $ as sendTtlWaitingOutRateLimit, $a as markWaitAbandoned, $i as secretNamedAttributeNamesOf, $n as sgProtocolKey, $o as getAccountInfo, Ao as s3BucketDomainName, At as S3_AUTO_DELETE_OBJECTS_TAG, B as declaredStreamTagsMember, Br as redactedDeleteAddressSkip, Ci as getStackRecords, Cl as stringifyValue, Cs as toFiniteNumber, Ct as INDEX_SETTLE_POLL_INTERVAL_MS, Dc as refuseMalformedNestedChildOutputs, Dl as listNestedTemplateRows, Dt as relayedIndexBusyDelete, El as isAbsoluteAssetPath, Et as maskedLogger, Fl as decodeListingKey, G as streamDeclaresTags, Gt as chunks, Ha as waitForLambdaFunctionActive, Hc as accountArgs, I as DynamoDBGlobalTableProvider, J as streamTagsMatchDeclared, Jt as withApiLimit, K as streamMemberRefusals, Kt as isAccessDeniedError, L as STREAM_POLICY_KEY, Lc as refuseMalformedResourcesForDestroy, Lr as REDACTED_DELETE_ADDRESS_SKIP_REASON, Ma as getCurrentResourceSecrets, Mo as s3BucketRegionalDomainName, Ms as passedParameterClassesOf, Mt as isTruthyCfnBoolean, No as s3BucketWebsiteUrl, Ol as renderNestedTemplateTreeDefect, Ot as waitForIndexesSettled, Q as readTtlSpec, Qn as cfnIngressPortValue, R as STREAM_TAGS_KEY, Rr as isRedactedRecordedValue, Ss as toCfnInteger, St as DELETE_INDEX_WAIT_PROCEED_NOTE, Su as displayAssemblyPath, Ti as replacedDeleteFailureVerdict, Tl as findNestedTemplateTreeDefect, Tt as deleteTableWithIndexBusyRetry, Tu as resolveAssemblyPath, U as reverseMapStreamPolicy, Uc as withheldAccountClause, Uo as parseWebACLArn, V as planStreamMemberOps, W as streamDeclaresPolicy, Wa as waitForGoneAfterDelete, X as isTtlRateLimited, Xa as withIndeterminateGuard, Xn as siblingOwnedSgRuleIdentities, Y as isTtlAlreadyDisabled, Ya as deleteSkipReason, Z as planTimeToLive, Zc as findSdkUnwiredProperties, Zn as withoutSiblingOwnedSgRules, Zr as getCurrentProducerRegions, _a as isStoredExpression, _t as beginDeleteWait, ao as isSettledInstanceState, at as CONTRIBUTOR_INSIGHTS_KEY, br as acquireIdempotencyToken, bs as coerceWarmThroughput$1, bt as resolveDynamoDbDeleteBudgetClock, cn as getCurrentNestedStackContext, cr as calculateResourceDrift, ct as planContributorInsightsOp, dt as reverseMapIndexContributorInsights, el as withoutSdkUnwiredProperties, er as canonicalizeIpProtocolValue, et as planVectorIndexUpdates, ft as reverseMapTableContributorInsights, ga as collectPrincipalsAttachingPolicy, gr as earliestDefined, gt as DYNAMODB_DELETE_POLL_COST_MS, ha as collectManagedPolicyArnsAttachedBySiblings, ht as DYNAMODB_DELETE_MIN_RESOURCE_TIMEOUT_MS, in as revertNestedChildFromJournal, it as vectorIndexesShapeDetail, jo as s3BucketDualStackDomainName, jt as hasCdkAutoDeleteTag, ko as s3BucketArn, kt as ECR_AUTO_DELETE_IMAGES_TAG, ln as withNestedStackContext, lt as planIndexContributorInsightsOps, ma as collectGroupsAddedBySiblings, mt as DYNAMODB_DELETE_DEADLINE_MARGIN_MS, nt as vectorIndexesForCreate, oo as APPSYNC_APIKEY_ARN_RESOURCE_PATH, ot as contributorInsightsRefusals, pt as stripIndexContributorInsights, q as streamPolicyMatchesDeclared, ql as rewriteTemplateAssetReferences, qo as outputReferenceProvenanceOf, qt as lookupEachName, rt as vectorIndexesSettled, so as maskedSecretSegment, st as indexDeclaresContributorInsights, t as DeployEngine, tn as getNestedRevertRun, tt as readbackVectorIndexes, ut as readContributorInsightsSpec, va as withoutSiblingAttachedArns, vr as reserveStackCreateToken, vt as compensateRemovedDeletionProtection, wt as TABLE_INDEX_NOUN, wu as renderAssemblyPathEscape, xi as awaitInFlightSibling, xs as isWarmThroughputDecrease, xt as resolveDynamoDbDeleteBudgetMs, xu as describeFileReadFailure, ya as withoutSiblingOwned, ys as WARM_THROUGHPUT_MEMBERS, yt as deleteBudgetKey, z as declaredStreamPolicyMember, zr as redactedDeleteAddressFields } from "./deploy-engine-CilA7v8d.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-eOILAZqS.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-Gdl3Djvt.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-CfIvxdWW.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-BfJK4-AO.js";
16
- import { RDSProvider } from "./rds-provider-CBmrdoyi.js";
17
- import { NeptuneProvider } from "./neptune-provider-LICtrjZA.js";
18
- import { ASGProvider } from "./asg-provider-B3SM2Pb6.js";
14
+ import { n as planSubscriptionAttributes } from "./diff-calculator-Bjr0sh-h.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-BdvFwhmu.js";
16
+ import { RDSProvider } from "./rds-provider-Q_PZr6mn.js";
17
+ import { NeptuneProvider } from "./neptune-provider-D3O8Y0lx.js";
18
+ import { ASGProvider } from "./asg-provider-BYsZoqmF.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";
@@ -527,48 +527,108 @@ async function deleteImpl$40(logicalId, physicalId, resourceType, properties, co
527
527
  }
528
528
 
529
529
  // src/provisioning/providers/iam-policy/read-state.ts
530
- async function readCurrentState$40(physicalId, _logicalId, _resourceType, properties) {
530
+ const TARGET_READ_CONCURRENCY = 5;
531
+ async function readCurrentState$40(physicalId, _logicalId, _resourceType, properties, context) {
531
532
  if (!properties) return void 0;
532
- if (!properties["PolicyDocument"]) return void 0;
533
+ const policyDocument = properties["PolicyDocument"];
534
+ if (!policyDocument) return void 0;
533
535
  const policyName = physicalId.includes(":") ? physicalId.split(":")[0] : physicalId;
534
536
  const targets = readPolicyTargetLists(properties);
535
537
  if ("malformed" in targets) return void 0;
536
538
  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;
539
+ const allTargets = [
540
+ ...(roles ?? []).map((name) => ({
541
+ kind: "role",
542
+ name
543
+ })),
544
+ ...(groups ?? []).map((name) => ({
545
+ kind: "group",
546
+ name
547
+ })),
548
+ ...(users ?? []).map((name) => ({
549
+ kind: "user",
550
+ name
551
+ }))
552
+ ];
553
+ if (allTargets.length === 0) return void 0;
554
+ const readTargets = context?.afterOwnWrite === true ? allTargets.slice(0, 1) : allTargets;
555
+ const readOne = async (target) => {
556
+ try {
557
+ const raw = await getTargetPolicyDocument.call(this, target, policyName);
558
+ return {
559
+ target,
560
+ document: this.decodePolicyDocument(raw)
561
+ };
562
+ } catch (err) {
563
+ if (err instanceof NoSuchEntityException) return {
564
+ target,
565
+ missing: true
566
+ };
567
+ throw err;
568
+ }
569
+ };
570
+ const reads = [];
571
+ 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)));
572
+ const documents = reads.flatMap((r) => "document" in r ? [r.document] : []);
573
+ if (documents.length === 0) return RESOURCE_NOT_FOUND;
574
+ if (!reads.some((r) => "missing" in r) && documents.every((d) => d === void 0)) return void 0;
575
+ const union = context?.driftBaseline !== void 0;
576
+ const unionWalkPaths = verbatimEchoDriftKeys("AWS::IAM::Policy");
577
+ const comparatorEqual = (a, b) => calculateResourceDrift({ PolicyDocument: a }, { PolicyDocument: b }, {
578
+ unionWalkObjects: union,
579
+ unionWalkPaths
580
+ }).length === 0;
581
+ const baseline = context?.driftBaseline?.["PolicyDocument"] !== void 0 ? context.driftBaseline["PolicyDocument"] : parseRecordedDocument(policyDocument);
582
+ let liveDocument = documents[0];
583
+ if (documents.some((d) => !comparatorEqual(liveDocument, d) || !comparatorEqual(d, liveDocument))) {
584
+ 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`);
585
+ const edited = documents.findIndex((d) => !comparatorEqual(baseline, d));
586
+ if (edited !== -1) liveDocument = documents[edited];
561
587
  }
562
- if (liveDocument === void 0) return void 0;
563
588
  const result = {
564
589
  PolicyName: policyName,
565
590
  PolicyDocument: liveDocument
566
591
  };
567
- if (roles) result["Roles"] = roles;
568
- if (groups) result["Groups"] = groups;
569
- if (users) result["Users"] = users;
592
+ const echo = (kind, names) => {
593
+ const missing = new Set(reads.flatMap((r) => "missing" in r && r.target.kind === kind ? [r.target.name] : []));
594
+ return names.filter((name) => !missing.has(name));
595
+ };
596
+ if (roles) result["Roles"] = echo("role", roles);
597
+ if (groups) result["Groups"] = echo("group", groups);
598
+ if (users) result["Users"] = echo("user", users);
570
599
  return result;
571
600
  }
601
+ async function getTargetPolicyDocument(target, policyName) {
602
+ switch (target.kind) {
603
+ case "role": return (await this.iamClient.send(new GetRolePolicyCommand({
604
+ RoleName: target.name,
605
+ PolicyName: policyName
606
+ }))).PolicyDocument;
607
+ case "group": return (await this.iamClient.send(new GetGroupPolicyCommand({
608
+ GroupName: target.name,
609
+ PolicyName: policyName
610
+ }))).PolicyDocument;
611
+ case "user": return (await this.iamClient.send(new GetUserPolicyCommand({
612
+ UserName: target.name,
613
+ PolicyName: policyName
614
+ }))).PolicyDocument;
615
+ }
616
+ }
617
+ function holdsSecretLeaf(value, depth = 0) {
618
+ if (depth > 64) return true;
619
+ if (typeof value === "string") return isStoredExpression(value);
620
+ if (Array.isArray(value)) return value.some((v) => holdsSecretLeaf(v, depth + 1));
621
+ if (typeof value === "object" && value !== null) return Object.entries(value).some(([k, v]) => holdsSecretLeaf(k, depth + 1) || holdsSecretLeaf(v, depth + 1));
622
+ return false;
623
+ }
624
+ function parseRecordedDocument(recorded) {
625
+ if (typeof recorded !== "string") return recorded;
626
+ try {
627
+ return JSON.parse(recorded);
628
+ } catch {
629
+ return recorded;
630
+ }
631
+ }
572
632
  function decodePolicyDocument(raw) {
573
633
  if (!raw) return void 0;
574
634
  try {
@@ -619,8 +679,8 @@ var IAMPolicyProvider = class {
619
679
  delete(logicalId, physicalId, resourceType, properties, context) {
620
680
  return deleteImpl$40.call(this, logicalId, physicalId, resourceType, properties, context);
621
681
  }
622
- readCurrentState(physicalId, logicalId, resourceType, properties) {
623
- return readCurrentState$40.call(this, physicalId, logicalId, resourceType, properties);
682
+ readCurrentState(physicalId, logicalId, resourceType, properties, context) {
683
+ return readCurrentState$40.call(this, physicalId, logicalId, resourceType, properties, context);
624
684
  }
625
685
  decodePolicyDocument(raw) {
626
686
  return decodePolicyDocument.call(this, raw);
@@ -6873,137 +6933,6 @@ function serializeResourcePolicy(document, resourceType, logicalId) {
6873
6933
  return typeof sent === "string" ? sent : JSON.stringify(sent);
6874
6934
  }
6875
6935
 
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));
6991
- }
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);
7005
- }
7006
-
7007
6936
  // src/provisioning/providers/s3-bucket-policy-provider.ts
7008
6937
  const OAI_USER_ARN_RE = /^arn:aws[a-z-]*:iam::cloudfront:user\/CloudFront Origin Access Identity ([A-Z0-9]+)$/;
7009
6938
  const IAM_UNIQUE_ID_RE = /^AIDA[A-Z0-9]{12,}$/;
@@ -7664,6 +7593,7 @@ const QUEUE_POLICY_NOT_COMPARED_LEFT_REASON = "the document it attempted is miss
7664
7593
  var SQSQueuePolicyProvider = class {
7665
7594
  sqsClient;
7666
7595
  logger = getLogger().child("SQSQueuePolicyProvider");
7596
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
7667
7597
  handledProperties = /* @__PURE__ */ new Map([["AWS::SQS::QueuePolicy", /* @__PURE__ */ new Set(["Queues", "PolicyDocument"])]]);
7668
7598
  constructor() {
7669
7599
  const awsClients = getAwsClients();
@@ -7859,7 +7789,20 @@ var SQSQueuePolicyProvider = class {
7859
7789
  };
7860
7790
  }
7861
7791
  }
7862
- async readCurrentState(physicalId, _logicalId, _resourceType) {
7792
+ async readCurrentState(physicalId, _logicalId, _resourceType, properties, context) {
7793
+ const declared = context?.afterOwnWrite === true ? declaredPolicyDocument(properties) : void 0;
7794
+ if (declared === void 0) return this.readQueuePolicy(physicalId);
7795
+ const queueCount = splitQueueUrls(physicalId).length;
7796
+ let policies = [];
7797
+ const { answer, settled } = await reReadUntilSettled(() => {
7798
+ policies = [];
7799
+ return this.readQueuePolicy(physicalId, policies);
7800
+ }, (read) => read !== void 0 && read !== RESOURCE_NOT_FOUND && policies.length === queueCount && policies.every((policy) => policyDocumentMatchesDeclared(policy, declared)), this.ownWriteRereadDelaysMs);
7801
+ if (settled) return answer;
7802
+ if (answer !== void 0 && answer !== RESOURCE_NOT_FOUND && answer["Queues"].length === queueCount) return answer;
7803
+ this.logger.debug(safeMsg`No drift baseline captured for queue policy ${physicalId}: a queue still read back no policy after the write`);
7804
+ }
7805
+ async readQueuePolicy(physicalId, policies) {
7863
7806
  const queueUrls = splitQueueUrls(physicalId);
7864
7807
  if (queueUrls.length === 0) return void 0;
7865
7808
  const held = [];
@@ -7878,6 +7821,7 @@ var SQSQueuePolicyProvider = class {
7878
7821
  }
7879
7822
  if (!policyAttr) continue;
7880
7823
  held.push(queueUrl);
7824
+ policies?.push(policyAttr);
7881
7825
  firstPolicy ??= policyAttr;
7882
7826
  }
7883
7827
  if (firstPolicy === void 0) return RESOURCE_NOT_FOUND;
@@ -8797,12 +8741,16 @@ function isPendingConfirmationError(error) {
8797
8741
  }
8798
8742
 
8799
8743
  // src/provisioning/providers/sns-topic-policy-provider.ts
8744
+ function isSnsDefaultPolicy(document) {
8745
+ return typeof document === "object" && document !== null && document["Id"] === "__default_policy_ID";
8746
+ }
8800
8747
  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
8748
  const TOPIC_POLICY_UNRESOLVED_DOCUMENT_SKIP_REASON = "the policy document it attempted could not be resolved right now to compare its topics with";
8802
8749
  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
8750
  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
8751
  var SNSTopicPolicyProvider = class {
8805
8752
  logger = getLogger().child("SNSTopicPolicyProvider");
8753
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
8806
8754
  handledProperties = /* @__PURE__ */ new Map([["AWS::SNS::TopicPolicy", /* @__PURE__ */ new Set(["Topics", "PolicyDocument"])]]);
8807
8755
  async create(logicalId, resourceType, properties, context) {
8808
8756
  this.logger.debug(`Creating SNS topic policy ${logicalId}`);
@@ -9006,7 +8954,16 @@ var SNSTopicPolicyProvider = class {
9006
8954
  };
9007
8955
  }
9008
8956
  }
9009
- async readCurrentState(physicalId, _logicalId, _resourceType) {
8957
+ async readCurrentState(physicalId, _logicalId, _resourceType, properties, context) {
8958
+ const declared = context?.afterOwnWrite === true ? declaredPolicyDocument(properties) : void 0;
8959
+ if (declared === void 0) return this.readTopicPolicy(physicalId);
8960
+ const { answer, settled } = await reReadUntilSettled(() => this.readTopicPolicy(physicalId), (read) => read !== void 0 && read !== RESOURCE_NOT_FOUND && policyDocumentMatchesDeclared(read["PolicyDocument"], declared), this.ownWriteRereadDelaysMs);
8961
+ if (settled) return answer;
8962
+ const read = answer === void 0 || answer === RESOURCE_NOT_FOUND ? void 0 : answer["PolicyDocument"];
8963
+ if (read !== void 0 && !isSnsDefaultPolicy(read)) return answer;
8964
+ this.logger.debug(safeMsg`No drift baseline captured for topic policy ${physicalId}: its topic still read back its default policy after the write`);
8965
+ }
8966
+ async readTopicPolicy(physicalId) {
9010
8967
  const topics = physicalId.split(",").filter((t) => t.length > 0);
9011
8968
  if (topics.length === 0) return void 0;
9012
8969
  const firstTopic = topics[0];
@@ -9603,6 +9560,21 @@ async function update$37(logicalId, physicalId, resourceType, properties, previo
9603
9560
  const liveManaged = desiredCapacity !== void 0 || recordedCapacity !== void 0 ? (await this.lambdaClient.send(new GetFunctionCommand({ FunctionName: physicalId }))).Configuration?.CapacityProviderConfig !== void 0 : false;
9604
9561
  if (liveManaged && desiredCapacity === void 0) throw markNonRetryable(new ProvisioningError(`Lambda function ${logicalId} cannot lose its CapacityProviderConfig: AWS does not support removing it from a function. Keep the property, or replace the function under a new logical id.`, resourceType, logicalId, physicalId));
9605
9562
  const capacityNeverApplied = !liveManaged && desiredCapacity !== void 0 && recordedCapacity !== void 0;
9563
+ let waitedForActive = false;
9564
+ const sendOnceActive = async (send) => {
9565
+ try {
9566
+ return await send();
9567
+ } catch (error) {
9568
+ if (waitedForActive || liveManaged || !isLambdaPendingRefusal(error)) throw error;
9569
+ waitedForActive = true;
9570
+ const budgetMs = Math.min(this.functionUpdateMaxWaitSeconds * 1e3, enclosingDeadlineRemainingMs() - this.latestPublishedDeadlineMarginMs);
9571
+ if (budgetMs < 1e3) throw error;
9572
+ log.debug(`Lambda function ${log.value(physicalId)} is still Pending; waiting for it to be Active`);
9573
+ await this.waitForFunctionActive(logicalId, resourceType, physicalId, log, Math.floor(budgetMs / 1e3));
9574
+ if (enclosingDeadlineExpired()) throw error;
9575
+ return await send();
9576
+ }
9577
+ };
9606
9578
  if (capacityNeverApplied) log.warn(`Lambda function ${logicalId} is not a Managed Instances function on AWS, so its CapacityProviderConfig and FunctionScalingConfig are not applied. Replace the function to apply them.`);
9607
9579
  const configFields = [
9608
9580
  "Role",
@@ -9656,7 +9628,7 @@ async function update$37(logicalId, physicalId, resourceType, properties, previo
9656
9628
  RuntimeConfig: properties["RuntimeConfig"]
9657
9629
  };
9658
9630
  for (const field of changedConfigFields) markUnsettled(field);
9659
- await this.lambdaClient.send(new UpdateFunctionConfigurationCommand(configParams));
9631
+ await sendOnceActive(() => this.lambdaClient.send(new UpdateFunctionConfigurationCommand(configParams)));
9660
9632
  log.debug(`Updated configuration for Lambda function ${log.value(physicalId)}`);
9661
9633
  await this.waitForFunctionUpdated(logicalId, resourceType, physicalId, log);
9662
9634
  }
@@ -9664,7 +9636,7 @@ async function update$37(logicalId, physicalId, resourceType, properties, previo
9664
9636
  const codeSigningChanged = newCodeSigningConfigArn !== previousProperties["CodeSigningConfigArn"];
9665
9637
  if (codeSigningChanged && newCodeSigningConfigArn === void 0) {
9666
9638
  markUnsettled("CodeSigningConfigArn");
9667
- await this.lambdaClient.send(new DeleteFunctionCodeSigningConfigCommand({ FunctionName: physicalId }));
9639
+ await sendOnceActive(() => this.lambdaClient.send(new DeleteFunctionCodeSigningConfigCommand({ FunctionName: physicalId })));
9668
9640
  log.debug(`Detached CodeSigningConfigArn from Lambda function ${log.value(physicalId)} (template removed the property)`);
9669
9641
  }
9670
9642
  const newCode = properties["Code"];
@@ -9686,7 +9658,7 @@ async function update$37(logicalId, physicalId, resourceType, properties, previo
9686
9658
  };
9687
9659
  markUnsettled("Code");
9688
9660
  if (architecturesChanged) markUnsettled("Architectures");
9689
- await this.lambdaClient.send(new UpdateFunctionCodeCommand(codeParams));
9661
+ await sendOnceActive(() => this.lambdaClient.send(new UpdateFunctionCodeCommand(codeParams)));
9690
9662
  log.debug(`Updated code for Lambda function ${log.value(physicalId)}`);
9691
9663
  await this.waitForFunctionUpdated(logicalId, resourceType, physicalId, log);
9692
9664
  }
@@ -9694,39 +9666,39 @@ async function update$37(logicalId, physicalId, resourceType, properties, previo
9694
9666
  const prevRecursiveLoop = previousProperties["RecursiveLoop"];
9695
9667
  if (newRecursiveLoop !== void 0 && newRecursiveLoop !== prevRecursiveLoop) {
9696
9668
  markUnsettled("RecursiveLoop");
9697
- await this.lambdaClient.send(new PutFunctionRecursionConfigCommand({
9669
+ await sendOnceActive(() => this.lambdaClient.send(new PutFunctionRecursionConfigCommand({
9698
9670
  FunctionName: physicalId,
9699
9671
  RecursiveLoop: newRecursiveLoop
9700
- }));
9672
+ })));
9701
9673
  log.debug(`Updated RecursiveLoop for Lambda function ${log.value(physicalId)} to '${log.value(newRecursiveLoop)}'`);
9702
9674
  }
9703
9675
  const newReservedConcurrentExecutions = properties["ReservedConcurrentExecutions"];
9704
9676
  if (newReservedConcurrentExecutions !== previousProperties["ReservedConcurrentExecutions"]) {
9705
9677
  markUnsettled("ReservedConcurrentExecutions");
9706
9678
  if (newReservedConcurrentExecutions === void 0) {
9707
- await this.lambdaClient.send(new DeleteFunctionConcurrencyCommand({ FunctionName: physicalId }));
9679
+ await sendOnceActive(() => this.lambdaClient.send(new DeleteFunctionConcurrencyCommand({ FunctionName: physicalId })));
9708
9680
  log.debug(`Cleared ReservedConcurrentExecutions for Lambda function ${log.value(physicalId)} (template removed the property)`);
9709
9681
  } else {
9710
- await this.lambdaClient.send(new PutFunctionConcurrencyCommand({
9682
+ await sendOnceActive(() => this.lambdaClient.send(new PutFunctionConcurrencyCommand({
9711
9683
  FunctionName: physicalId,
9712
9684
  ReservedConcurrentExecutions: newReservedConcurrentExecutions
9713
- }));
9685
+ })));
9714
9686
  log.debug(`Updated ReservedConcurrentExecutions for Lambda function ${log.value(physicalId)} to ${log.value(newReservedConcurrentExecutions)}`);
9715
9687
  }
9716
9688
  }
9717
9689
  if (codeSigningChanged && newCodeSigningConfigArn !== void 0) {
9718
9690
  markUnsettled("CodeSigningConfigArn");
9719
- await this.lambdaClient.send(new PutFunctionCodeSigningConfigCommand({
9691
+ await sendOnceActive(() => this.lambdaClient.send(new PutFunctionCodeSigningConfigCommand({
9720
9692
  FunctionName: physicalId,
9721
9693
  CodeSigningConfigArn: newCodeSigningConfigArn
9722
- }));
9694
+ })));
9723
9695
  log.debug(`Updated CodeSigningConfigArn for Lambda function ${log.value(physicalId)} to ${log.value(newCodeSigningConfigArn)}`);
9724
9696
  }
9725
9697
  const newRuntimeManagementConfig = properties["RuntimeManagementConfig"];
9726
9698
  const prevRuntimeManagementConfig = previousProperties["RuntimeManagementConfig"];
9727
9699
  if (newRuntimeManagementConfig?.["UpdateRuntimeOn"] !== prevRuntimeManagementConfig?.["UpdateRuntimeOn"] || newRuntimeManagementConfig?.["RuntimeVersionArn"] !== prevRuntimeManagementConfig?.["RuntimeVersionArn"]) {
9728
9700
  markUnsettled("RuntimeManagementConfig");
9729
- await this.putRuntimeManagementConfig(physicalId, newRuntimeManagementConfig ?? { UpdateRuntimeOn: "Auto" });
9701
+ await sendOnceActive(() => this.putRuntimeManagementConfig(physicalId, newRuntimeManagementConfig ?? { UpdateRuntimeOn: "Auto" }));
9730
9702
  log.debug(`Updated RuntimeManagementConfig for Lambda function ${log.value(physicalId)} to ${JSON.stringify(maskDeep(newRuntimeManagementConfig ?? { UpdateRuntimeOn: "Auto" }, operationMask))}`);
9731
9703
  }
9732
9704
  if (liveManaged && desiredCapacity !== void 0) {
@@ -9758,7 +9730,8 @@ async function update$37(logicalId, physicalId, resourceType, properties, previo
9758
9730
  const functionArn = getResponse.Configuration?.FunctionArn;
9759
9731
  await this.applyTagDiff(functionArn, physicalId, resourceType, logicalId, previousProperties["Tags"], properties["Tags"], log, {
9760
9732
  forceUpsert: context?.unsettledProperties?.has("Tags") === true,
9761
- beforeWrite: () => markUnsettled("Tags")
9733
+ beforeWrite: () => markUnsettled("Tags"),
9734
+ send: sendOnceActive
9762
9735
  });
9763
9736
  return {
9764
9737
  physicalId,
@@ -9776,6 +9749,7 @@ async function applyTagDiff$19(functionArn, functionName, resourceType, logicalI
9776
9749
  beforeWrite: () => void 0
9777
9750
  }) {
9778
9751
  if (!functionArn) return;
9752
+ const send = unsettled.send ?? ((call) => call());
9779
9753
  const plan = planTagDiff(oldTagsRaw, newTagsRaw);
9780
9754
  const tagWarning = tagPlanWarning(plan, resourceType, logicalId);
9781
9755
  if (tagWarning !== void 0) log.warn(tagWarning);
@@ -9783,17 +9757,17 @@ async function applyTagDiff$19(functionArn, functionName, resourceType, logicalI
9783
9757
  const tagsToRemove = plan.remove;
9784
9758
  if (tagsToRemove.length > 0 || Object.keys(tagsToAdd).length > 0) unsettled.beforeWrite();
9785
9759
  if (tagsToRemove.length > 0) {
9786
- await this.lambdaClient.send(new UntagResourceCommand$1({
9760
+ await send(() => this.lambdaClient.send(new UntagResourceCommand$1({
9787
9761
  Resource: functionArn,
9788
9762
  TagKeys: tagsToRemove
9789
- }));
9763
+ })));
9790
9764
  log.debug(`Removed ${tagsToRemove.length} tag(s) from Lambda function ${log.value(functionName)}`);
9791
9765
  }
9792
9766
  if (Object.keys(tagsToAdd).length > 0) {
9793
- await this.lambdaClient.send(new TagResourceCommand$1({
9767
+ await send(() => this.lambdaClient.send(new TagResourceCommand$1({
9794
9768
  Resource: functionArn,
9795
9769
  Tags: tagsToAdd
9796
- }));
9770
+ })));
9797
9771
  log.debug(`Added/updated ${Object.keys(tagsToAdd).length} tag(s) on Lambda function ${log.value(functionName)}`);
9798
9772
  }
9799
9773
  }
@@ -9810,6 +9784,23 @@ async function waitForFunctionUpdated(logicalId, resourceType, functionName, log
9810
9784
  throw this.wrapMaskedError(log, error, (text) => new ProvisioningError(`Lambda function ${logicalId} update did not complete: ${text}`, resourceType, logicalId, functionName, cause ?? new Error(safeStringify(error))));
9811
9785
  }
9812
9786
  }
9787
+ const LAMBDA_PENDING_REFUSAL = /currently in the following state: '?Pending\b/;
9788
+ function isLambdaPendingRefusal(error) {
9789
+ return LAMBDA_PENDING_REFUSAL.test(describeAwsFailure(error).detail);
9790
+ }
9791
+ async function waitForFunctionActive(logicalId, resourceType, functionName, log, maxWaitSeconds) {
9792
+ try {
9793
+ await waitUntilFunctionActiveV2({
9794
+ client: this.lambdaClient,
9795
+ maxWaitTime: maxWaitSeconds,
9796
+ minDelay: 1,
9797
+ maxDelay: 5
9798
+ }, { FunctionName: functionName });
9799
+ } catch (error) {
9800
+ const cause = error instanceof Error ? error : void 0;
9801
+ throw this.wrapMaskedError(log, error, (text) => new ProvisioningError(`Lambda function ${logicalId} did not become Active: ${text}`, resourceType, logicalId, functionName, cause ?? new Error(safeStringify(error))));
9802
+ }
9803
+ }
9813
9804
  async function waitForLambdaUpdateCompleted(functionName) {
9814
9805
  const start = Date.now();
9815
9806
  let delay = this.eniWaitInitialDelayMs;
@@ -10434,6 +10425,9 @@ var LambdaFunctionProvider = class {
10434
10425
  waitForFunctionUpdated(logicalId, resourceType, functionName, log) {
10435
10426
  return waitForFunctionUpdated.call(this, logicalId, resourceType, functionName, log);
10436
10427
  }
10428
+ waitForFunctionActive(logicalId, resourceType, functionName, log, maxWaitSeconds) {
10429
+ return waitForFunctionActive.call(this, logicalId, resourceType, functionName, log, maxWaitSeconds);
10430
+ }
10437
10431
  waitForLambdaUpdateCompleted(functionName) {
10438
10432
  return waitForLambdaUpdateCompleted.call(this, functionName);
10439
10433
  }
@@ -10512,6 +10506,7 @@ var LambdaPermissionProvider = class {
10512
10506
  lambdaClient;
10513
10507
  createClient = new LambdaCreateClientCache(() => this.lambdaClient);
10514
10508
  logger = getLogger().child("LambdaPermissionProvider");
10509
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
10515
10510
  handledProperties = /* @__PURE__ */ new Map([["AWS::Lambda::Permission", /* @__PURE__ */ new Set([
10516
10511
  "FunctionName",
10517
10512
  "Action",
@@ -10664,7 +10659,13 @@ var LambdaPermissionProvider = class {
10664
10659
  throw error instanceof Error && error.name.includes("NotFound") ? markNotGone(thrown) : thrown;
10665
10660
  }
10666
10661
  }
10667
- async readCurrentState(physicalId, _logicalId, _resourceType, properties) {
10662
+ async readCurrentState(physicalId, _logicalId, _resourceType, properties, context) {
10663
+ if (context?.afterOwnWrite !== true || typeof properties?.["FunctionName"] !== "string") return this.readPermission(physicalId, properties);
10664
+ const { answer, settled } = await reReadUntilSettled(() => this.readPermission(physicalId, properties), (read) => read !== void 0 && read !== RESOURCE_NOT_FOUND && lambdaPermissionMatchesDeclared(read, properties), this.ownWriteRereadDelaysMs);
10665
+ if (settled || answer !== void 0 && answer !== RESOURCE_NOT_FOUND) return answer;
10666
+ this.logger.debug(safeMsg`No drift baseline captured for permission ${physicalId}: its function policy still read back no such statement after the write`);
10667
+ }
10668
+ async readPermission(physicalId, properties) {
10668
10669
  const functionName = properties?.["FunctionName"];
10669
10670
  if (!functionName) return void 0;
10670
10671
  const statementId = physicalId.includes("|") ? physicalId.split("|").pop() : physicalId;
@@ -14986,7 +14987,10 @@ async function readCurrentState$33(physicalId, _logicalId, _resourceType, proper
14986
14987
  tableArn ? this.readTableTags(tableArn) : Promise.resolve(void 0),
14987
14988
  this.readPointInTimeRecovery(physicalId),
14988
14989
  this.readTimeToLive(physicalId),
14989
- tableArn ? this.readTableResourcePolicy(physicalId, tableArn) : Promise.resolve(void 0),
14990
+ tableArn ? this.readTableResourcePolicy(physicalId, tableArn, false, properties !== void 0 && bagInformative ? {
14991
+ desired: properties,
14992
+ afterOwnWrite: context?.afterOwnWrite === true
14993
+ } : void 0) : Promise.resolve(void 0),
14990
14994
  this.readKinesisStreamSpecification(physicalId),
14991
14995
  this.readTableContributorInsights(physicalId),
14992
14996
  this.readIndexContributorInsights(physicalId, result, properties, bagInformative),
@@ -15042,16 +15046,36 @@ async function readTimeToLive(physicalId, strict = false) {
15042
15046
  return;
15043
15047
  }
15044
15048
  }
15045
- async function readTableResourcePolicy(physicalId, tableArn, strict = false) {
15049
+ async function readTableResourcePolicy(physicalId, tableArn, strict = false, settle) {
15050
+ const declared = settle !== void 0 && streamDeclaresPolicy(settle.desired);
15051
+ const afterOwnWrite = settle?.afterOwnWrite === true;
15052
+ let lastPolicy;
15046
15053
  try {
15047
- const rpResp = await this.dynamoDBClient.send(new GetResourcePolicyCommand({ ResourceArn: tableArn }));
15048
- if (!rpResp.Policy) return void 0;
15049
- let doc = rpResp.Policy;
15054
+ const readOnce = async () => {
15055
+ try {
15056
+ lastPolicy = (await this.dynamoDBClient.send(new GetResourcePolicyCommand({ ResourceArn: tableArn }))).Policy;
15057
+ } catch (err) {
15058
+ if (settle === void 0 || !(err instanceof PolicyNotFoundException)) throw err;
15059
+ lastPolicy = void 0;
15060
+ }
15061
+ return lastPolicy;
15062
+ };
15063
+ const livePolicy = settle === void 0 || !declared && !afterOwnWrite ? await readOnce() : await this.reAskUntilSettled(readOnce, (answer) => declared ? streamPolicyMatchesDeclared(answer, settle.desired) : answer === void 0 || answer === "");
15064
+ const keepDeclared = afterOwnWrite && declared;
15065
+ if (!livePolicy) return keepDeclared ? declaredStreamPolicyMember(settle?.desired) : void 0;
15066
+ if (settle !== void 0) return keepDeclared && !streamPolicyMatchesDeclared(livePolicy, settle.desired) ? declaredStreamPolicyMember(settle.desired) : reverseMapStreamPolicy(livePolicy, settle.desired);
15067
+ let doc = livePolicy;
15050
15068
  try {
15051
- doc = JSON.parse(rpResp.Policy);
15069
+ doc = JSON.parse(livePolicy);
15052
15070
  } catch {}
15053
15071
  return { PolicyDocument: doc };
15054
15072
  } catch (err) {
15073
+ const answered = lastPolicy !== void 0 && lastPolicy !== "";
15074
+ if (declared && afterOwnWrite && (answered || isTransientStreamReadFailure(err))) {
15075
+ this.logger.debug(safeMsg`Kept the declared ResourcePolicy of ${physicalId} in the baseline captured after its write: the read failed before it settled`);
15076
+ return declaredStreamPolicyMember(settle?.desired);
15077
+ }
15078
+ if (declared && answered) return reverseMapStreamPolicy(lastPolicy, settle?.desired);
15055
15079
  if (strict && !(err instanceof ResourceNotFoundException$1) && !(err instanceof PolicyNotFoundException)) throw err;
15056
15080
  if (!(err instanceof ResourceNotFoundException$1)) this.logger.debug(`Could not read ResourcePolicy for ${physicalId}: ${describeAwsFailure(err).detail}`);
15057
15081
  return;
@@ -15131,16 +15155,15 @@ async function readStreamMembers(tableName, streamArn, desiredBlock, streamBlock
15131
15155
  return lastPolicy;
15132
15156
  }, (answer) => streamPolicyMatchesDeclared(answer, desiredBlock));
15133
15157
  if (afterOwnWrite && (livePolicy === void 0 || livePolicy === "")) keepDeclared(STREAM_POLICY_KEY, "the read still found no policy");
15158
+ else if (afterOwnWrite && !streamPolicyMatchesDeclared(livePolicy, desiredBlock)) keepDeclared(STREAM_POLICY_KEY, "the read still found another policy");
15134
15159
  else {
15135
15160
  const member = reverseMapStreamPolicy(livePolicy, desiredBlock);
15136
15161
  if (member !== void 0) streamBlock[STREAM_POLICY_KEY] = member;
15137
15162
  }
15138
15163
  } catch (err) {
15139
15164
  this.logger.debug(`Could not read the stream ResourcePolicy for ${tableName}: ${describeAwsFailure(err).detail}`);
15140
- if (afterOwnWrite && lastPolicy !== void 0 && lastPolicy !== "") {
15141
- const member = reverseMapStreamPolicy(lastPolicy, desiredBlock);
15142
- if (member !== void 0) streamBlock[STREAM_POLICY_KEY] = member;
15143
- } else if (afterOwnWrite && isTransientStreamReadFailure(err)) keepDeclared(STREAM_POLICY_KEY, "the read failed transiently");
15165
+ if (afterOwnWrite && isTransientStreamReadFailure(err)) keepDeclared(STREAM_POLICY_KEY, "the read failed transiently");
15166
+ else if (afterOwnWrite && lastPolicy !== void 0 && lastPolicy !== "") keepDeclared(STREAM_POLICY_KEY, "the read failed after an unsettled answer");
15144
15167
  }
15145
15168
  }
15146
15169
  if (streamDeclaresTags(desiredBlock)) {
@@ -16534,7 +16557,21 @@ async function getAttribute$13(physicalId, _resourceType, attributeName) {
16534
16557
  if (attributeName !== "Arn") return;
16535
16558
  return this.buildArn(physicalId);
16536
16559
  }
16537
- async function readCurrentState$32(physicalId, _logicalId, _resourceType) {
16560
+ async function readDataProtectionPolicy(physicalId) {
16561
+ let document;
16562
+ try {
16563
+ document = (await this.logsClient.send(new GetDataProtectionPolicyCommand({ logGroupIdentifier: physicalId }))).policyDocument;
16564
+ } catch (err) {
16565
+ return memberReadFailure(err);
16566
+ }
16567
+ if (!document) return "absent";
16568
+ try {
16569
+ return { value: JSON.parse(document) };
16570
+ } catch {
16571
+ return { value: document };
16572
+ }
16573
+ }
16574
+ async function readCurrentState$32(physicalId, logicalId, _resourceType, properties, context) {
16538
16575
  try {
16539
16576
  const found = (await this.logsClient.send(new DescribeLogGroupsCommand({ logGroupNamePrefix: physicalId }))).logGroups?.find((g) => g.logGroupName === physicalId);
16540
16577
  if (!found) return RESOURCE_NOT_FOUND;
@@ -16557,16 +16594,10 @@ async function readCurrentState$32(physicalId, _logicalId, _resourceType) {
16557
16594
  }
16558
16595
  }
16559
16596
  result["Tags"] = tags;
16560
- let dpp = "";
16561
- try {
16562
- const dppResp = await this.logsClient.send(new GetDataProtectionPolicyCommand({ logGroupIdentifier: physicalId }));
16563
- if (dppResp.policyDocument) try {
16564
- dpp = JSON.parse(dppResp.policyDocument);
16565
- } catch {
16566
- dpp = dppResp.policyDocument;
16567
- }
16568
- } catch {}
16569
- result["DataProtectionPolicy"] = dpp;
16597
+ let dpp = await readDataProtectionPolicy.call(this, physicalId);
16598
+ const declared = context?.afterOwnWrite === true ? declaredMemberDocument(properties?.["DataProtectionPolicy"]) : void 0;
16599
+ 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"));
16600
+ result["DataProtectionPolicy"] = typeof dpp === "object" ? dpp.value : "";
16570
16601
  let fieldIndexPolicies = [];
16571
16602
  try {
16572
16603
  fieldIndexPolicies = ((await this.logsClient.send(new DescribeIndexPoliciesCommand({ logGroupIdentifiers: [physicalId] }))).indexPolicies ?? []).filter((p) => p.source !== "ACCOUNT").map((p) => {
@@ -16606,6 +16637,7 @@ var LogsLogGroupProvider = class {
16606
16637
  logsClient;
16607
16638
  stsClient;
16608
16639
  logger = getLogger().child("LogsLogGroupProvider");
16640
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
16609
16641
  protectionFlips = new ProtectionFlipRegistry();
16610
16642
  handledProperties = /* @__PURE__ */ new Map([["AWS::Logs::LogGroup", /* @__PURE__ */ new Set([
16611
16643
  "LogGroupName",
@@ -16669,8 +16701,8 @@ var LogsLogGroupProvider = class {
16669
16701
  getAttribute(physicalId, _resourceType, attributeName) {
16670
16702
  return getAttribute$13.call(this, physicalId, _resourceType, attributeName);
16671
16703
  }
16672
- readCurrentState(physicalId, _logicalId, _resourceType) {
16673
- return readCurrentState$32.call(this, physicalId, _logicalId, _resourceType);
16704
+ readCurrentState(physicalId, _logicalId, _resourceType, properties, context) {
16705
+ return readCurrentState$32.call(this, physicalId, _logicalId, _resourceType, properties, context);
16674
16706
  }
16675
16707
  import(input) {
16676
16708
  return importImpl$33.call(this, input);
@@ -16946,6 +16978,7 @@ const WHAT$1 = "CloudWatch Logs delivery destination";
16946
16978
  var LogsDeliveryDestinationProvider = class {
16947
16979
  client;
16948
16980
  logger = getLogger().child("LogsDeliveryDestinationProvider");
16981
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
16949
16982
  constructor() {
16950
16983
  this.client = getAwsClients().cloudWatchLogs;
16951
16984
  }
@@ -17053,7 +17086,7 @@ var LogsDeliveryDestinationProvider = class {
17053
17086
  throw error;
17054
17087
  }
17055
17088
  }
17056
- async readCurrentState(physicalId, _logicalId, _resourceType, properties) {
17089
+ async readCurrentState(physicalId, logicalId, _resourceType, properties, context) {
17057
17090
  let destination;
17058
17091
  try {
17059
17092
  destination = (await this.client.send(new GetDeliveryDestinationCommand({ name: physicalId }))).deliveryDestination;
@@ -17068,19 +17101,14 @@ var LogsDeliveryDestinationProvider = class {
17068
17101
  if (destinationArn !== void 0) result["DestinationResourceArn"] = destinationArn;
17069
17102
  if (destination.deliveryDestinationType !== void 0) result["DeliveryDestinationType"] = destination.deliveryDestinationType;
17070
17103
  if (destination.outputFormat !== void 0) result["OutputFormat"] = destination.outputFormat;
17071
- let policy;
17072
- try {
17073
- policy = (await this.client.send(new GetDeliveryDestinationPolicyCommand({ deliveryDestinationName: physicalId }))).policy?.deliveryDestinationPolicy;
17074
- } catch (error) {
17075
- if (!isLogsNotFound(error)) throw error;
17076
- }
17077
- if (policy !== void 0 && policy !== "") {
17078
- const declared = properties?.["DeliveryDestinationPolicy"];
17079
- result["DeliveryDestinationPolicy"] = {
17080
- ...isPlainRecord$3(declared) && declared["DeliveryDestinationName"] !== void 0 && { DeliveryDestinationName: physicalId },
17081
- DeliveryDestinationPolicy: parsePolicy(policy)
17082
- };
17083
- }
17104
+ let policy = await this.readDestinationPolicy(physicalId);
17105
+ const declared = properties?.["DeliveryDestinationPolicy"];
17106
+ const declaredDocument = context?.afterOwnWrite === true && isPlainRecord$3(declared) ? declared["DeliveryDestinationPolicy"] : void 0;
17107
+ 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"));
17108
+ if (typeof policy === "object") result["DeliveryDestinationPolicy"] = {
17109
+ ...isPlainRecord$3(declared) && declared["DeliveryDestinationName"] !== void 0 && { DeliveryDestinationName: physicalId },
17110
+ DeliveryDestinationPolicy: policy.value
17111
+ };
17084
17112
  try {
17085
17113
  if (destination.arn) result["Tags"] = await readTags$1(this.client, destination.arn);
17086
17114
  } catch (error) {
@@ -17089,6 +17117,15 @@ var LogsDeliveryDestinationProvider = class {
17089
17117
  }
17090
17118
  return result;
17091
17119
  }
17120
+ async readDestinationPolicy(physicalId) {
17121
+ let policy;
17122
+ try {
17123
+ policy = (await this.client.send(new GetDeliveryDestinationPolicyCommand({ deliveryDestinationName: physicalId }))).policy?.deliveryDestinationPolicy;
17124
+ } catch (error) {
17125
+ if (!isLogsNotFound(error)) throw error;
17126
+ }
17127
+ return policy !== void 0 && policy !== "" ? { value: parsePolicy(policy) } : "absent";
17128
+ }
17092
17129
  wrapError(operation, logicalId, resourceType, physicalId, error) {
17093
17130
  if (error instanceof ProvisioningError) return error;
17094
17131
  return wrapLogsError(this.logger, WHAT$1, operation, logicalId, resourceType, physicalId, error);
@@ -25097,7 +25134,7 @@ async function withDependencyViolationRetry(operation, opts) {
25097
25134
  } catch (error) {
25098
25135
  if (!this.isDependencyViolationError(error)) throw error;
25099
25136
  const elapsed = Date.now() - startedAt;
25100
- if (elapsed >= totalBudgetMs) throw error;
25137
+ if (elapsed >= totalBudgetMs) throw markNonRetryable(error);
25101
25138
  attempt += 1;
25102
25139
  const sleepMs = Math.min(delay, totalBudgetMs - elapsed);
25103
25140
  const message = describeAwsFailure(error).detail;
@@ -26738,6 +26775,503 @@ function methodChildCalls(ids, desired, previous) {
26738
26775
  return calls;
26739
26776
  }
26740
26777
 
26778
+ // src/provisioning/providers/apigateway/rest-api.ts
26779
+ const BODY_KEYS = [
26780
+ "Body",
26781
+ "BodyS3Location",
26782
+ "Mode",
26783
+ "FailOnWarnings",
26784
+ "Parameters"
26785
+ ];
26786
+ const SCALAR_FIELDS = [
26787
+ {
26788
+ key: "Name",
26789
+ path: "/name"
26790
+ },
26791
+ {
26792
+ key: "Description",
26793
+ path: "/description"
26794
+ },
26795
+ {
26796
+ key: "Version",
26797
+ path: "/version"
26798
+ },
26799
+ {
26800
+ key: "MinimumCompressionSize",
26801
+ path: "/minimumCompressionSize"
26802
+ },
26803
+ {
26804
+ key: "ApiKeySourceType",
26805
+ path: "/apiKeySource"
26806
+ },
26807
+ {
26808
+ key: "DisableExecuteApiEndpoint",
26809
+ path: "/disableExecuteApiEndpoint"
26810
+ },
26811
+ {
26812
+ key: "SecurityPolicy",
26813
+ path: "/securityPolicy"
26814
+ },
26815
+ {
26816
+ key: "EndpointAccessMode",
26817
+ path: "/endpointAccessMode"
26818
+ }
26819
+ ];
26820
+ function pointerSegment(value) {
26821
+ return value.replace(/~/g, "~0").replace(/\//g, "~1");
26822
+ }
26823
+ function stringList(value) {
26824
+ if (!Array.isArray(value)) return void 0;
26825
+ return value.filter((v) => typeof v === "string");
26826
+ }
26827
+ function asRecord$2(value) {
26828
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
26829
+ }
26830
+ function restApiPolicyString(policy) {
26831
+ if (policy === void 0 || policy === null) return void 0;
26832
+ return typeof policy === "string" ? policy : JSON.stringify(policy);
26833
+ }
26834
+ function parseRestApiPolicy(raw, restApiId, recorded) {
26835
+ if (raw === void 0 || raw === "") return void 0;
26836
+ let text = raw;
26837
+ let parsed;
26838
+ try {
26839
+ parsed = JSON.parse(text);
26840
+ } catch {
26841
+ text = raw.replace(/\\(["\\/])/g, "$1");
26842
+ try {
26843
+ parsed = JSON.parse(text);
26844
+ } catch {
26845
+ return raw;
26846
+ }
26847
+ }
26848
+ const recordedText = restApiPolicyString(recorded);
26849
+ if (recordedText !== void 0 && recordedText.includes("execute-api:/")) {
26850
+ const expanded = new RegExp(`arn:[a-z-]+:execute-api:[a-z0-9-]+:\\d{12}:${restApiId}/`, "g");
26851
+ parsed = JSON.parse(JSON.stringify(parsed).replace(expanded, "execute-api:/"));
26852
+ }
26853
+ return parsed;
26854
+ }
26855
+ function restApiAsCfn(api, recordedPolicy) {
26856
+ const out = {};
26857
+ if (api.name !== void 0) out["Name"] = api.name;
26858
+ if (api.description !== void 0) out["Description"] = api.description;
26859
+ if (api.version !== void 0) out["Version"] = api.version;
26860
+ out["BinaryMediaTypes"] = api.binaryMediaTypes ? [...api.binaryMediaTypes] : [];
26861
+ if (api.minimumCompressionSize !== void 0) out["MinimumCompressionSize"] = api.minimumCompressionSize;
26862
+ if (api.apiKeySource !== void 0) out["ApiKeySourceType"] = api.apiKeySource;
26863
+ if (api.disableExecuteApiEndpoint !== void 0) out["DisableExecuteApiEndpoint"] = api.disableExecuteApiEndpoint;
26864
+ const policy = parseRestApiPolicy(api.policy, api.id ?? "", recordedPolicy);
26865
+ if (policy !== void 0) out["Policy"] = policy;
26866
+ if (api.endpointConfiguration !== void 0) {
26867
+ const ec = {};
26868
+ if (api.endpointConfiguration.types !== void 0) ec["Types"] = [...api.endpointConfiguration.types];
26869
+ if (api.endpointConfiguration.vpcEndpointIds !== void 0) ec["VpcEndpointIds"] = [...api.endpointConfiguration.vpcEndpointIds];
26870
+ if (api.endpointConfiguration.ipAddressType !== void 0) ec["IpAddressType"] = api.endpointConfiguration.ipAddressType;
26871
+ out["EndpointConfiguration"] = ec;
26872
+ }
26873
+ if (api.securityPolicy !== void 0) out["SecurityPolicy"] = api.securityPolicy;
26874
+ if (api.endpointAccessMode !== void 0) out["EndpointAccessMode"] = api.endpointAccessMode;
26875
+ return out;
26876
+ }
26877
+ function definitionBinaryMediaTypes(body) {
26878
+ let definition = body;
26879
+ if (typeof body === "string") try {
26880
+ definition = JSON.parse(body);
26881
+ } catch {
26882
+ return /* @__PURE__ */ new Set();
26883
+ }
26884
+ return new Set(stringList(asRecord$2(definition)?.["x-amazon-apigateway-binary-media-types"]) ?? []);
26885
+ }
26886
+ function isJsonText(text) {
26887
+ try {
26888
+ JSON.parse(text);
26889
+ return true;
26890
+ } catch {
26891
+ return false;
26892
+ }
26893
+ }
26894
+ function endpointType(config) {
26895
+ return stringList(asRecord$2(config)?.["Types"])?.[0];
26896
+ }
26897
+ function restApiPatchOperations(desired, current, previous, bodyPutMode) {
26898
+ const ops = [];
26899
+ for (const { key, path } of SCALAR_FIELDS) {
26900
+ const next = desired[key];
26901
+ if (next === void 0 || next === null) continue;
26902
+ const value = stringifyValue(next);
26903
+ if (value !== (current[key] == null ? "" : stringifyValue(current[key]))) ops.push({
26904
+ op: "replace",
26905
+ path,
26906
+ value
26907
+ });
26908
+ }
26909
+ const nextPolicy = restApiPolicyString(desired["Policy"]);
26910
+ if (nextPolicy !== void 0 && nextPolicy !== restApiPolicyString(current["Policy"])) ops.push({
26911
+ op: "replace",
26912
+ path: "/policy",
26913
+ value: nextPolicy
26914
+ });
26915
+ const targetTypes = stringList(desired["BinaryMediaTypes"]) ?? (previous["BinaryMediaTypes"] !== void 0 ? [] : void 0);
26916
+ if (targetTypes !== void 0) {
26917
+ const live = new Set(stringList(current["BinaryMediaTypes"]) ?? []);
26918
+ const target = new Set(targetTypes);
26919
+ const fromDefinition = definitionBinaryMediaTypes(desired["Body"]);
26920
+ const dropped = bodyPutMode === "overwrite" ? [] : stringList(previous["BinaryMediaTypes"]) ?? [];
26921
+ for (const t of new Set(dropped)) if (live.has(t) && !target.has(t) && !fromDefinition.has(t)) ops.push({
26922
+ op: "remove",
26923
+ path: `/binaryMediaTypes/${pointerSegment(t)}`
26924
+ });
26925
+ for (const t of target) if (!live.has(t)) ops.push({
26926
+ op: "add",
26927
+ path: `/binaryMediaTypes/${pointerSegment(t)}`
26928
+ });
26929
+ }
26930
+ const desiredEc = asRecord$2(desired["EndpointConfiguration"]);
26931
+ const currentEc = asRecord$2(current["EndpointConfiguration"]);
26932
+ const targetType = endpointType(desiredEc) ?? (previous["EndpointConfiguration"] !== void 0 ? "EDGE" : void 0);
26933
+ const currentType = endpointType(currentEc) ?? "EDGE";
26934
+ if (targetType !== void 0 && targetType !== currentType) ops.push({
26935
+ op: "replace",
26936
+ path: `/endpointConfiguration/types/${currentType}`,
26937
+ value: targetType
26938
+ });
26939
+ if (desiredEc !== void 0) {
26940
+ const nextIds = stringList(desiredEc["VpcEndpointIds"]);
26941
+ if (nextIds !== void 0 || targetType === "PRIVATE") {
26942
+ const live = new Set(stringList(currentEc?.["VpcEndpointIds"]) ?? []);
26943
+ const target = new Set(nextIds ?? []);
26944
+ for (const id of target) if (!live.has(id)) ops.push({
26945
+ op: "add",
26946
+ path: "/endpointConfiguration/vpcEndpointIds",
26947
+ value: id
26948
+ });
26949
+ for (const id of live) if (!target.has(id)) ops.push({
26950
+ op: "remove",
26951
+ path: "/endpointConfiguration/vpcEndpointIds",
26952
+ value: id
26953
+ });
26954
+ }
26955
+ const ipType = desiredEc["IpAddressType"];
26956
+ if (typeof ipType === "string" && ipType !== currentEc?.["IpAddressType"]) ops.push({
26957
+ op: "replace",
26958
+ path: "/endpointConfiguration/ipAddressType",
26959
+ value: ipType
26960
+ });
26961
+ }
26962
+ return ops;
26963
+ }
26964
+ function declaresBody(properties) {
26965
+ return properties["Body"] != null || properties["BodyS3Location"] != null;
26966
+ }
26967
+ function restApiBodyChanged(desired, previous, maskSecrets) {
26968
+ if (!declaresBody(desired)) return false;
26969
+ return BODY_KEYS.some((key) => !isDeepStrictEqual(desired[key], previous[key]) && !onlySecretReferencesDiffer(desired[key], previous[key], maskSecrets));
26970
+ }
26971
+ function definitionTitle(body) {
26972
+ try {
26973
+ const info = asRecord$2(asRecord$2(JSON.parse(new TextDecoder().decode(body)))?.["info"]);
26974
+ return typeof info?.["title"] === "string" ? info["title"] : void 0;
26975
+ } catch {
26976
+ return;
26977
+ }
26978
+ }
26979
+ function bodyParameters(value) {
26980
+ const record = asRecord$2(value);
26981
+ if (record === void 0) return void 0;
26982
+ return Object.fromEntries(Object.entries(record).map(([k, v]) => [k, String(v)]));
26983
+ }
26984
+ async function resolveRestApiBody(logicalId, resourceType, properties, mask, physicalId) {
26985
+ const body = properties["Body"];
26986
+ if (body !== void 0 && body !== null) {
26987
+ if (typeof body === "string") return new TextEncoder().encode(body);
26988
+ if (typeof body === "object") return new TextEncoder().encode(JSON.stringify(body));
26989
+ throw new ProvisioningError(`Body of ${resourceType} ${logicalId} must be an OpenAPI definition object or string`, resourceType, logicalId, physicalId);
26990
+ }
26991
+ const location = asRecord$2(properties["BodyS3Location"]);
26992
+ if (properties["BodyS3Location"] == null) return void 0;
26993
+ const bucket = location?.["Bucket"];
26994
+ const key = location?.["Key"];
26995
+ 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);
26996
+ const version = location?.["Version"];
26997
+ const etag = location?.["ETag"];
26998
+ const resp = await getAwsClients().s3.send(new GetObjectCommand({
26999
+ Bucket: bucket,
27000
+ Key: key,
27001
+ ...typeof version === "string" && version && { VersionId: version },
27002
+ ...typeof etag === "string" && etag && { IfMatch: etag }
27003
+ }));
27004
+ const bytes = resp.Body ? await resp.Body.transformToByteArray() : void 0;
27005
+ if (!bytes || bytes.length === 0) throw new ProvisioningError(`BodyS3Location of ${resourceType} ${logicalId} (s3://${mask(bucket)}/${mask(key)}) holds no definition`, resourceType, logicalId, physicalId);
27006
+ return bytes;
27007
+ }
27008
+ async function restApiArn(restApiId) {
27009
+ const region = await this.apiGatewayClient.config.region();
27010
+ const { partition } = derivePartitionAndUrlSuffix(region);
27011
+ return `arn:${partition}:apigateway:${region}::/restapis/${restApiId}`;
27012
+ }
27013
+ async function createRestApi(logicalId, resourceType, properties, log) {
27014
+ log.debug(safeMsg`Creating API Gateway RestApi ${logicalId}`);
27015
+ const name = typeof properties["Name"] === "string" ? properties["Name"] : void 0;
27016
+ const cloneFrom = typeof properties["CloneFrom"] === "string" ? properties["CloneFrom"] : void 0;
27017
+ const hasBody = declaresBody(properties);
27018
+ if (!name && (!hasBody || cloneFrom)) throw new ProvisioningError(`Name is required for API Gateway RestApi ${logicalId} unless Body or BodyS3Location defines the API`, resourceType, logicalId);
27019
+ const tags = refuseMalformedDesiredTags(properties["Tags"], resourceType, logicalId);
27020
+ let restApiId;
27021
+ try {
27022
+ const body = await resolveRestApiBody.call(this, logicalId, resourceType, properties, log.value);
27023
+ const createdName = body && !cloneFrom ? definitionTitle(body) : name;
27024
+ const desiredEc = asRecord$2(properties["EndpointConfiguration"]);
27025
+ const reportOrphans = async (lookupWindow) => {
27026
+ const aws = pasteableAwsCommand(log.mask);
27027
+ const regionArg = await this.orphanCommandRegionArg(aws);
27028
+ await reportPossibleOrphans(logicalId, lookupWindow, log, {
27029
+ action: body && !cloneFrom ? "ImportRestApi" : "CreateRestApi",
27030
+ listAction: "GetRestApis",
27031
+ subject: createdName ? `a REST API named ${log.value(createdName)}` : "a REST API",
27032
+ noun: "REST API(s)",
27033
+ ...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." },
27034
+ list: () => collectOrphanIds(async (position) => {
27035
+ const page = await this.apiGatewayClient.send(new GetRestApisCommand({
27036
+ limit: 500,
27037
+ ...position && { position }
27038
+ }));
27039
+ return {
27040
+ items: page.items ?? [],
27041
+ next: page.position
27042
+ };
27043
+ }, (a) => a.id && (createdName === void 0 || a.name === createdName) && isInsideWindow(a.createdDate, lookupWindow) && !restApisCreatedByThisProcess.has(a.id) ? a.id : void 0),
27044
+ inspect: (id) => aws`aws apigateway get-rest-api --rest-api-id ${id}${regionArg}`.render(),
27045
+ remove: (id) => aws`aws apigateway delete-rest-api --rest-api-id ${id}${regionArg}`.render()
27046
+ });
27047
+ };
27048
+ const orphanWindow = createRestApiLatch.take(logicalId);
27049
+ if (orphanWindow !== void 0) await reportOrphans(orphanWindow);
27050
+ const createClient = await this.getCreateClient();
27051
+ const attemptStartMs = Date.now();
27052
+ let response;
27053
+ try {
27054
+ if (body && !cloneFrom) {
27055
+ const parameters = bodyParameters(properties["Parameters"]) ?? {};
27056
+ const type = endpointType(desiredEc);
27057
+ if (type !== void 0 && parameters["endpointConfigurationTypes"] === void 0) parameters["endpointConfigurationTypes"] = type;
27058
+ response = await createClient.send(new ImportRestApiCommand({
27059
+ body,
27060
+ failOnWarnings: properties["FailOnWarnings"] === true,
27061
+ ...Object.keys(parameters).length > 0 && { parameters }
27062
+ }));
27063
+ } else response = await createClient.send(new CreateRestApiCommand({
27064
+ name,
27065
+ description: properties["Description"],
27066
+ version: properties["Version"],
27067
+ cloneFrom,
27068
+ binaryMediaTypes: stringList(properties["BinaryMediaTypes"]),
27069
+ minimumCompressionSize: properties["MinimumCompressionSize"],
27070
+ apiKeySource: properties["ApiKeySourceType"],
27071
+ endpointConfiguration: desiredEc ? {
27072
+ types: stringList(desiredEc["Types"]),
27073
+ vpcEndpointIds: stringList(desiredEc["VpcEndpointIds"]),
27074
+ ipAddressType: desiredEc["IpAddressType"]
27075
+ } : void 0,
27076
+ policy: restApiPolicyString(properties["Policy"]),
27077
+ tags: tags.length > 0 ? Object.fromEntries(tags.map((t) => [t.Key, t.Value])) : void 0,
27078
+ disableExecuteApiEndpoint: properties["DisableExecuteApiEndpoint"],
27079
+ securityPolicy: properties["SecurityPolicy"],
27080
+ endpointAccessMode: properties["EndpointAccessMode"]
27081
+ }));
27082
+ } catch (error) {
27083
+ createRestApiLatch.noteFailure(logicalId, error, attemptStartMs, orphanWindow);
27084
+ throw error;
27085
+ }
27086
+ if (!response.id) throw new ProvisioningError(`API Gateway answered no id for RestApi ${logicalId}`, resourceType, logicalId);
27087
+ restApiId = response.id;
27088
+ restApisCreatedByThisProcess.add(restApiId);
27089
+ const replayWindow = replayedSendWindow(response, attemptStartMs);
27090
+ if (replayWindow !== void 0) await reportOrphans(replayWindow);
27091
+ let rootResourceId = response.rootResourceId;
27092
+ if (body) {
27093
+ let live = restApiAsCfn(response, properties["Policy"]);
27094
+ if (cloneFrom) {
27095
+ const put = await this.apiGatewayClient.send(new PutRestApiCommand({
27096
+ restApiId,
27097
+ mode: properties["Mode"] ?? "overwrite",
27098
+ failOnWarnings: properties["FailOnWarnings"] === true,
27099
+ parameters: bodyParameters(properties["Parameters"]),
27100
+ body
27101
+ }));
27102
+ live = restApiAsCfn(put, properties["Policy"]);
27103
+ rootResourceId = put.rootResourceId ?? rootResourceId;
27104
+ }
27105
+ const patchOperations = restApiPatchOperations(properties, live, {}, cloneFrom ? properties["Mode"] ?? "overwrite" : "overwrite");
27106
+ if (patchOperations.length > 0) await this.apiGatewayClient.send(new UpdateRestApiCommand({
27107
+ restApiId,
27108
+ patchOperations
27109
+ }));
27110
+ if (tags.length > 0 && !cloneFrom) await this.apiGatewayClient.send(new TagResourceCommand$3({
27111
+ resourceArn: await restApiArn.call(this, restApiId),
27112
+ tags: Object.fromEntries(tags.map((t) => [t.Key, t.Value]))
27113
+ }));
27114
+ }
27115
+ if (rootResourceId === void 0) rootResourceId = (await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId }))).rootResourceId;
27116
+ log.debug(safeMsg`Successfully created API Gateway RestApi ${logicalId}: ${restApiId}`);
27117
+ return {
27118
+ physicalId: restApiId,
27119
+ attributes: {
27120
+ RestApiId: restApiId,
27121
+ ...rootResourceId !== void 0 ? { RootResourceId: rootResourceId } : {}
27122
+ }
27123
+ };
27124
+ } catch (error) {
27125
+ if (error instanceof CdkdError && restApiId === void 0) throw error;
27126
+ const cause = error instanceof Error ? error : void 0;
27127
+ const survivor = restApiId === void 0 ? "" : await retireFailedRestApi.call(this, restApiId, log);
27128
+ throw this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to create API Gateway RestApi ${logicalId}: ${text}${survivor}`, resourceType, logicalId, void 0, cause));
27129
+ }
27130
+ }
27131
+ async function retireFailedRestApi(restApiId, log) {
27132
+ try {
27133
+ await this.apiGatewayClient.send(new DeleteRestApiCommand({ restApiId }));
27134
+ log.debug(safeMsg`Deleted REST API ${restApiId} left by the failed create`);
27135
+ return "";
27136
+ } catch (cleanupError) {
27137
+ if (cleanupError instanceof NotFoundException$1) return "";
27138
+ const aws = pasteableAwsCommand(log.mask);
27139
+ const regionArg = await this.orphanCommandRegionArg(aws);
27140
+ 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();
27141
+ }
27142
+ }
27143
+ async function updateRestApi(logicalId, physicalId, resourceType, properties, previousProperties, log, changedProperties, noEchoOnlyChanged, keptNoEchoOnly) {
27144
+ refuseMalformedDesiredTags(properties["Tags"], resourceType, logicalId, physicalId);
27145
+ try {
27146
+ let current = previousProperties;
27147
+ let bodyPutMode;
27148
+ let rootResourceId;
27149
+ let bodyChanged = changedProperties !== void 0 ? declaresBody(properties) && BODY_KEYS.some((key) => changedProperties.has(key)) : restApiBodyChanged(properties, previousProperties, log.mask);
27150
+ if (bodyChanged && changedProperties !== void 0 && noEchoOnlyChanged !== void 0) {
27151
+ const named = BODY_KEYS.filter((key) => changedProperties.has(key));
27152
+ if (named.length > 0 && named.every((key) => noEchoOnlyChanged.has(key))) {
27153
+ bodyChanged = false;
27154
+ for (const key of named) keptNoEchoOnly?.(key);
27155
+ 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.`);
27156
+ }
27157
+ }
27158
+ if (bodyChanged) {
27159
+ const body = await resolveRestApiBody.call(this, logicalId, resourceType, properties, log.value, physicalId);
27160
+ const put = await this.apiGatewayClient.send(new PutRestApiCommand({
27161
+ restApiId: physicalId,
27162
+ mode: properties["Mode"] ?? "overwrite",
27163
+ failOnWarnings: properties["FailOnWarnings"] === true,
27164
+ parameters: bodyParameters(properties["Parameters"]),
27165
+ body
27166
+ }));
27167
+ log.debug(safeMsg`Put the OpenAPI definition of API Gateway RestApi ${logicalId}: ${physicalId}`);
27168
+ current = restApiAsCfn(put, properties["Policy"]);
27169
+ bodyPutMode = properties["Mode"] ?? "overwrite";
27170
+ rootResourceId = put.rootResourceId;
27171
+ }
27172
+ const patchOperations = restApiPatchOperations(properties, current, previousProperties, bodyPutMode);
27173
+ if (patchOperations.length > 0) {
27174
+ await this.apiGatewayClient.send(new UpdateRestApiCommand({
27175
+ restApiId: physicalId,
27176
+ patchOperations
27177
+ }));
27178
+ log.debug(safeMsg`Updated API Gateway RestApi ${logicalId} (${patchOperations.length} patch ops)`);
27179
+ }
27180
+ const arn = await restApiArn.call(this, physicalId);
27181
+ await this.applyTagDiff(arn, resourceType, logicalId, previousProperties["Tags"], properties["Tags"], log, arn);
27182
+ return {
27183
+ physicalId,
27184
+ wasReplaced: false,
27185
+ ...rootResourceId !== void 0 ? { attributes: {
27186
+ RestApiId: physicalId,
27187
+ RootResourceId: rootResourceId
27188
+ } } : {}
27189
+ };
27190
+ } catch (error) {
27191
+ if (error instanceof CdkdError) throw error;
27192
+ const cause = error instanceof Error ? error : void 0;
27193
+ throw this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to update API Gateway RestApi ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
27194
+ }
27195
+ }
27196
+ async function deleteRestApi(logicalId, physicalId, resourceType, context) {
27197
+ this.logger.debug(safeMsg`Deleting API Gateway RestApi ${logicalId}: ${physicalId}`);
27198
+ try {
27199
+ await this.apiGatewayClient.send(new DeleteRestApiCommand({ restApiId: physicalId }));
27200
+ this.logger.debug(safeMsg`Successfully deleted API Gateway RestApi ${logicalId}`);
27201
+ } catch (error) {
27202
+ if (error instanceof NotFoundException$1) {
27203
+ const clientRegion = await this.apiGatewayClient.config.region();
27204
+ assertRegionMatch(clientRegion, context?.expectedRegion, resourceType, logicalId, physicalId);
27205
+ this.logger.debug(safeMsg`API Gateway RestApi ${physicalId} does not exist, skipping deletion`);
27206
+ return;
27207
+ }
27208
+ const cause = error instanceof Error ? error : void 0;
27209
+ const thrown = this.wrapMaskedError(context?.maskSecrets ?? ((text) => text), error, (text) => new ProvisioningError(`Failed to delete API Gateway RestApi ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
27210
+ throw error instanceof Error && error.name.includes("NotFound") ? markNotGone(thrown) : thrown;
27211
+ }
27212
+ }
27213
+ async function getRestApiAttribute(physicalId, attributeName) {
27214
+ if (attributeName === "RestApiId") return physicalId;
27215
+ if (attributeName === "RootResourceId") return (await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: physicalId }))).rootResourceId;
27216
+ }
27217
+ async function readCurrentStateRestApi(physicalId, properties) {
27218
+ try {
27219
+ const resp = await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: physicalId }));
27220
+ const result = restApiAsCfn(resp, properties?.["Policy"]);
27221
+ const fromDefinition = definitionBinaryMediaTypes(properties?.["Body"]);
27222
+ const declared = new Set(stringList(properties?.["BinaryMediaTypes"]) ?? []);
27223
+ const unreadable = properties?.["BodyS3Location"] != null || typeof properties?.["Body"] === "string" && !isJsonText(properties["Body"]);
27224
+ result["BinaryMediaTypes"] = result["BinaryMediaTypes"].filter((t) => unreadable ? declared.has(t) : !fromDefinition.has(t) || declared.has(t));
27225
+ result["Tags"] = Object.entries(resp.tags ?? {}).filter(([key]) => !key.startsWith("aws:")).map(([Key, Value]) => ({
27226
+ Key,
27227
+ Value
27228
+ }));
27229
+ return result;
27230
+ } catch (err) {
27231
+ if (err instanceof NotFoundException$1) return RESOURCE_NOT_FOUND;
27232
+ throw err;
27233
+ }
27234
+ }
27235
+ const REST_API_WRITE_ONLY_PATHS = [
27236
+ "Body",
27237
+ "BodyS3Location",
27238
+ "CloneFrom",
27239
+ "FailOnWarnings",
27240
+ "Mode",
27241
+ "Parameters"
27242
+ ];
27243
+ async function importRestApi(input) {
27244
+ if (!input.knownPhysicalId) return null;
27245
+ try {
27246
+ const resp = await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: input.knownPhysicalId }));
27247
+ return {
27248
+ physicalId: input.knownPhysicalId,
27249
+ attributes: {
27250
+ RestApiId: input.knownPhysicalId,
27251
+ ...resp.rootResourceId !== void 0 ? { RootResourceId: resp.rootResourceId } : {}
27252
+ }
27253
+ };
27254
+ } catch (err) {
27255
+ if (err instanceof NotFoundException$1) return null;
27256
+ throw err;
27257
+ }
27258
+ }
27259
+
27260
+ // src/provisioning/providers/apigateway/rest-api-own-write.ts
27261
+ async function settleRestApiPolicy(physicalId, logicalId, read, properties) {
27262
+ const declared = declaredMemberDocument(properties?.["Policy"]);
27263
+ if (declared === void 0 || read === void 0 || read === RESOURCE_NOT_FOUND) return read;
27264
+ const asMember = (policy) => policy === void 0 ? "absent" : { value: policy };
27265
+ const policy = await settleDeclaredMember(asMember(read["Policy"]), async () => {
27266
+ const resp = await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: physicalId }));
27267
+ return asMember(restApiAsCfn(resp, properties?.["Policy"])["Policy"]);
27268
+ }, (value) => policyDocumentMatchesDeclared(value, declared), declared, this.ownWriteRereadDelaysMs, () => warnUnsettledMember(this.logger, logicalId, "AWS::ApiGateway::RestApi", "Policy"));
27269
+ return typeof policy === "object" ? {
27270
+ ...read,
27271
+ Policy: policy.value
27272
+ } : read;
27273
+ }
27274
+
26741
27275
  // src/provisioning/providers/apigateway/core.ts
26742
27276
  function getCreateClient$7() {
26743
27277
  this.createClient ??= this.apiGatewayClient.config.region().then((region) => withoutServerErrorRetries(withApiGatewayPacing(new APIGatewayClient({
@@ -27794,488 +28328,6 @@ function getMethodAttribute(physicalId, attributeName) {
27794
28328
  return Promise.resolve(void 0);
27795
28329
  }
27796
28330
 
27797
- // src/provisioning/providers/apigateway/rest-api.ts
27798
- const BODY_KEYS = [
27799
- "Body",
27800
- "BodyS3Location",
27801
- "Mode",
27802
- "FailOnWarnings",
27803
- "Parameters"
27804
- ];
27805
- const SCALAR_FIELDS = [
27806
- {
27807
- key: "Name",
27808
- path: "/name"
27809
- },
27810
- {
27811
- key: "Description",
27812
- path: "/description"
27813
- },
27814
- {
27815
- key: "Version",
27816
- path: "/version"
27817
- },
27818
- {
27819
- key: "MinimumCompressionSize",
27820
- path: "/minimumCompressionSize"
27821
- },
27822
- {
27823
- key: "ApiKeySourceType",
27824
- path: "/apiKeySource"
27825
- },
27826
- {
27827
- key: "DisableExecuteApiEndpoint",
27828
- path: "/disableExecuteApiEndpoint"
27829
- },
27830
- {
27831
- key: "SecurityPolicy",
27832
- path: "/securityPolicy"
27833
- },
27834
- {
27835
- key: "EndpointAccessMode",
27836
- path: "/endpointAccessMode"
27837
- }
27838
- ];
27839
- function pointerSegment(value) {
27840
- return value.replace(/~/g, "~0").replace(/\//g, "~1");
27841
- }
27842
- function stringList(value) {
27843
- if (!Array.isArray(value)) return void 0;
27844
- return value.filter((v) => typeof v === "string");
27845
- }
27846
- function asRecord$2(value) {
27847
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
27848
- }
27849
- function restApiPolicyString(policy) {
27850
- if (policy === void 0 || policy === null) return void 0;
27851
- return typeof policy === "string" ? policy : JSON.stringify(policy);
27852
- }
27853
- function parseRestApiPolicy(raw, restApiId, recorded) {
27854
- if (raw === void 0 || raw === "") return void 0;
27855
- let text = raw;
27856
- let parsed;
27857
- try {
27858
- parsed = JSON.parse(text);
27859
- } catch {
27860
- text = raw.replace(/\\(["\\/])/g, "$1");
27861
- try {
27862
- parsed = JSON.parse(text);
27863
- } catch {
27864
- return raw;
27865
- }
27866
- }
27867
- const recordedText = restApiPolicyString(recorded);
27868
- if (recordedText !== void 0 && recordedText.includes("execute-api:/")) {
27869
- const expanded = new RegExp(`arn:[a-z-]+:execute-api:[a-z0-9-]+:\\d{12}:${restApiId}/`, "g");
27870
- parsed = JSON.parse(JSON.stringify(parsed).replace(expanded, "execute-api:/"));
27871
- }
27872
- return parsed;
27873
- }
27874
- function restApiAsCfn(api, recordedPolicy) {
27875
- const out = {};
27876
- if (api.name !== void 0) out["Name"] = api.name;
27877
- if (api.description !== void 0) out["Description"] = api.description;
27878
- if (api.version !== void 0) out["Version"] = api.version;
27879
- out["BinaryMediaTypes"] = api.binaryMediaTypes ? [...api.binaryMediaTypes] : [];
27880
- if (api.minimumCompressionSize !== void 0) out["MinimumCompressionSize"] = api.minimumCompressionSize;
27881
- if (api.apiKeySource !== void 0) out["ApiKeySourceType"] = api.apiKeySource;
27882
- if (api.disableExecuteApiEndpoint !== void 0) out["DisableExecuteApiEndpoint"] = api.disableExecuteApiEndpoint;
27883
- const policy = parseRestApiPolicy(api.policy, api.id ?? "", recordedPolicy);
27884
- if (policy !== void 0) out["Policy"] = policy;
27885
- if (api.endpointConfiguration !== void 0) {
27886
- const ec = {};
27887
- if (api.endpointConfiguration.types !== void 0) ec["Types"] = [...api.endpointConfiguration.types];
27888
- if (api.endpointConfiguration.vpcEndpointIds !== void 0) ec["VpcEndpointIds"] = [...api.endpointConfiguration.vpcEndpointIds];
27889
- if (api.endpointConfiguration.ipAddressType !== void 0) ec["IpAddressType"] = api.endpointConfiguration.ipAddressType;
27890
- out["EndpointConfiguration"] = ec;
27891
- }
27892
- if (api.securityPolicy !== void 0) out["SecurityPolicy"] = api.securityPolicy;
27893
- if (api.endpointAccessMode !== void 0) out["EndpointAccessMode"] = api.endpointAccessMode;
27894
- return out;
27895
- }
27896
- function definitionBinaryMediaTypes(body) {
27897
- let definition = body;
27898
- if (typeof body === "string") try {
27899
- definition = JSON.parse(body);
27900
- } catch {
27901
- return /* @__PURE__ */ new Set();
27902
- }
27903
- return new Set(stringList(asRecord$2(definition)?.["x-amazon-apigateway-binary-media-types"]) ?? []);
27904
- }
27905
- function isJsonText(text) {
27906
- try {
27907
- JSON.parse(text);
27908
- return true;
27909
- } catch {
27910
- return false;
27911
- }
27912
- }
27913
- function endpointType(config) {
27914
- return stringList(asRecord$2(config)?.["Types"])?.[0];
27915
- }
27916
- function restApiPatchOperations(desired, current, previous, bodyPutMode) {
27917
- const ops = [];
27918
- for (const { key, path } of SCALAR_FIELDS) {
27919
- const next = desired[key];
27920
- if (next === void 0 || next === null) continue;
27921
- const value = stringifyValue(next);
27922
- if (value !== (current[key] == null ? "" : stringifyValue(current[key]))) ops.push({
27923
- op: "replace",
27924
- path,
27925
- value
27926
- });
27927
- }
27928
- const nextPolicy = restApiPolicyString(desired["Policy"]);
27929
- if (nextPolicy !== void 0 && nextPolicy !== restApiPolicyString(current["Policy"])) ops.push({
27930
- op: "replace",
27931
- path: "/policy",
27932
- value: nextPolicy
27933
- });
27934
- const targetTypes = stringList(desired["BinaryMediaTypes"]) ?? (previous["BinaryMediaTypes"] !== void 0 ? [] : void 0);
27935
- if (targetTypes !== void 0) {
27936
- const live = new Set(stringList(current["BinaryMediaTypes"]) ?? []);
27937
- const target = new Set(targetTypes);
27938
- const fromDefinition = definitionBinaryMediaTypes(desired["Body"]);
27939
- const dropped = bodyPutMode === "overwrite" ? [] : stringList(previous["BinaryMediaTypes"]) ?? [];
27940
- for (const t of new Set(dropped)) if (live.has(t) && !target.has(t) && !fromDefinition.has(t)) ops.push({
27941
- op: "remove",
27942
- path: `/binaryMediaTypes/${pointerSegment(t)}`
27943
- });
27944
- for (const t of target) if (!live.has(t)) ops.push({
27945
- op: "add",
27946
- path: `/binaryMediaTypes/${pointerSegment(t)}`
27947
- });
27948
- }
27949
- const desiredEc = asRecord$2(desired["EndpointConfiguration"]);
27950
- const currentEc = asRecord$2(current["EndpointConfiguration"]);
27951
- const targetType = endpointType(desiredEc) ?? (previous["EndpointConfiguration"] !== void 0 ? "EDGE" : void 0);
27952
- const currentType = endpointType(currentEc) ?? "EDGE";
27953
- if (targetType !== void 0 && targetType !== currentType) ops.push({
27954
- op: "replace",
27955
- path: `/endpointConfiguration/types/${currentType}`,
27956
- value: targetType
27957
- });
27958
- if (desiredEc !== void 0) {
27959
- const nextIds = stringList(desiredEc["VpcEndpointIds"]);
27960
- if (nextIds !== void 0 || targetType === "PRIVATE") {
27961
- const live = new Set(stringList(currentEc?.["VpcEndpointIds"]) ?? []);
27962
- const target = new Set(nextIds ?? []);
27963
- for (const id of target) if (!live.has(id)) ops.push({
27964
- op: "add",
27965
- path: "/endpointConfiguration/vpcEndpointIds",
27966
- value: id
27967
- });
27968
- for (const id of live) if (!target.has(id)) ops.push({
27969
- op: "remove",
27970
- path: "/endpointConfiguration/vpcEndpointIds",
27971
- value: id
27972
- });
27973
- }
27974
- const ipType = desiredEc["IpAddressType"];
27975
- if (typeof ipType === "string" && ipType !== currentEc?.["IpAddressType"]) ops.push({
27976
- op: "replace",
27977
- path: "/endpointConfiguration/ipAddressType",
27978
- value: ipType
27979
- });
27980
- }
27981
- return ops;
27982
- }
27983
- function declaresBody(properties) {
27984
- return properties["Body"] != null || properties["BodyS3Location"] != null;
27985
- }
27986
- function restApiBodyChanged(desired, previous, maskSecrets) {
27987
- if (!declaresBody(desired)) return false;
27988
- return BODY_KEYS.some((key) => !isDeepStrictEqual(desired[key], previous[key]) && !onlySecretReferencesDiffer(desired[key], previous[key], maskSecrets));
27989
- }
27990
- function definitionTitle(body) {
27991
- try {
27992
- const info = asRecord$2(asRecord$2(JSON.parse(new TextDecoder().decode(body)))?.["info"]);
27993
- return typeof info?.["title"] === "string" ? info["title"] : void 0;
27994
- } catch {
27995
- return;
27996
- }
27997
- }
27998
- function bodyParameters(value) {
27999
- const record = asRecord$2(value);
28000
- if (record === void 0) return void 0;
28001
- return Object.fromEntries(Object.entries(record).map(([k, v]) => [k, String(v)]));
28002
- }
28003
- async function resolveRestApiBody(logicalId, resourceType, properties, mask, physicalId) {
28004
- const body = properties["Body"];
28005
- if (body !== void 0 && body !== null) {
28006
- if (typeof body === "string") return new TextEncoder().encode(body);
28007
- if (typeof body === "object") return new TextEncoder().encode(JSON.stringify(body));
28008
- throw new ProvisioningError(`Body of ${resourceType} ${logicalId} must be an OpenAPI definition object or string`, resourceType, logicalId, physicalId);
28009
- }
28010
- const location = asRecord$2(properties["BodyS3Location"]);
28011
- if (properties["BodyS3Location"] == null) return void 0;
28012
- const bucket = location?.["Bucket"];
28013
- const key = location?.["Key"];
28014
- 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);
28015
- const version = location?.["Version"];
28016
- const etag = location?.["ETag"];
28017
- const resp = await getAwsClients().s3.send(new GetObjectCommand({
28018
- Bucket: bucket,
28019
- Key: key,
28020
- ...typeof version === "string" && version && { VersionId: version },
28021
- ...typeof etag === "string" && etag && { IfMatch: etag }
28022
- }));
28023
- const bytes = resp.Body ? await resp.Body.transformToByteArray() : void 0;
28024
- if (!bytes || bytes.length === 0) throw new ProvisioningError(`BodyS3Location of ${resourceType} ${logicalId} (s3://${mask(bucket)}/${mask(key)}) holds no definition`, resourceType, logicalId, physicalId);
28025
- return bytes;
28026
- }
28027
- async function restApiArn(restApiId) {
28028
- const region = await this.apiGatewayClient.config.region();
28029
- const { partition } = derivePartitionAndUrlSuffix(region);
28030
- return `arn:${partition}:apigateway:${region}::/restapis/${restApiId}`;
28031
- }
28032
- async function createRestApi(logicalId, resourceType, properties, log) {
28033
- log.debug(safeMsg`Creating API Gateway RestApi ${logicalId}`);
28034
- const name = typeof properties["Name"] === "string" ? properties["Name"] : void 0;
28035
- const cloneFrom = typeof properties["CloneFrom"] === "string" ? properties["CloneFrom"] : void 0;
28036
- const hasBody = declaresBody(properties);
28037
- if (!name && (!hasBody || cloneFrom)) throw new ProvisioningError(`Name is required for API Gateway RestApi ${logicalId} unless Body or BodyS3Location defines the API`, resourceType, logicalId);
28038
- const tags = refuseMalformedDesiredTags(properties["Tags"], resourceType, logicalId);
28039
- let restApiId;
28040
- try {
28041
- const body = await resolveRestApiBody.call(this, logicalId, resourceType, properties, log.value);
28042
- const createdName = body && !cloneFrom ? definitionTitle(body) : name;
28043
- const desiredEc = asRecord$2(properties["EndpointConfiguration"]);
28044
- const reportOrphans = async (lookupWindow) => {
28045
- const aws = pasteableAwsCommand(log.mask);
28046
- const regionArg = await this.orphanCommandRegionArg(aws);
28047
- await reportPossibleOrphans(logicalId, lookupWindow, log, {
28048
- action: body && !cloneFrom ? "ImportRestApi" : "CreateRestApi",
28049
- listAction: "GetRestApis",
28050
- subject: createdName ? `a REST API named ${log.value(createdName)}` : "a REST API",
28051
- noun: "REST API(s)",
28052
- ...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." },
28053
- list: () => collectOrphanIds(async (position) => {
28054
- const page = await this.apiGatewayClient.send(new GetRestApisCommand({
28055
- limit: 500,
28056
- ...position && { position }
28057
- }));
28058
- return {
28059
- items: page.items ?? [],
28060
- next: page.position
28061
- };
28062
- }, (a) => a.id && (createdName === void 0 || a.name === createdName) && isInsideWindow(a.createdDate, lookupWindow) && !restApisCreatedByThisProcess.has(a.id) ? a.id : void 0),
28063
- inspect: (id) => aws`aws apigateway get-rest-api --rest-api-id ${id}${regionArg}`.render(),
28064
- remove: (id) => aws`aws apigateway delete-rest-api --rest-api-id ${id}${regionArg}`.render()
28065
- });
28066
- };
28067
- const orphanWindow = createRestApiLatch.take(logicalId);
28068
- if (orphanWindow !== void 0) await reportOrphans(orphanWindow);
28069
- const createClient = await this.getCreateClient();
28070
- const attemptStartMs = Date.now();
28071
- let response;
28072
- try {
28073
- if (body && !cloneFrom) {
28074
- const parameters = bodyParameters(properties["Parameters"]) ?? {};
28075
- const type = endpointType(desiredEc);
28076
- if (type !== void 0 && parameters["endpointConfigurationTypes"] === void 0) parameters["endpointConfigurationTypes"] = type;
28077
- response = await createClient.send(new ImportRestApiCommand({
28078
- body,
28079
- failOnWarnings: properties["FailOnWarnings"] === true,
28080
- ...Object.keys(parameters).length > 0 && { parameters }
28081
- }));
28082
- } else response = await createClient.send(new CreateRestApiCommand({
28083
- name,
28084
- description: properties["Description"],
28085
- version: properties["Version"],
28086
- cloneFrom,
28087
- binaryMediaTypes: stringList(properties["BinaryMediaTypes"]),
28088
- minimumCompressionSize: properties["MinimumCompressionSize"],
28089
- apiKeySource: properties["ApiKeySourceType"],
28090
- endpointConfiguration: desiredEc ? {
28091
- types: stringList(desiredEc["Types"]),
28092
- vpcEndpointIds: stringList(desiredEc["VpcEndpointIds"]),
28093
- ipAddressType: desiredEc["IpAddressType"]
28094
- } : void 0,
28095
- policy: restApiPolicyString(properties["Policy"]),
28096
- tags: tags.length > 0 ? Object.fromEntries(tags.map((t) => [t.Key, t.Value])) : void 0,
28097
- disableExecuteApiEndpoint: properties["DisableExecuteApiEndpoint"],
28098
- securityPolicy: properties["SecurityPolicy"],
28099
- endpointAccessMode: properties["EndpointAccessMode"]
28100
- }));
28101
- } catch (error) {
28102
- createRestApiLatch.noteFailure(logicalId, error, attemptStartMs, orphanWindow);
28103
- throw error;
28104
- }
28105
- if (!response.id) throw new ProvisioningError(`API Gateway answered no id for RestApi ${logicalId}`, resourceType, logicalId);
28106
- restApiId = response.id;
28107
- restApisCreatedByThisProcess.add(restApiId);
28108
- const replayWindow = replayedSendWindow(response, attemptStartMs);
28109
- if (replayWindow !== void 0) await reportOrphans(replayWindow);
28110
- let rootResourceId = response.rootResourceId;
28111
- if (body) {
28112
- let live = restApiAsCfn(response, properties["Policy"]);
28113
- if (cloneFrom) {
28114
- const put = await this.apiGatewayClient.send(new PutRestApiCommand({
28115
- restApiId,
28116
- mode: properties["Mode"] ?? "overwrite",
28117
- failOnWarnings: properties["FailOnWarnings"] === true,
28118
- parameters: bodyParameters(properties["Parameters"]),
28119
- body
28120
- }));
28121
- live = restApiAsCfn(put, properties["Policy"]);
28122
- rootResourceId = put.rootResourceId ?? rootResourceId;
28123
- }
28124
- const patchOperations = restApiPatchOperations(properties, live, {}, cloneFrom ? properties["Mode"] ?? "overwrite" : "overwrite");
28125
- if (patchOperations.length > 0) await this.apiGatewayClient.send(new UpdateRestApiCommand({
28126
- restApiId,
28127
- patchOperations
28128
- }));
28129
- if (tags.length > 0 && !cloneFrom) await this.apiGatewayClient.send(new TagResourceCommand$3({
28130
- resourceArn: await restApiArn.call(this, restApiId),
28131
- tags: Object.fromEntries(tags.map((t) => [t.Key, t.Value]))
28132
- }));
28133
- }
28134
- if (rootResourceId === void 0) rootResourceId = (await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId }))).rootResourceId;
28135
- log.debug(safeMsg`Successfully created API Gateway RestApi ${logicalId}: ${restApiId}`);
28136
- return {
28137
- physicalId: restApiId,
28138
- attributes: {
28139
- RestApiId: restApiId,
28140
- ...rootResourceId !== void 0 ? { RootResourceId: rootResourceId } : {}
28141
- }
28142
- };
28143
- } catch (error) {
28144
- if (error instanceof CdkdError && restApiId === void 0) throw error;
28145
- const cause = error instanceof Error ? error : void 0;
28146
- const survivor = restApiId === void 0 ? "" : await retireFailedRestApi.call(this, restApiId, log);
28147
- throw this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to create API Gateway RestApi ${logicalId}: ${text}${survivor}`, resourceType, logicalId, void 0, cause));
28148
- }
28149
- }
28150
- async function retireFailedRestApi(restApiId, log) {
28151
- try {
28152
- await this.apiGatewayClient.send(new DeleteRestApiCommand({ restApiId }));
28153
- log.debug(safeMsg`Deleted REST API ${restApiId} left by the failed create`);
28154
- return "";
28155
- } catch (cleanupError) {
28156
- if (cleanupError instanceof NotFoundException$1) return "";
28157
- const aws = pasteableAwsCommand(log.mask);
28158
- const regionArg = await this.orphanCommandRegionArg(aws);
28159
- 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();
28160
- }
28161
- }
28162
- async function updateRestApi(logicalId, physicalId, resourceType, properties, previousProperties, log, changedProperties, noEchoOnlyChanged, keptNoEchoOnly) {
28163
- refuseMalformedDesiredTags(properties["Tags"], resourceType, logicalId, physicalId);
28164
- try {
28165
- let current = previousProperties;
28166
- let bodyPutMode;
28167
- let rootResourceId;
28168
- let bodyChanged = changedProperties !== void 0 ? declaresBody(properties) && BODY_KEYS.some((key) => changedProperties.has(key)) : restApiBodyChanged(properties, previousProperties, log.mask);
28169
- if (bodyChanged && changedProperties !== void 0 && noEchoOnlyChanged !== void 0) {
28170
- const named = BODY_KEYS.filter((key) => changedProperties.has(key));
28171
- if (named.length > 0 && named.every((key) => noEchoOnlyChanged.has(key))) {
28172
- bodyChanged = false;
28173
- for (const key of named) keptNoEchoOnly?.(key);
28174
- 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.`);
28175
- }
28176
- }
28177
- if (bodyChanged) {
28178
- const body = await resolveRestApiBody.call(this, logicalId, resourceType, properties, log.value, physicalId);
28179
- const put = await this.apiGatewayClient.send(new PutRestApiCommand({
28180
- restApiId: physicalId,
28181
- mode: properties["Mode"] ?? "overwrite",
28182
- failOnWarnings: properties["FailOnWarnings"] === true,
28183
- parameters: bodyParameters(properties["Parameters"]),
28184
- body
28185
- }));
28186
- log.debug(safeMsg`Put the OpenAPI definition of API Gateway RestApi ${logicalId}: ${physicalId}`);
28187
- current = restApiAsCfn(put, properties["Policy"]);
28188
- bodyPutMode = properties["Mode"] ?? "overwrite";
28189
- rootResourceId = put.rootResourceId;
28190
- }
28191
- const patchOperations = restApiPatchOperations(properties, current, previousProperties, bodyPutMode);
28192
- if (patchOperations.length > 0) {
28193
- await this.apiGatewayClient.send(new UpdateRestApiCommand({
28194
- restApiId: physicalId,
28195
- patchOperations
28196
- }));
28197
- log.debug(safeMsg`Updated API Gateway RestApi ${logicalId} (${patchOperations.length} patch ops)`);
28198
- }
28199
- const arn = await restApiArn.call(this, physicalId);
28200
- await this.applyTagDiff(arn, resourceType, logicalId, previousProperties["Tags"], properties["Tags"], log, arn);
28201
- return {
28202
- physicalId,
28203
- wasReplaced: false,
28204
- ...rootResourceId !== void 0 ? { attributes: {
28205
- RestApiId: physicalId,
28206
- RootResourceId: rootResourceId
28207
- } } : {}
28208
- };
28209
- } catch (error) {
28210
- if (error instanceof CdkdError) throw error;
28211
- const cause = error instanceof Error ? error : void 0;
28212
- throw this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to update API Gateway RestApi ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
28213
- }
28214
- }
28215
- async function deleteRestApi(logicalId, physicalId, resourceType, context) {
28216
- this.logger.debug(safeMsg`Deleting API Gateway RestApi ${logicalId}: ${physicalId}`);
28217
- try {
28218
- await this.apiGatewayClient.send(new DeleteRestApiCommand({ restApiId: physicalId }));
28219
- this.logger.debug(safeMsg`Successfully deleted API Gateway RestApi ${logicalId}`);
28220
- } catch (error) {
28221
- if (error instanceof NotFoundException$1) {
28222
- const clientRegion = await this.apiGatewayClient.config.region();
28223
- assertRegionMatch(clientRegion, context?.expectedRegion, resourceType, logicalId, physicalId);
28224
- this.logger.debug(safeMsg`API Gateway RestApi ${physicalId} does not exist, skipping deletion`);
28225
- return;
28226
- }
28227
- const cause = error instanceof Error ? error : void 0;
28228
- const thrown = this.wrapMaskedError(context?.maskSecrets ?? ((text) => text), error, (text) => new ProvisioningError(`Failed to delete API Gateway RestApi ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
28229
- throw error instanceof Error && error.name.includes("NotFound") ? markNotGone(thrown) : thrown;
28230
- }
28231
- }
28232
- async function getRestApiAttribute(physicalId, attributeName) {
28233
- if (attributeName === "RestApiId") return physicalId;
28234
- if (attributeName === "RootResourceId") return (await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: physicalId }))).rootResourceId;
28235
- }
28236
- async function readCurrentStateRestApi(physicalId, properties) {
28237
- try {
28238
- const resp = await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: physicalId }));
28239
- const result = restApiAsCfn(resp, properties?.["Policy"]);
28240
- const fromDefinition = definitionBinaryMediaTypes(properties?.["Body"]);
28241
- const declared = new Set(stringList(properties?.["BinaryMediaTypes"]) ?? []);
28242
- const unreadable = properties?.["BodyS3Location"] != null || typeof properties?.["Body"] === "string" && !isJsonText(properties["Body"]);
28243
- result["BinaryMediaTypes"] = result["BinaryMediaTypes"].filter((t) => unreadable ? declared.has(t) : !fromDefinition.has(t) || declared.has(t));
28244
- result["Tags"] = Object.entries(resp.tags ?? {}).filter(([key]) => !key.startsWith("aws:")).map(([Key, Value]) => ({
28245
- Key,
28246
- Value
28247
- }));
28248
- return result;
28249
- } catch (err) {
28250
- if (err instanceof NotFoundException$1) return RESOURCE_NOT_FOUND;
28251
- throw err;
28252
- }
28253
- }
28254
- const REST_API_WRITE_ONLY_PATHS = [
28255
- "Body",
28256
- "BodyS3Location",
28257
- "CloneFrom",
28258
- "FailOnWarnings",
28259
- "Mode",
28260
- "Parameters"
28261
- ];
28262
- async function importRestApi(input) {
28263
- if (!input.knownPhysicalId) return null;
28264
- try {
28265
- const resp = await this.apiGatewayClient.send(new GetRestApiCommand({ restApiId: input.knownPhysicalId }));
28266
- return {
28267
- physicalId: input.knownPhysicalId,
28268
- attributes: {
28269
- RestApiId: input.knownPhysicalId,
28270
- ...resp.rootResourceId !== void 0 ? { RootResourceId: resp.rootResourceId } : {}
28271
- }
28272
- };
28273
- } catch (err) {
28274
- if (err instanceof NotFoundException$1) return null;
28275
- throw err;
28276
- }
28277
- }
28278
-
28279
28331
  // src/provisioning/providers/apigateway/read-state.ts
28280
28332
  function canonicalizeDriftProperties$2(resourceType, properties) {
28281
28333
  if (resourceType === "AWS::ApiGateway::RestApi") {
@@ -28480,6 +28532,7 @@ async function importImpl$30(input) {
28480
28532
  var ApiGatewayProvider = class {
28481
28533
  apiGatewayClient;
28482
28534
  logger = getLogger().child("ApiGatewayProvider");
28535
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
28483
28536
  handledProperties = /* @__PURE__ */ new Map([
28484
28537
  ["AWS::ApiGateway::Account", /* @__PURE__ */ new Set(["CloudWatchRoleArn"])],
28485
28538
  ["AWS::ApiGateway::Authorizer", /* @__PURE__ */ new Set([
@@ -28673,8 +28726,9 @@ var ApiGatewayProvider = class {
28673
28726
  getRestApiAttribute(physicalId, attributeName) {
28674
28727
  return getRestApiAttribute.call(this, physicalId, attributeName);
28675
28728
  }
28676
- readCurrentStateRestApi(physicalId, properties) {
28677
- return readCurrentStateRestApi.call(this, physicalId, properties);
28729
+ async readCurrentStateRestApi(physicalId, properties, context, logicalId = physicalId) {
28730
+ const read = await readCurrentStateRestApi.call(this, physicalId, properties);
28731
+ return context?.afterOwnWrite === true ? settleRestApiPolicy.call(this, physicalId, logicalId, read, properties) : read;
28678
28732
  }
28679
28733
  importRestApi(input) {
28680
28734
  return importRestApi.call(this, input);
@@ -28697,7 +28751,8 @@ var ApiGatewayProvider = class {
28697
28751
  getDriftUnorderedPaths(resourceType) {
28698
28752
  return getDriftUnorderedPaths$6.call(this, resourceType);
28699
28753
  }
28700
- readCurrentState(physicalId, _logicalId, resourceType, properties) {
28754
+ readCurrentState(physicalId, _logicalId, resourceType, properties, context) {
28755
+ if (resourceType === "AWS::ApiGateway::RestApi") return this.readCurrentStateRestApi(physicalId, properties, context, _logicalId);
28701
28756
  return readCurrentState$28.call(this, physicalId, _logicalId, resourceType, properties);
28702
28757
  }
28703
28758
  readCurrentStateAuthorizer(physicalId, properties) {
@@ -50604,7 +50659,26 @@ async function updateAlias(logicalId, physicalId, resourceType, properties, mask
50604
50659
  }
50605
50660
 
50606
50661
  // src/provisioning/providers/kms/read-state.ts
50607
- async function readCurrentStateKey(physicalId) {
50662
+ async function readKeyPolicy(keyId) {
50663
+ const policyResp = await this.getClient().send(new GetKeyPolicyCommand({
50664
+ KeyId: keyId,
50665
+ PolicyName: "default"
50666
+ }));
50667
+ if (!policyResp.Policy) return "failed";
50668
+ try {
50669
+ return { value: JSON.parse(policyResp.Policy) };
50670
+ } catch {
50671
+ return { value: policyResp.Policy };
50672
+ }
50673
+ }
50674
+ async function settleKeyPolicy(keyId, logicalId, first, declared) {
50675
+ const asMember = (answer) => typeof answer === "object" && !policyDocumentMatchesDeclared(answer.value, declared) && isKmsDefaultKeyPolicy(answer.value) ? "absent" : answer;
50676
+ 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"));
50677
+ }
50678
+ function isKmsDefaultKeyPolicy(policy) {
50679
+ return typeof policy === "object" && policy !== null && policy["Id"] === "key-default-1";
50680
+ }
50681
+ async function readCurrentStateKey(physicalId, properties, context, logicalId = physicalId) {
50608
50682
  let resp;
50609
50683
  try {
50610
50684
  resp = await this.getClient().send(new DescribeKeyCommand({ KeyId: physicalId }));
@@ -50622,19 +50696,16 @@ async function readCurrentStateKey(physicalId) {
50622
50696
  if (md.MultiRegion !== void 0) result["MultiRegion"] = md.MultiRegion;
50623
50697
  if (md.Origin !== void 0) result["Origin"] = md.Origin;
50624
50698
  if (md.KeyId) {
50699
+ let keyPolicy;
50625
50700
  try {
50626
- const policyResp = await this.getClient().send(new GetKeyPolicyCommand({
50627
- KeyId: md.KeyId,
50628
- PolicyName: "default"
50629
- }));
50630
- if (policyResp.Policy) try {
50631
- result["KeyPolicy"] = JSON.parse(policyResp.Policy);
50632
- } catch {
50633
- result["KeyPolicy"] = policyResp.Policy;
50634
- }
50701
+ keyPolicy = await readKeyPolicy.call(this, md.KeyId);
50635
50702
  } catch (err) {
50636
50703
  if (err instanceof NotFoundException$2) return RESOURCE_NOT_FOUND;
50704
+ keyPolicy = memberReadFailure(err);
50637
50705
  }
50706
+ const declared = context?.afterOwnWrite === true ? declaredMemberDocument(properties?.["KeyPolicy"]) : void 0;
50707
+ if (declared !== void 0) keyPolicy = await settleKeyPolicy.call(this, md.KeyId, logicalId, keyPolicy, declared);
50708
+ if (typeof keyPolicy === "object") result["KeyPolicy"] = keyPolicy.value;
50638
50709
  if (md.KeySpec === void 0 || md.KeySpec === "SYMMETRIC_DEFAULT") try {
50639
50710
  const rotationResp = await this.getClient().send(new GetKeyRotationStatusCommand({ KeyId: md.KeyId }));
50640
50711
  result["EnableKeyRotation"] = rotationResp.KeyRotationEnabled ?? false;
@@ -50705,6 +50776,7 @@ var KMSProvider = class {
50705
50776
  createClient;
50706
50777
  providerRegion = ambientRegion();
50707
50778
  logger = getLogger().child("KMSProvider");
50779
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
50708
50780
  wrapCaughtError(mask, error, build) {
50709
50781
  const failure = describeAwsFailure(error);
50710
50782
  if (!(error instanceof Error) || !failure.redacted) return build(failure.detail);
@@ -50802,15 +50874,15 @@ var KMSProvider = class {
50802
50874
  deleteAlias(logicalId, physicalId, resourceType, context) {
50803
50875
  return deleteAlias.call(this, logicalId, physicalId, resourceType, context);
50804
50876
  }
50805
- async readCurrentState(physicalId, _logicalId, resourceType) {
50877
+ async readCurrentState(physicalId, _logicalId, resourceType, properties, context) {
50806
50878
  switch (resourceType) {
50807
- case "AWS::KMS::Key": return this.readCurrentStateKey(physicalId);
50879
+ case "AWS::KMS::Key": return this.readCurrentStateKey(physicalId, properties, context, _logicalId);
50808
50880
  case "AWS::KMS::Alias": return this.readCurrentStateAlias(physicalId);
50809
50881
  default: return;
50810
50882
  }
50811
50883
  }
50812
- readCurrentStateKey(physicalId) {
50813
- return readCurrentStateKey.call(this, physicalId);
50884
+ readCurrentStateKey(physicalId, properties, context, logicalId) {
50885
+ return readCurrentStateKey.call(this, physicalId, properties, context, logicalId);
50814
50886
  }
50815
50887
  getDriftUnknownPaths(resourceType) {
50816
50888
  if (resourceType === "AWS::KMS::Key") return ["BypassPolicyLockoutSafetyCheck", "PendingWindowInDays"];
@@ -54509,7 +54581,22 @@ async function deleteAccessPoint(logicalId, physicalId, resourceType, context) {
54509
54581
  }
54510
54582
 
54511
54583
  // src/provisioning/providers/efs/read-state.ts
54512
- async function readFileSystem(physicalId) {
54584
+ async function readFileSystemPolicy(physicalId) {
54585
+ let policy;
54586
+ try {
54587
+ policy = (await this.getClient().send(new DescribeFileSystemPolicyCommand({ FileSystemId: physicalId }))).Policy;
54588
+ } catch (err) {
54589
+ if (err.name === "PolicyNotFound") return "absent";
54590
+ throw err;
54591
+ }
54592
+ if (policy === void 0) return "failed";
54593
+ try {
54594
+ return { value: JSON.parse(policy) };
54595
+ } catch {
54596
+ return { value: policy };
54597
+ }
54598
+ }
54599
+ async function readFileSystem(physicalId, properties, context, logicalId = physicalId) {
54513
54600
  let fs;
54514
54601
  let listed;
54515
54602
  try {
@@ -54548,16 +54635,16 @@ async function readFileSystem(physicalId) {
54548
54635
  } catch (err) {
54549
54636
  if (err instanceof FileSystemNotFound) return RESOURCE_NOT_FOUND;
54550
54637
  }
54638
+ let policy;
54551
54639
  try {
54552
- const resp = await this.getClient().send(new DescribeFileSystemPolicyCommand({ FileSystemId: physicalId }));
54553
- if (resp.Policy !== void 0) try {
54554
- result["FileSystemPolicy"] = JSON.parse(resp.Policy);
54555
- } catch {
54556
- result["FileSystemPolicy"] = resp.Policy;
54557
- }
54640
+ policy = await readFileSystemPolicy.call(this, physicalId);
54558
54641
  } catch (err) {
54559
54642
  if (err instanceof FileSystemNotFound) return RESOURCE_NOT_FOUND;
54643
+ policy = memberReadFailure(err);
54560
54644
  }
54645
+ const declared = context?.afterOwnWrite === true ? declaredMemberDocument(properties?.["FileSystemPolicy"]) : void 0;
54646
+ 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"));
54647
+ if (typeof policy === "object") result["FileSystemPolicy"] = policy.value;
54561
54648
  result["FileSystemTags"] = normalizeAwsTagsToCfn(fs.Tags);
54562
54649
  return result;
54563
54650
  }
@@ -54672,6 +54759,7 @@ var EFSProvider = class {
54672
54759
  mountTargetCreateClient;
54673
54760
  providerRegion = ambientRegion();
54674
54761
  logger = getLogger().child("EFSProvider");
54762
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
54675
54763
  unconfirmedCreationTokens = /* @__PURE__ */ new Map();
54676
54764
  removalDefaults = /* @__PURE__ */ new Map([["AWS::EFS::FileSystem", /* @__PURE__ */ new Map([["BackupPolicy", { Status: "DISABLED" }], ["FileSystemProtection", { ReplicationOverwriteProtection: "ENABLED" }]])]]);
54677
54765
  handledProperties = /* @__PURE__ */ new Map([
@@ -54798,11 +54886,12 @@ var EFSProvider = class {
54798
54886
  deleteAccessPoint(logicalId, physicalId, resourceType, context) {
54799
54887
  return deleteAccessPoint.call(this, logicalId, physicalId, resourceType, context);
54800
54888
  }
54801
- readCurrentState(physicalId, _logicalId, resourceType) {
54889
+ readCurrentState(physicalId, _logicalId, resourceType, properties, context) {
54890
+ if (resourceType === "AWS::EFS::FileSystem") return this.readFileSystem(physicalId, properties, context, _logicalId);
54802
54891
  return readCurrentState$8.call(this, physicalId, _logicalId, resourceType);
54803
54892
  }
54804
- readFileSystem(physicalId) {
54805
- return readFileSystem.call(this, physicalId);
54893
+ readFileSystem(physicalId, properties, context, logicalId) {
54894
+ return readFileSystem.call(this, physicalId, properties, context, logicalId);
54806
54895
  }
54807
54896
  readAccessPoint(physicalId) {
54808
54897
  return readAccessPoint.call(this, physicalId);
@@ -60587,7 +60676,15 @@ async function deleteImpl$5(logicalId, physicalId, resourceType, _properties, co
60587
60676
  }
60588
60677
 
60589
60678
  // src/provisioning/providers/codebuild/read-state.ts
60590
- async function readCurrentState$3(physicalId, _logicalId, _resourceType) {
60679
+ async function readCurrentState$3(physicalId, logicalId, _resourceType, properties, context) {
60680
+ const read = await readProject.call(this, physicalId);
60681
+ const declared = context?.afterOwnWrite === true ? properties?.["Visibility"] : void 0;
60682
+ if (typeof declared !== "string" || declared === "" || read === RESOURCE_NOT_FOUND) return read;
60683
+ const asMember = (answer) => answer === RESOURCE_NOT_FOUND ? "failed" : { value: answer };
60684
+ 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"));
60685
+ return typeof settled === "object" ? settled.value : read;
60686
+ }
60687
+ async function readProject(physicalId) {
60591
60688
  let project;
60592
60689
  try {
60593
60690
  project = (await this.getClient().send(new BatchGetProjectsCommand({ names: [physicalId] }))).projects?.[0];
@@ -60779,6 +60876,7 @@ var CodeBuildProvider = class {
60779
60876
  createClient;
60780
60877
  providerRegion = ambientRegion();
60781
60878
  logger = getLogger().child("CodeBuildProvider");
60879
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
60782
60880
  disableCcApiFallback = true;
60783
60881
  handledProperties = /* @__PURE__ */ new Map([["AWS::CodeBuild::Project", /* @__PURE__ */ new Set([
60784
60882
  "Name",
@@ -60867,8 +60965,8 @@ var CodeBuildProvider = class {
60867
60965
  getAttribute(_physicalId, _resourceType, attributeName) {
60868
60966
  return Promise.resolve(attributeName);
60869
60967
  }
60870
- readCurrentState(physicalId, _logicalId, _resourceType) {
60871
- return readCurrentState$3.call(this, physicalId, _logicalId, _resourceType);
60968
+ readCurrentState(physicalId, _logicalId, _resourceType, properties, context) {
60969
+ return readCurrentState$3.call(this, physicalId, _logicalId, _resourceType, properties, context);
60872
60970
  }
60873
60971
  getDriftUnknownPaths() {
60874
60972
  return ["Source.Auth", "Triggers"];
@@ -65502,4 +65600,4 @@ var ACMCertificateProvider = class {
65502
65600
  };
65503
65601
 
65504
65602
  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 };
65505
- //# sourceMappingURL=provider-classes-DTrcboTq.js.map
65603
+ //# sourceMappingURL=provider-classes-KrOpD8Sp.js.map