@cdkd/cli 0.358.6 → 0.359.0

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 (58) hide show
  1. package/dist/{ambient-client-defaults-XFcZ_IMI.js → ambient-client-defaults-BNqC0q-Z.js} +3 -3
  2. package/dist/{ambient-client-defaults-XFcZ_IMI.js.map → ambient-client-defaults-BNqC0q-Z.js.map} +1 -1
  3. package/dist/{asg-provider-BP8oMti2.js → asg-provider-BDCUGWZV.js} +6 -6
  4. package/dist/{asg-provider-BP8oMti2.js.map → asg-provider-BDCUGWZV.js.map} +1 -1
  5. package/dist/cli.js +3 -3
  6. package/dist/{custom-resource-runtime-QfoyaxPW.js → custom-resource-runtime-DMkX_oQo.js} +6 -6
  7. package/dist/{custom-resource-runtime-QfoyaxPW.js.map → custom-resource-runtime-DMkX_oQo.js.map} +1 -1
  8. package/dist/{db-associated-roles-5I6qQ0C6.js → db-associated-roles-Bx5ML-MI.js} +2 -2
  9. package/dist/{db-associated-roles-5I6qQ0C6.js.map → db-associated-roles-Bx5ML-MI.js.map} +1 -1
  10. package/dist/{delete-started-B3fWZ4t9.js → delete-started-V5NHQ1O-.js} +4 -4
  11. package/dist/{delete-started-B3fWZ4t9.js.map → delete-started-V5NHQ1O-.js.map} +1 -1
  12. package/dist/{deploy-engine-DwpkRhxS.js → deploy-engine-BjSv27_M.js} +2111 -906
  13. package/dist/deploy-engine-BjSv27_M.js.map +1 -0
  14. package/dist/{ec2-termination-protection-CEAH5-4N.js → ec2-termination-protection-hc3MeuqF.js} +11 -7
  15. package/dist/ec2-termination-protection-hc3MeuqF.js.map +1 -0
  16. package/dist/{ecr-uri-CsP8Bfa_.js → ecr-uri-D1ijxg7D.js} +2 -2
  17. package/dist/{ecr-uri-CsP8Bfa_.js.map → ecr-uri-D1ijxg7D.js.map} +1 -1
  18. package/dist/{expected-bucket-owner-Lk8hXI9d.js → expected-bucket-owner-CQimj8gv.js} +2 -2
  19. package/dist/{expected-bucket-owner-Lk8hXI9d.js.map → expected-bucket-owner-CQimj8gv.js.map} +1 -1
  20. package/dist/{iam-role-provider-B6iCxpQV.js → iam-role-provider-b46RdZD5.js} +117 -68
  21. package/dist/iam-role-provider-b46RdZD5.js.map +1 -0
  22. package/dist/{image-plan-D-54O-Nq.js → image-plan-DtFbiJj5.js} +8 -8
  23. package/dist/{image-plan-D-54O-Nq.js.map → image-plan-DtFbiJj5.js.map} +1 -1
  24. package/dist/index.d.ts +4 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +5 -5
  27. package/dist/{logger-jcgg96uu.js → logger-CqKPJ_tV.js} +2 -2
  28. package/dist/{logger-jcgg96uu.js.map → logger-CqKPJ_tV.js.map} +1 -1
  29. package/dist/{neptune-provider-CpoLlf2R.js → neptune-provider-DiyWADaS.js} +7 -7
  30. package/dist/{neptune-provider-CpoLlf2R.js.map → neptune-provider-DiyWADaS.js.map} +1 -1
  31. package/dist/{program-DDysnPS0.js → program-Cdwgr3Yv.js} +882 -391
  32. package/dist/program-Cdwgr3Yv.js.map +1 -0
  33. package/dist/{provider-classes-CwIe3PGY.js → provider-classes-DhmwW7hI.js} +938 -514
  34. package/dist/provider-classes-DhmwW7hI.js.map +1 -0
  35. package/dist/{rds-provider-DJtzCaTQ.js → rds-provider-DpOZv_UG.js} +10 -10
  36. package/dist/{rds-provider-DJtzCaTQ.js.map → rds-provider-DpOZv_UG.js.map} +1 -1
  37. package/dist/{read-replica-eSaw4q1p.js → read-replica-Ct0oakPU.js} +3 -3
  38. package/dist/{read-replica-eSaw4q1p.js.map → read-replica-Ct0oakPU.js.map} +1 -1
  39. package/dist/{replacement-rules-DOyuWYSl.js → replacement-rules-CMnMy7rf.js} +3 -3
  40. package/dist/{replacement-rules-DOyuWYSl.js.map → replacement-rules-CMnMy7rf.js.map} +1 -1
  41. package/dist/{resource-deadline-Cd5Jfimc.js → resource-deadline-DlZTHrBj.js} +123 -122
  42. package/dist/resource-deadline-DlZTHrBj.js.map +1 -0
  43. package/dist/{restore-source-guard-YKb1WUF2.js → restore-source-guard-DIs6rqZm.js} +4 -4
  44. package/dist/{restore-source-guard-YKb1WUF2.js.map → restore-source-guard-DIs6rqZm.js.map} +1 -1
  45. package/dist/{run-cli-CyokhRcp.js → run-cli-BLZnjA32.js} +2 -2
  46. package/dist/{run-cli-CyokhRcp.js.map → run-cli-BLZnjA32.js.map} +1 -1
  47. package/dist/{diff-calculator-Drt5nkqk.js → settle-own-write-members-C1uPhq2z.js} +161 -16
  48. package/dist/settle-own-write-members-C1uPhq2z.js.map +1 -0
  49. package/dist/{version-DKW7jD3V.js → version-DyE_oClc.js} +2 -2
  50. package/dist/{version-DKW7jD3V.js.map → version-DyE_oClc.js.map} +1 -1
  51. package/package.json +1 -1
  52. package/dist/deploy-engine-DwpkRhxS.js.map +0 -1
  53. package/dist/diff-calculator-Drt5nkqk.js.map +0 -1
  54. package/dist/ec2-termination-protection-CEAH5-4N.js.map +0 -1
  55. package/dist/iam-role-provider-B6iCxpQV.js.map +0 -1
  56. package/dist/program-DDysnPS0.js.map +0 -1
  57. package/dist/provider-classes-CwIe3PGY.js.map +0 -1
  58. package/dist/resource-deadline-Cd5Jfimc.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-B6iCxpQV.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-jcgg96uu.js";
1
+ import { a as IamCreateClientCache, i as isEntityAlreadyExists, n as collectInlinePolicyNamesManagedBySiblings, r as iamEntityLeftByThisCreate, t as IAMRoleProvider } from "./iam-role-provider-b46RdZD5.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-CqKPJ_tV.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, 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-XFcZ_IMI.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-Cd5Jfimc.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-DKW7jD3V.js";
7
- import { gt as slowCcOperationTimeoutMs, n as isRefusedByName, r as markDeleteStarted } from "./delete-started-B3fWZ4t9.js";
8
- import { A as configItemId, B as SNS_DEFAULT_POLICY_ID, C as effectiveAnalyticsItem, D as eventBridgeEnabledOf, E as effectiveNotificationConfiguration, F as manualBucketDeletionClause, G as memberReadFailure, H as declaredPolicyDocument, I as mergeLegacySingular, J as settleDeclaredMember, K as policyDocumentMatchesDeclared, L as shownLifecycleRuleId, M as declaresNestedObjectLock, N as describeValue$1, O as caughtErrorName, P as isPlainObject$3, R as KMS_DEFAULT_KEY_POLICY_ID, S as EVENTBRIDGE_CONFIG_PATH, T as effectiveInventoryItem, U as efsPolicyMatchesDeclared, V as declaredMemberDocument, W as lambdaPermissionMatchesDeclared, X as attemptedPolicyDocument, Y as warnUnsettledMember, Z as policyContentKey, _ as canonicalizeItemList, a as resolveSecretDerivedPrincipals, b as lifecycleUsesFilterForm, c as lifecycleSettleTarget, d as takeLifecycleWrite, f as LIFECYCLE_DEFAULT_STATUS, g as canonicalizeBlock, h as LIFECYCLE_TAG_FILTERS_PATH, i as isResolvableSecretPrincipalList, j as declaresBucketObjectLock, k as coerceCfnNumber, l as recordLifecycleWrite, m as LIFECYCLE_RULE_PATH, n as runDestroyForStack, o as LIFECYCLE_BASELINE_REREAD_DELAYS_MS, p as LIFECYCLE_FILTER_PATH, q as reReadUntilSettled, r as holdsUnprovenSecretPrincipalToken, s as clearLifecycleWritesOf, t as canonicalizeIpv4Cidr, u as settleLifecycleRead, v as effectiveLifecycleConfiguration, w as effectiveIntelligentTieringItem, x as parseCfnTimestamp, y as lifecycleRuleScope, z as OWN_WRITE_REREAD_DELAYS_MS } from "./program-DDysnPS0.js";
9
- import { $ as sendTtlWaitingOutRateLimit, $c as findSdkUnwiredProperties, $n as sgProtocolKey, Al as renderNestedTemplateTreeDefect, At as S3_AUTO_DELETE_OBJECTS_TAG, B as declaredStreamTagsMember, Ci as replacedDeleteFailureVerdict, Cs as isWarmThroughputDecrease, Ct as INDEX_SETTLE_POLL_INTERVAL_MS, Cu as describeFileReadFailure, Dl as findNestedTemplateTreeDefect, Dt as relayedIndexBusyDelete, Du as resolveAssemblyPath, Et as maskedLogger, Eu as renderAssemblyPathEscape, Fo as s3BucketWebsiteUrl, Fr as REDACTED_DELETE_ADDRESS_SKIP_REASON, G as streamDeclaresTags, Gc as withheldAccountClause, Go as parseWebACLArn, Gt as chunks, I as DynamoDBGlobalTableProvider, Ir as isRedactedRecordedValue, J as streamTagsMatchDeclared, Jt as withApiLimit, K as streamMemberRefusals, Ka as waitForGoneAfterDelete, Kt as isAccessDeniedError, L as STREAM_POLICY_KEY, Ll as decodeListingKey, Lr as redactedDeleteAddressFields, Mo as s3BucketDomainName, Mt as isTruthyCfnBoolean, No as s3BucketDualStackDomainName, Ol as isAbsoluteAssetPath, Ot as waitForIndexesSettled, Pa as getCurrentResourceSecrets, Po as s3BucketRegionalDomainName, Ps as passedParameterClassesOf, Q as readTtlSpec, Qa as withIndeterminateGuard, Qn as cfnIngressPortValue, R as STREAM_TAGS_KEY, Rr as redactedDeleteAddressSkip, Ss as coerceWarmThroughput$1, St as DELETE_INDEX_WAIT_PROCEED_NOTE, Tl as stringifyValue, Ts as toFiniteNumber, Tt as deleteTableWithIndexBusyRetry, U as reverseMapStreamPolicy, V as planStreamMemberOps, W as streamDeclaresPolicy, Wa as waitForLambdaFunctionActive, Wc as accountArgs, X as isTtlRateLimited, Xn as siblingOwnedSgRuleIdentities, Y as isTtlAlreadyDisabled, Yl as rewriteTemplateAssetReferences, Yo as outputReferenceProvenanceOf, Yr as getCurrentProducerRegions, Z as planTimeToLive, Za as deleteSkipReason, Zn as withoutSiblingOwnedSgRules, _a as collectManagedPolicyArnsAttachedBySiblings, _r as earliestDefined, _t as beginDeleteWait, at as CONTRIBUTOR_INSIGHTS_KEY, ba as withoutSiblingAttachedArns, bt as resolveDynamoDbDeleteBudgetClock, cn as getCurrentNestedStackContext, co as APPSYNC_APIKEY_ARN_RESOURCE_PATH, cr as calculateResourceDrift, ct as planContributorInsightsOp, dt as reverseMapIndexContributorInsights, er as canonicalizeIpProtocolValue, et as planVectorIndexUpdates, fr as verbatimEchoDriftKeys, ft as reverseMapTableContributorInsights, ga as collectGroupsAddedBySiblings, gt as DYNAMODB_DELETE_POLL_COST_MS, ht as DYNAMODB_DELETE_MIN_RESOURCE_TIMEOUT_MS, in as revertNestedChildFromJournal, it as vectorIndexesShapeDetail, jo as s3BucketArn, jt as hasCdkAutoDeleteTag, kc as refuseMalformedNestedChildOutputs, kl as listNestedTemplateRows, kt as ECR_AUTO_DELETE_IMAGES_TAG, ln as withNestedStackContext, lo as maskedSecretSegment, lt as planIndexContributorInsightsOps, mt as DYNAMODB_DELETE_DEADLINE_MARGIN_MS, nl as withoutSdkUnwiredProperties, nt as vectorIndexesForCreate, ot as contributorInsightsRefusals, pt as stripIndexContributorInsights, q as streamPolicyMatchesDeclared, qt as lookupEachName, rt as vectorIndexesSettled, so as isSettledInstanceState, st as indexDeclaresContributorInsights, t as DeployEngine, ta as secretNamedAttributeNamesOf, tn as getNestedRevertRun, to as markWaitAbandoned, ts as getAccountInfo, tt as readbackVectorIndexes, ut as readContributorInsightsSpec, va as collectPrincipalsAttachingPolicy, vt as compensateRemovedDeletionProtection, ws as toCfnInteger, wt as TABLE_INDEX_NOUN, wu as displayAssemblyPath, xa as withoutSiblingOwned, xi as getStackRecords, xr as acquireIdempotencyToken, xs as WARM_THROUGHPUT_MEMBERS, xt as resolveDynamoDbDeleteBudgetMs, ya as isStoredExpression, yi as awaitInFlightSibling, yr as reserveStackCreateToken, yt as deleteBudgetKey, z as declaredStreamPolicyMember, zc as refuseMalformedResourcesForDestroy } from "./deploy-engine-DwpkRhxS.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-YKb1WUF2.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-CEAH5-4N.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, 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-BNqC0q-Z.js";
5
+ import { $ as isProceedDbStatus, $t as markAuxiliaryFailure, A as isPlainImportJson, At as canonicalizeRoute53QueryName, B as assertRegionMatch, Bt as createMaskedRetryLogger, C as isInsideWindow, Ct as SECRET_DERIVED_READ_LIVE, D as withoutServerErrorRetries, E as setBounded, Et as readPrincipalLists, F as refusalTypeShown, Ft as packCompositeId, G as logGroupProtectionSite, H as markNotGone, Ht as maskDeep, I as remedyLogicalId, K as observeThenDisableProtection, L as resolveExplicitPhysicalId, Lt as segmentAfterAnchor, M as isQuotableImportValue, Mt as compositeIdSeparatorRefusal, N as normalizeAwsTagsToCfn, Nt as compositeIdSkipResult, O as VALUE_NOT_SHOWN, Ot as recordedPrincipalsRepair, P as quotedRemedyLogicalId, Pt as logicalIdShown, R as DriftReadRefusedError, Rt as stateOrphanRecordRemedy, S as createAttemptKey, T as replayedSendWindow, Tt as onlySecretDerived, Ut as maskerOrIdentity, Vt as isSecretDerivedValue, W as deleteWithProtectionCompensation, Wt as withDerivedNameMasks, X as PROTECTION_FLIP_RETRY_WAIT_MS, Y as userPoolProtectionSite, Z as deleteAfterProtectionFlipWithFinalSnapshot, Zt as isAuxiliaryFailure, _ as AMBIGUOUS_LATCH_TTL_MS, _n as withPasteableAwsProfile, a as clearOnUpdateRemoval, b as RecentIdSet, bt as startInterruptWatch, c as removedTemplateKeys, dt as WITHHELD_AWS_COMMAND, en as markCreatedBeforeFailure, et as isTerminalDbWaitStatus, ft as isAwsCliLiteral, g as retractCreatedResource, ht as renderDisableCommand, it as protectionFlipKey, j as isPlainImportValue, jt as compositeIdFormatMessage, k as importRemedyCommand, l as withRemovalDefaults, m as reportCreatedResource, mt as protectedReplacementAdvice, n as enclosingDeadlineRemainingMs, nt as ProtectionFlipRegistry, ot as ElapsedBudget, pt as pasteableAwsCommand, q as rdsFamilyProtectionSite, qt as clearCreatedBeforeFailure, rt as isTerminalDeleteFailure, st as ElapsedBudgetRegistry, t as enclosingDeadlineExpired, tn as markSupersedesEarlierCreate, ut as UNNAMEABLE_ID_CLAUSE, v as AmbiguousCreateLatch, vn as injectiveKey, w as replayFollowedAmbiguousAttempt, wt as holdsSecretDerivedEntry, x as ambiguousAttemptLead, y as CREATION_DATE_SKEW_MARGIN_MS, yn as injectiveKeyPrefix, yt as isInterruptedWaitError, z as RESOURCE_NOT_FOUND, zt as createMaskedLogSinks } from "./resource-deadline-DlZTHrBj.js";
6
+ import { A as displayStackName, L as truncateCodePoints, 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-DyE_oClc.js";
7
+ import { gt as slowCcOperationTimeoutMs, n as isRefusedByName, r as markDeleteStarted } from "./delete-started-V5NHQ1O-.js";
8
+ import { $ as effectiveInventoryItem, A as tagListsMatch, B as LIFECYCLE_DEFAULT_STATUS, C as reconcileSgRules, D as singleSecurityGroupRuleId, E as sgRuleKey, F as clearLifecycleWritesOf, G as canonicalizeItemList, H as LIFECYCLE_RULE_PATH, I as lifecycleSettleTarget, J as lifecycleUsesFilterForm, K as effectiveLifecycleConfiguration, L as recordLifecycleWrite, M as declaredSgRulesRead, N as mergeDeclaredSgRules, O as stackIngressRuleHolder, P as LIFECYCLE_BASELINE_REREAD_DELAYS_MS, Q as effectiveIntelligentTieringItem, R as settleLifecycleRead, S as narrowIngressIpProtocol, T as securityGroupRuleMatchesCfnIngress, U as LIFECYCLE_TAG_FILTERS_PATH, V as LIFECYCLE_FILTER_PATH, W as canonicalizeBlock, X as EVENTBRIDGE_CONFIG_PATH, Y as parseCfnTimestamp, Z as effectiveAnalyticsItem, _ as flattenIpPermissions, a as resolveSecretDerivedPrincipals, at as declaresBucketObjectLock, b as isDefaultEgressRule, c as readSgIngressById, ct as isPlainObject$4, d as SG_RULE_PAGE_SIZE, dt as shownLifecycleRuleId, et as effectiveNotificationConfiguration, f as authorizeDefinitelyNotApplied, g as descriptionKey, h as comparableIngressIdentity, i as isResolvableSecretPrincipalList, it as configItemId, j as markCopiesAgreed, k as survivingRecordOfRuleId, l as siblingIdOwnedSgRules, lt as manualBucketDeletionClause, m as canonicalizeSgRuleProtocol, n as runDestroyForStack, nt as caughtErrorName, o as refuseRevertRevokingSiblingRules, ot as declaresNestedObjectLock, p as canonicalizeSgInlineRuleProtocols, q as lifecycleRuleScope, r as holdsUnprovenSecretPrincipalToken, rt as coerceCfnNumber, s as sgRuleDiffKey, st as describeValue$1, t as canonicalizeIpv4Cidr, tt as eventBridgeEnabledOf, u as SG_READBACK_RETRY_DELAY_MS, ut as mergeLegacySingular, v as ingressRuleIdentity, w as securityGroupReadbackDelays, x as isResendableSocketFailure, y as isConnectTimeout, z as takeLifecycleWrite } from "./program-Cdwgr3Yv.js";
9
+ import { $ as recordTagWrite, $r as redactedDeleteAddressSkip, Al as accountArgs, At as DELETE_INDEX_WAIT_PROCEED_NOTE, B as declaredStreamTagsMember, Ba as SNS_DEFAULT_POLICY_ID, Bt as isTruthyCfnBoolean, Cr as calculateResourceDrift, Ct as DYNAMODB_DELETE_MIN_RESOURCE_TIMEOUT_MS, Cu as decodeListingKey, Do as RecordedIdentityError, Dr as verbatimEchoDriftKeys, Dt as deleteBudgetKey, Eo as waitForGoneAfterDelete, Et as compensateRemovedDeletionProtection, Fa as withoutSiblingAttachedArns, Fo as deleteSkipReason, Fs as outputReferenceProvenanceOf, Ft as relayedIndexBusyDelete, Fu as rewriteTemplateAssetReferences, G as streamDeclaresTags, Ga as memberReadFailure, Go as isSettledInstanceState, Ha as declaredPolicyDocument, Hl as withoutSdkUnwiredProperties, I as DynamoDBGlobalTableProvider, Ia as withoutSiblingOwned, Ii as getStackRecords, Io as withIndeterminateGuard, Ir as acquireIdempotencyToken, It as waitForIndexesSettled, J as streamTagsMatchDeclared, Ja as settleDeclaredMember, Jo as maskedSecretSegment, K as streamMemberRefusals, Ka as policyDocumentMatchesDeclared, Ki as replacedDeleteFailureVerdict, Ko as APPSYNC_APIKEY_ARN_RESOURCE_PATH, L as STREAM_POLICY_KEY, La as KMS_DEFAULT_KEY_POLICY_ID, Lt as ECR_AUTO_DELETE_IMAGES_TAG, Ma as collectManagedPolicyArnsAttachedBySiblings, Mr as earliestDefined, Mt as TABLE_INDEX_NOUN, Na as collectPrincipalsAttachingPolicy, Nt as deleteTableWithIndexBusyRetry, Oo as RecordedIdentityMismatchError, Ot as resolveDynamoDbDeleteBudgetClock, Pa as isStoredExpression, Pi as awaitInFlightSibling, Pr as reserveStackCreateToken, Pt as maskedLogger, Q as isDynamoDBTableArnIn, Qr as redactedDeleteAddressFields, Qt as licensedNameHolder, R as STREAM_TAGS_KEY, Rt as S3_AUTO_DELETE_OBJECTS_TAG, St as DYNAMODB_DELETE_DEADLINE_MARGIN_MS, Tl as refuseMalformedResourcesForDestroy, Tt as beginDeleteWait, U as reverseMapStreamPolicy, Ua as efsPolicyMatchesDeclared, V as planStreamMemberOps, Va as declaredMemberDocument, Vs as getAccountInfo, W as streamDeclaresPolicy, Wa as lambdaPermissionMatchesDeclared, X as clearTagWrites, Xa as attemptedPolicyDocument, Xr as REDACTED_DELETE_ADDRESS_SKIP_REASON, Y as TAGS_BASELINE_REREAD_DELAYS_MS, Ya as warnUnsettledMember, Za as policyContentKey, Zr as isRedactedRecordedValue, _n as getCurrentNestedStackContext, _s as s3BucketArn, _t as planIndexContributorInsightsOps, ao as classifyHandleUrl, at as planTimeToLive, bc as passedParameterClassesOf, bs as s3BucketRegionalDomainName, bt as reverseMapTableContributorInsights, cc as coerceWarmThroughput$1, cr as siblingOwnedSgRuleIdentities, ct as planVectorIndexUpdates, dc as toFiniteNumber, dr as SG_RULE_ID_PATTERN, dt as vectorIndexesSettled, du as stringifyValue, en as chunks, et as settleWrittenTags, fd as renderAssemblyPathEscape, fr as cfnIngressPortValue, ft as vectorIndexesShapeDetail, ga as secretNamedAttributeNamesOf, gt as planContributorInsightsOp, gu as renderNestedTemplateTreeDefect, hl as refuseMalformedNestedChildOutputs, ht as indexDeclaresContributorInsights, hu as listNestedTemplateRows, io as WaitConditionSignalStore, it as isTtlRateLimited, ja as collectGroupsAddedBySiblings, jl as withheldAccountClause, js as parseWebACLArn, jt as INDEX_SETTLE_POLL_INTERVAL_MS, ko as assertRecordedIdentity, kt as resolveDynamoDbDeleteBudgetMs, lc as isWarmThroughputDecrease, ld as describeFileReadFailure, lt as readbackVectorIndexes, mo as getCurrentResourceSecrets, mr as sgProtocolKey, mt as contributorInsightsRefusals, mu as isAbsoluteAssetPath, nn as lookupEachName, nt as takeTagWrite, oo as evaluateSignals, ot as readTtlSpec, pd as resolveAssemblyPath, pn as revertNestedChildFromJournal, pr as recordedSgRuleId, pt as CONTRIBUTOR_INSIGHTS_KEY, pu as findNestedTemplateTreeDefect, q as streamPolicyMatchesDeclared, qa as reReadUntilSettled, rn as withApiLimit, ro as LEGACY_HANDLE_ID_PREFIX, rt as isTtlAlreadyDisabled, sc as WARM_THROUGHPUT_MEMBERS, st as sendTtlWaitingOutRateLimit, t as DeployEngine, tn as isAccessDeniedError, uc as toCfnInteger, ud as displayAssemblyPath, ui as getCurrentProducerRegions, un as getNestedRevertRun, ur as withoutSiblingOwnedSgRules, ut as vectorIndexesForCreate, vn as withNestedStackContext, vs as s3BucketDomainName, vt as readContributorInsightsSpec, wo as waitForLambdaFunctionActive, wt as DYNAMODB_DELETE_POLL_COST_MS, xs as s3BucketWebsiteUrl, xt as stripIndexContributorInsights, ys as s3BucketDualStackDomainName, yt as reverseMapIndexContributorInsights, z as declaredStreamPolicyMember, za as OWN_WRITE_REREAD_DELAYS_MS, zl as findSdkUnwiredProperties, zo as markWaitAbandoned, zt as hasCdkAutoDeleteTag } from "./deploy-engine-BjSv27_M.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-DIs6rqZm.js";
11
+ import { W as timePhase, _ as onlySecretReferencesDiffer, a as reDisableInstanceApiTermination, c as resolvedResourceTimeoutMs, f as markRefusedBeforeApplying, i as observeThenDisableInstanceApiTermination, j as withRetry, n as ec2InstanceProtectionSite, o as reEnableInstanceApiTermination, r as isTerminationProtectionPropagationError, s as resolvedPerTypeResourceTimeoutMs, u as getPriorAttempts, v as unchangedBehindSecretReference } from "./ec2-termination-protection-hc3MeuqF.js";
12
+ import { a as principalOwnWriteMembers, c as stringListMember, d as planSubscriptionAttributes, n as declaredStringList, o as settleOwnWriteMembers, u as normalizeRecordName } from "./settle-own-write-members-C1uPhq2z.js";
12
13
  import { n as canonicalizeRegion, r as derivePartitionAndUrlSuffix } from "./aws-partition-DA0r2sr-.js";
13
14
  import { f as ambientRegion, r as awsEndpointOverrideActive } from "./aws-client-defaults-DAebi99J.js";
14
- import { n as planSubscriptionAttributes } from "./diff-calculator-Drt5nkqk.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-DOyuWYSl.js";
16
- import { RDSProvider } from "./rds-provider-DJtzCaTQ.js";
17
- import { NeptuneProvider } from "./neptune-provider-CpoLlf2R.js";
18
- import { ASGProvider } from "./asg-provider-BP8oMti2.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-CMnMy7rf.js";
16
+ import { RDSProvider } from "./rds-provider-DpOZv_UG.js";
17
+ import { NeptuneProvider } from "./neptune-provider-DiyWADaS.js";
18
+ import { ASGProvider } from "./asg-provider-BDCUGWZV.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";
@@ -537,7 +537,7 @@ async function deleteImpl$40(logicalId, physicalId, resourceType, properties, co
537
537
 
538
538
  // src/provisioning/providers/iam-policy/read-state.ts
539
539
  const TARGET_READ_CONCURRENCY = 5;
540
- async function readCurrentState$41(physicalId, _logicalId, _resourceType, properties, context) {
540
+ async function readCurrentState$41(physicalId, logicalId, _resourceType, properties, context) {
541
541
  if (!properties) return void 0;
542
542
  const policyDocument = properties["PolicyDocument"];
543
543
  if (!policyDocument) return void 0;
@@ -576,8 +576,12 @@ async function readCurrentState$41(physicalId, _logicalId, _resourceType, proper
576
576
  throw err;
577
577
  }
578
578
  };
579
+ const declared = context?.afterOwnWrite === true ? declaredMemberDocument(policyDocument) : void 0;
579
580
  const reads = [];
580
- for (let i = 0; i < readTargets.length; i += TARGET_READ_CONCURRENCY) reads.push(...await Promise.all(readTargets.slice(i, i + TARGET_READ_CONCURRENCY).map(readOne)));
581
+ if (declared !== void 0) {
582
+ const unsettled = () => warnUnsettledMember(this.logger, logicalId, "AWS::IAM::Policy", "PolicyDocument");
583
+ reads.push(...await Promise.all(readTargets.map((target) => settleTargetCopy.call(this, target, policyName, declared, unsettled))));
584
+ } else for (let i = 0; i < readTargets.length; i += TARGET_READ_CONCURRENCY) reads.push(...await Promise.all(readTargets.slice(i, i + TARGET_READ_CONCURRENCY).map(readOne)));
581
585
  const documents = reads.flatMap((r) => "document" in r ? [r.document] : []);
582
586
  if (documents.length === 0) return RESOURCE_NOT_FOUND;
583
587
  if (!reads.some((r) => "missing" in r) && documents.every((d) => d === void 0)) return void 0;
@@ -589,7 +593,8 @@ async function readCurrentState$41(physicalId, _logicalId, _resourceType, proper
589
593
  }).length === 0;
590
594
  const baseline = context?.driftBaseline?.["PolicyDocument"] !== void 0 ? context.driftBaseline["PolicyDocument"] : parseRecordedDocument(policyDocument);
591
595
  let liveDocument = documents[0];
592
- if (documents.some((d) => !comparatorEqual(liveDocument, d) || !comparatorEqual(d, liveDocument))) {
596
+ const copiesDiffer = documents.some((d) => !comparatorEqual(liveDocument, d) || !comparatorEqual(d, liveDocument));
597
+ if (copiesDiffer) {
593
598
  if (holdsSecretLeaf(baseline)) throw new DriftReadRefusedError(`the copies of inline policy ${policyName} differ across its principals and its recorded document holds a secret reference, so cdkd cannot tell which copy was edited — inspect each principal's copy by hand`);
594
599
  const edited = documents.findIndex((d) => !comparatorEqual(baseline, d));
595
600
  if (edited !== -1) liveDocument = documents[edited];
@@ -605,8 +610,33 @@ async function readCurrentState$41(physicalId, _logicalId, _resourceType, proper
605
610
  if (roles) result["Roles"] = echo("role", roles);
606
611
  if (groups) result["Groups"] = echo("group", groups);
607
612
  if (users) result["Users"] = echo("user", users);
613
+ if (!copiesDiffer && readTargets.length === allTargets.length) markCopiesAgreed(result);
608
614
  return result;
609
615
  }
616
+ async function settleTargetCopy(target, policyName, declared, unsettled) {
617
+ const read = async () => {
618
+ try {
619
+ return { value: this.decodePolicyDocument(await getTargetPolicyDocument.call(this, target, policyName)) };
620
+ } catch (err) {
621
+ if (err instanceof NoSuchEntityException) return "absent";
622
+ throw err;
623
+ }
624
+ };
625
+ let first;
626
+ let firstError;
627
+ try {
628
+ first = await read();
629
+ } catch (err) {
630
+ firstError = err;
631
+ first = memberReadFailure(err);
632
+ }
633
+ const settled = await settleDeclaredMember(first, read, (value) => policyDocumentMatchesDeclared(value, declared), declared, this.ownWriteRereadDelaysMs, unsettled);
634
+ if (typeof settled !== "object") throw firstError;
635
+ return {
636
+ target,
637
+ document: settled.value
638
+ };
639
+ }
610
640
  async function getTargetPolicyDocument(target, policyName) {
611
641
  switch (target.kind) {
612
642
  case "role": return (await this.iamClient.send(new GetRolePolicyCommand({
@@ -665,6 +695,7 @@ var IAMPolicyProvider = class {
665
695
  this.logger.debug(mask(build(mask(failure.detail)).message));
666
696
  return markRedactedCause(build(`${mask(failure.summary)}${relayedNameCollision(failure.detail)}`));
667
697
  }
698
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
668
699
  handledProperties = /* @__PURE__ */ new Map([["AWS::IAM::Policy", /* @__PURE__ */ new Set([
669
700
  "PolicyName",
670
701
  "PolicyDocument",
@@ -899,14 +930,18 @@ async function update$41(logicalId, physicalId, resourceType, properties, previo
899
930
  const createResult = await this.create(logicalId, resourceType, properties, { maskSecrets: log.mask });
900
931
  let orphanReason;
901
932
  try {
902
- const deleteResult = await this.delete(logicalId, physicalId, resourceType, previousProperties, { maskSecrets: log.mask });
933
+ const deleteResult = await this.delete(logicalId, physicalId, resourceType, previousProperties, {
934
+ maskSecrets: log.mask,
935
+ ...context?.recordedAttributes && { recordedAttributes: context.recordedAttributes }
936
+ });
903
937
  if (deleteResult?.outcome === "skipped") {
904
938
  orphanReason = log.mask(`old managed policy ${v(physicalId)} was not deleted: ${deleteResult.reason}`);
905
939
  log.warn(`Skipped deleting old managed policy ${v(physicalId)} during replacement: ${deleteResult.reason}. The old policy may be orphaned and require manual cleanup.`);
906
940
  }
907
941
  } catch (error) {
908
- orphanReason = log.mask(`old managed policy ${v(physicalId)} could not be deleted: ${safeStringify(error)}`);
909
- log.warn(`Failed to delete old managed policy ${v(physicalId)} during replacement: ${v(safeStringify(error))}. The old policy may be orphaned and require manual cleanup.`);
942
+ orphanReason = log.mask(error instanceof RecordedIdentityMismatchError ? `old managed policy ${v(physicalId)} was not deleted: the managed policy now holding that name is not the one cdkd created (its ${error.attribute} differs from the recorded one), so cdkd left it alone` : `old managed policy ${v(physicalId)} could not be deleted: ${safeStringify(error)}`);
943
+ if (error instanceof RecordedIdentityMismatchError) log.warn(`${orphanReason}.`);
944
+ else log.warn(`Failed to delete old managed policy ${v(physicalId)} during replacement: ${v(safeStringify(error))}. The old policy may be orphaned and require manual cleanup.`);
910
945
  }
911
946
  const base = {
912
947
  physicalId: createResult.physicalId,
@@ -1022,8 +1057,10 @@ async function deleteImpl$39(logicalId, physicalId, resourceType, _properties, c
1022
1057
  this.logger.debug(mask(`Deleting IAM managed policy ${logicalId}: ${physicalId}`));
1023
1058
  const progress = { stripped: false };
1024
1059
  try {
1060
+ const readPolicyId = async () => policyIdentityToken((await this.iamClient.send(new GetPolicyCommand({ PolicyArn: physicalId }))).Policy?.PolicyId);
1061
+ let liveId;
1025
1062
  try {
1026
- await this.iamClient.send(new GetPolicyCommand({ PolicyArn: physicalId }));
1063
+ liveId = await readPolicyId();
1027
1064
  } catch (error) {
1028
1065
  if (error instanceof NoSuchEntityException) {
1029
1066
  await this.goneOnDelete(logicalId, physicalId, resourceType, context, mask);
@@ -1031,11 +1068,21 @@ async function deleteImpl$39(logicalId, physicalId, resourceType, _properties, c
1031
1068
  }
1032
1069
  throw error;
1033
1070
  }
1071
+ await assertRecordedIdentity({
1072
+ label: "IAM managed policy",
1073
+ resourceType,
1074
+ logicalId,
1075
+ physicalId,
1076
+ liveId,
1077
+ reread: readPolicyId,
1078
+ context
1079
+ });
1034
1080
  await this.detachAllPrincipals(physicalId, progress);
1035
1081
  await this.deleteAllNonDefaultVersions(physicalId);
1036
1082
  await this.iamClient.send(new DeletePolicyCommand({ PolicyArn: physicalId }));
1037
1083
  this.logger.debug(`Successfully deleted IAM managed policy ${logicalId}`);
1038
1084
  } catch (error) {
1085
+ if (error instanceof RecordedIdentityError) throw error;
1039
1086
  if (error instanceof NoSuchEntityException) {
1040
1087
  await this.goneOnDelete(logicalId, physicalId, resourceType, context, mask);
1041
1088
  return;
@@ -1049,7 +1096,7 @@ async function deleteImpl$39(logicalId, physicalId, resourceType, _properties, c
1049
1096
 
1050
1097
  // src/provisioning/providers/iam-managed-policy/read-state.ts
1051
1098
  const AWS_MANAGED_POLICY_ARN_RE = /^arn:aws[a-z0-9-]*:iam::aws:/;
1052
- async function readCurrentState$40(physicalId, _logicalId, _resourceType, properties, context) {
1099
+ async function readCurrentState$40(physicalId, logicalId, _resourceType, properties, context) {
1053
1100
  let policy;
1054
1101
  try {
1055
1102
  policy = (await this.iamClient.send(new GetPolicyCommand({ PolicyArn: physicalId }))).Policy;
@@ -1063,38 +1110,13 @@ async function readCurrentState$40(physicalId, _logicalId, _resourceType, proper
1063
1110
  result["Description"] = policy.Description ?? "";
1064
1111
  if (policy.Path !== void 0) result["Path"] = policy.Path;
1065
1112
  if (policy.DefaultVersionId) try {
1066
- const doc = (await this.iamClient.send(new GetPolicyVersionCommand({
1067
- PolicyArn: physicalId,
1068
- VersionId: policy.DefaultVersionId
1069
- }))).PolicyVersion?.Document;
1070
- if (typeof doc === "string") try {
1071
- result["PolicyDocument"] = JSON.parse(decodeURIComponent(doc));
1072
- } catch {
1073
- result["PolicyDocument"] = doc;
1074
- }
1113
+ const doc = await readDefaultVersionDocument.call(this, physicalId, policy.DefaultVersionId);
1114
+ if (doc !== void 0) result["PolicyDocument"] = doc;
1075
1115
  } catch (err) {
1076
1116
  if (!(err instanceof NoSuchEntityException)) throw err;
1077
1117
  }
1078
1118
  try {
1079
- const groups = [];
1080
- const roles = [];
1081
- const users = [];
1082
- let marker;
1083
- while (true) {
1084
- const resp = await this.iamClient.send(new ListEntitiesForPolicyCommand({
1085
- PolicyArn: physicalId,
1086
- ...marker ? { Marker: marker } : {}
1087
- }));
1088
- for (const g of resp.PolicyGroups ?? []) if (g.GroupName) groups.push(g.GroupName);
1089
- for (const r of resp.PolicyRoles ?? []) if (r.RoleName) roles.push(r.RoleName);
1090
- for (const u of resp.PolicyUsers ?? []) if (u.UserName) users.push(u.UserName);
1091
- if (!resp.IsTruncated) break;
1092
- marker = resp.Marker;
1093
- }
1094
- const own = (key, names) => withoutSiblingOwned(names, collectPrincipalsAttachingPolicy(physicalId, context, key), properties, key);
1095
- result["Groups"] = own("Groups", groups);
1096
- result["Roles"] = own("Roles", roles);
1097
- result["Users"] = own("Users", users);
1119
+ Object.assign(result, await readAttachments.call(this, physicalId, properties, context));
1098
1120
  } catch (err) {
1099
1121
  if (!(err instanceof NoSuchEntityException)) throw err;
1100
1122
  }
@@ -1117,8 +1139,79 @@ async function readCurrentState$40(physicalId, _logicalId, _resourceType, proper
1117
1139
  } catch (err) {
1118
1140
  if (!(err instanceof NoSuchEntityException)) throw err;
1119
1141
  }
1142
+ if (context?.afterOwnWrite === true && properties !== void 0) await settleOwnWriteMembers(result, managedPolicyOwnWriteMembers.call(this, physicalId, properties, context), this.ownWriteRereadDelaysMs, (key) => warnUnsettledMember(this.logger, logicalId, "AWS::IAM::ManagedPolicy", key));
1120
1143
  return result;
1121
1144
  }
1145
+ async function readDefaultVersionDocument(physicalId, versionId) {
1146
+ const doc = (await this.iamClient.send(new GetPolicyVersionCommand({
1147
+ PolicyArn: physicalId,
1148
+ VersionId: versionId
1149
+ }))).PolicyVersion?.Document;
1150
+ if (typeof doc !== "string") return void 0;
1151
+ try {
1152
+ return JSON.parse(decodeURIComponent(doc));
1153
+ } catch {
1154
+ return doc;
1155
+ }
1156
+ }
1157
+ async function readAttachments(physicalId, properties, context) {
1158
+ const groups = [];
1159
+ const roles = [];
1160
+ const users = [];
1161
+ let marker;
1162
+ while (true) {
1163
+ const resp = await this.iamClient.send(new ListEntitiesForPolicyCommand({
1164
+ PolicyArn: physicalId,
1165
+ ...marker ? { Marker: marker } : {}
1166
+ }));
1167
+ for (const g of resp.PolicyGroups ?? []) if (g.GroupName) groups.push(g.GroupName);
1168
+ for (const r of resp.PolicyRoles ?? []) if (r.RoleName) roles.push(r.RoleName);
1169
+ for (const u of resp.PolicyUsers ?? []) if (u.UserName) users.push(u.UserName);
1170
+ if (!resp.IsTruncated) break;
1171
+ marker = resp.Marker;
1172
+ }
1173
+ const own = (key, names) => withoutSiblingOwned(names, collectPrincipalsAttachingPolicy(physicalId, context, key), properties, key);
1174
+ return {
1175
+ Groups: own("Groups", groups),
1176
+ Roles: own("Roles", roles),
1177
+ Users: own("Users", users)
1178
+ };
1179
+ }
1180
+ function managedPolicyOwnWriteMembers(physicalId, properties, context) {
1181
+ const members = [];
1182
+ const document = declaredMemberDocument(properties["PolicyDocument"]);
1183
+ if (document !== void 0) members.push({
1184
+ key: "PolicyDocument",
1185
+ declared: document,
1186
+ matches: (value) => policyDocumentMatchesDeclared(value, document),
1187
+ read: async () => {
1188
+ const versionId = (await this.iamClient.send(new GetPolicyCommand({ PolicyArn: physicalId }))).Policy?.DefaultVersionId;
1189
+ if (!versionId) return "failed";
1190
+ const value = await readDefaultVersionDocument.call(this, physicalId, versionId);
1191
+ return value === void 0 ? "failed" : { value };
1192
+ }
1193
+ });
1194
+ const rounds = [];
1195
+ const served = {
1196
+ Groups: 0,
1197
+ Roles: 0,
1198
+ Users: 0
1199
+ };
1200
+ for (const key of [
1201
+ "Groups",
1202
+ "Roles",
1203
+ "Users"
1204
+ ]) {
1205
+ const declared = declaredStringList(properties[key]);
1206
+ if (declared === void 0) continue;
1207
+ members.push(stringListMember(key, declared, async () => {
1208
+ const round = served[key]++;
1209
+ rounds[round] ??= readAttachments.call(this, physicalId, properties, context);
1210
+ return { value: (await rounds[round])[key] };
1211
+ }));
1212
+ }
1213
+ return members;
1214
+ }
1122
1215
  async function importImpl$39(input) {
1123
1216
  const explicit = resolveExplicitPhysicalId(input, "ManagedPolicyName");
1124
1217
  if (explicit) {
@@ -1152,6 +1245,7 @@ var IAMManagedPolicyProvider = class {
1152
1245
  iamClient;
1153
1246
  createClient = new IamCreateClientCache(() => this.iamClient);
1154
1247
  logger = getLogger().child("IAMManagedPolicyProvider");
1248
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
1155
1249
  wrapMaskedError(mask, error, build) {
1156
1250
  const failure = describeAwsFailure(error);
1157
1251
  if (!(error instanceof Error)) return build(mask(failure.detail));
@@ -1196,6 +1290,13 @@ var IAMManagedPolicyProvider = class {
1196
1290
  return managedPolicyAttributes(physicalId, resp.Policy)[attributeName];
1197
1291
  }
1198
1292
  }
1293
+ getDriftUnorderedPaths(resourceType) {
1294
+ return resourceType === "AWS::IAM::ManagedPolicy" ? [
1295
+ "Roles",
1296
+ "Users",
1297
+ "Groups"
1298
+ ] : [];
1299
+ }
1199
1300
  readCurrentState(physicalId, logicalId, resourceType, properties, context) {
1200
1301
  return readCurrentState$40.call(this, physicalId, logicalId, resourceType, properties, context);
1201
1302
  }
@@ -1477,6 +1578,7 @@ var IAMInstanceProfileProvider = class {
1477
1578
  iamClient;
1478
1579
  createClient = new IamCreateClientCache(() => this.iamClient);
1479
1580
  logger = getLogger().child("IAMInstanceProfileProvider");
1581
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
1480
1582
  wrapMaskedError(mask, error, build) {
1481
1583
  const failure = describeAwsFailure(error);
1482
1584
  if (!(error instanceof Error)) return build(mask(failure.detail));
@@ -1573,7 +1675,10 @@ var IAMInstanceProfileProvider = class {
1573
1675
  log.debug(`Successfully created IAM instance profile ${logicalId}: ${v(instanceProfileName)}`);
1574
1676
  return {
1575
1677
  physicalId: instanceProfileName,
1576
- attributes: { Arn: profile?.Arn }
1678
+ attributes: {
1679
+ Arn: profile?.Arn,
1680
+ ...definedAttributes({ InstanceProfileId: createdProfileIdentity })
1681
+ }
1577
1682
  };
1578
1683
  } catch (error) {
1579
1684
  const cause = error instanceof Error ? error : void 0;
@@ -1624,10 +1729,14 @@ var IAMInstanceProfileProvider = class {
1624
1729
  log.debug(`Added role ${v(roleName)} to instance profile ${v(physicalId)}`);
1625
1730
  }
1626
1731
  log.debug(`Successfully updated IAM instance profile ${logicalId}`);
1732
+ const getResponse = await this.iamClient.send(new GetInstanceProfileCommand({ InstanceProfileName: physicalId }));
1627
1733
  return {
1628
1734
  physicalId,
1629
1735
  wasReplaced: false,
1630
- attributes: { Arn: (await this.iamClient.send(new GetInstanceProfileCommand({ InstanceProfileName: physicalId }))).InstanceProfile?.Arn }
1736
+ attributes: {
1737
+ Arn: getResponse.InstanceProfile?.Arn,
1738
+ ...definedAttributes({ InstanceProfileId: instanceProfileIdentityToken(getResponse.InstanceProfile?.InstanceProfileId) })
1739
+ }
1631
1740
  };
1632
1741
  } catch (error) {
1633
1742
  const cause = error instanceof Error ? error : void 0;
@@ -1650,7 +1759,20 @@ var IAMInstanceProfileProvider = class {
1650
1759
  try {
1651
1760
  let roles = [];
1652
1761
  try {
1653
- roles = (await this.iamClient.send(new GetInstanceProfileCommand({ InstanceProfileName: physicalId }))).InstanceProfile?.Roles?.map((r) => r.RoleName).filter((name) => !!name) || [];
1762
+ const readProfile = async () => {
1763
+ const response = await this.iamClient.send(new GetInstanceProfileCommand({ InstanceProfileName: physicalId }));
1764
+ roles = response.InstanceProfile?.Roles?.map((r) => r.RoleName).filter((name) => !!name) || [];
1765
+ return response.InstanceProfile?.InstanceProfileName?.toLowerCase() === physicalId.toLowerCase() ? response.InstanceProfile.InstanceProfileId : void 0;
1766
+ };
1767
+ await assertRecordedIdentity({
1768
+ label: "IAM instance profile",
1769
+ resourceType,
1770
+ logicalId,
1771
+ physicalId,
1772
+ liveId: await readProfile(),
1773
+ reread: readProfile,
1774
+ context
1775
+ });
1654
1776
  } catch (error) {
1655
1777
  if (error instanceof NoSuchEntityException) {
1656
1778
  const clientRegion = await this.iamClient.config.region();
@@ -1679,6 +1801,7 @@ var IAMInstanceProfileProvider = class {
1679
1801
  this.logGoneOnDelete(logicalId, physicalId, context, log);
1680
1802
  return;
1681
1803
  }
1804
+ if (error instanceof RecordedIdentityError) throw error;
1682
1805
  const cause = error instanceof Error ? error : void 0;
1683
1806
  const { mask } = log;
1684
1807
  const failure = this.wrapMaskedError(mask, error, (text) => new ProvisioningError(mask(`Failed to delete IAM instance profile ${logicalId}: ${text}`), resourceType, logicalId, physicalId, cause));
@@ -1724,7 +1847,7 @@ var IAMInstanceProfileProvider = class {
1724
1847
  if (token === void 0) throw new Error("IAM returned no InstanceProfileId");
1725
1848
  return token;
1726
1849
  }
1727
- async readCurrentState(physicalId, _logicalId, _resourceType) {
1850
+ async readCurrentState(physicalId, logicalId, _resourceType, properties, context) {
1728
1851
  let profile;
1729
1852
  try {
1730
1853
  profile = (await this.iamClient.send(new GetInstanceProfileCommand({ InstanceProfileName: physicalId }))).InstanceProfile;
@@ -1736,7 +1859,12 @@ var IAMInstanceProfileProvider = class {
1736
1859
  const result = {};
1737
1860
  if (profile.InstanceProfileName !== void 0) result["InstanceProfileName"] = profile.InstanceProfileName;
1738
1861
  if (profile.Path !== void 0) result["Path"] = profile.Path;
1739
- result["Roles"] = (profile.Roles ?? []).map((r) => r.RoleName).filter((n) => !!n);
1862
+ result["Roles"] = profileRoleNames(profile);
1863
+ const declared = context?.afterOwnWrite === true ? declaredStringList(properties?.["Roles"]) : void 0;
1864
+ if (declared !== void 0) await settleOwnWriteMembers(result, [stringListMember("Roles", declared, async () => {
1865
+ const resp = await this.iamClient.send(new GetInstanceProfileCommand({ InstanceProfileName: physicalId }));
1866
+ return resp.InstanceProfile ? { value: profileRoleNames(resp.InstanceProfile) } : "failed";
1867
+ })], this.ownWriteRereadDelaysMs, (key) => warnUnsettledMember(this.logger, logicalId, "AWS::IAM::InstanceProfile", key));
1740
1868
  return result;
1741
1869
  }
1742
1870
  async import(input) {
@@ -1745,7 +1873,10 @@ var IAMInstanceProfileProvider = class {
1745
1873
  const resp = await this.iamClient.send(new GetInstanceProfileCommand({ InstanceProfileName: explicit }));
1746
1874
  return {
1747
1875
  physicalId: explicit,
1748
- attributes: definedAttributes({ Arn: resp.InstanceProfile?.Arn })
1876
+ attributes: definedAttributes({
1877
+ Arn: resp.InstanceProfile?.Arn,
1878
+ InstanceProfileId: instanceProfileIdentityToken(resp.InstanceProfile?.InstanceProfileId)
1879
+ })
1749
1880
  };
1750
1881
  } catch (err) {
1751
1882
  if (err instanceof NoSuchEntityException) return null;
@@ -1754,6 +1885,9 @@ var IAMInstanceProfileProvider = class {
1754
1885
  return null;
1755
1886
  }
1756
1887
  };
1888
+ function profileRoleNames(profile) {
1889
+ return (profile.Roles ?? []).map((r) => r.RoleName).filter((n) => !!n);
1890
+ }
1757
1891
 
1758
1892
  // src/provisioning/providers/iam-access-key-provider.ts
1759
1893
  const ACCESS_KEY_ID_PATTERN = /^AKIA[A-Z0-9]{16}$/;
@@ -2299,7 +2433,10 @@ async function createUser(logicalId, resourceType, properties, log) {
2299
2433
  log.debug(`Successfully created IAM user ${logicalId}: ${v(userName)}`);
2300
2434
  return {
2301
2435
  physicalId: userName,
2302
- attributes: { Arn: user?.Arn }
2436
+ attributes: {
2437
+ Arn: user?.Arn,
2438
+ ...definedAttributes({ UserId: createdUserIdentity })
2439
+ }
2303
2440
  };
2304
2441
  } catch (error) {
2305
2442
  const cause = error instanceof Error ? error : void 0;
@@ -2382,10 +2519,14 @@ async function updateUser(logicalId, physicalId, resourceType, properties, previ
2382
2519
  await this.updateUserManagedPolicies(physicalId, properties["ManagedPolicyArns"], previousProperties["ManagedPolicyArns"], log);
2383
2520
  await this.updateUserGroups(physicalId, groups.next.Groups, groups.prev.Groups, log);
2384
2521
  await this.updateUserInlinePolicies(physicalId, properties["Policies"], previousProperties["Policies"], log, claimed);
2522
+ const getUserResponse = await this.iamClient.send(new GetUserCommand({ UserName: physicalId }));
2385
2523
  return {
2386
2524
  physicalId,
2387
2525
  wasReplaced: false,
2388
- attributes: { Arn: (await this.iamClient.send(new GetUserCommand({ UserName: physicalId }))).User?.Arn }
2526
+ attributes: {
2527
+ Arn: getUserResponse.User?.Arn,
2528
+ ...definedAttributes({ UserId: userOrGroupIdentityToken(getUserResponse.User?.UserId) })
2529
+ }
2389
2530
  };
2390
2531
  } catch (error) {
2391
2532
  const cause = error instanceof Error ? error : void 0;
@@ -2498,7 +2639,20 @@ async function deleteUser(logicalId, physicalId, resourceType, context) {
2498
2639
  let hadBoundary = false;
2499
2640
  try {
2500
2641
  try {
2501
- hadBoundary = (await this.iamClient.send(new GetUserCommand({ UserName: physicalId }))).User?.PermissionsBoundary !== void 0;
2642
+ const readUser = async () => {
2643
+ const user = (await this.iamClient.send(new GetUserCommand({ UserName: physicalId }))).User;
2644
+ hadBoundary = user?.PermissionsBoundary !== void 0;
2645
+ return user?.UserName?.toLowerCase() === physicalId.toLowerCase() ? user.UserId : void 0;
2646
+ };
2647
+ await assertRecordedIdentity({
2648
+ label: "IAM user",
2649
+ resourceType,
2650
+ logicalId,
2651
+ physicalId,
2652
+ liveId: await readUser(),
2653
+ reread: readUser,
2654
+ context
2655
+ });
2502
2656
  } catch (error) {
2503
2657
  if (error instanceof NoSuchEntityException) {
2504
2658
  const clientRegion = await this.iamClient.config.region();
@@ -2529,6 +2683,7 @@ async function deleteUser(logicalId, physicalId, resourceType, context) {
2529
2683
  await this.iamClient.send(new DeleteUserCommand({ UserName: physicalId }));
2530
2684
  log.debug(`Successfully deleted IAM user ${logicalId}`);
2531
2685
  } catch (error) {
2686
+ if (error instanceof RecordedIdentityError) throw error;
2532
2687
  const cause = error instanceof Error ? error : void 0;
2533
2688
  const failure = this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(log.mask(`Failed to delete IAM user ${logicalId}: ${text}`), resourceType, logicalId, physicalId, cause));
2534
2689
  throw progress.stripped ? markDeleteStarted(failure) : failure;
@@ -2695,7 +2850,10 @@ async function createGroup(logicalId, resourceType, properties, log) {
2695
2850
  log.debug(`Successfully created IAM group ${logicalId}: ${v(groupName)}`);
2696
2851
  return {
2697
2852
  physicalId: groupName,
2698
- attributes: { Arn: group?.Arn }
2853
+ attributes: {
2854
+ Arn: group?.Arn,
2855
+ ...definedAttributes({ GroupId: createdGroupIdentity })
2856
+ }
2699
2857
  };
2700
2858
  } catch (error) {
2701
2859
  const cause = error instanceof Error ? error : void 0;
@@ -2723,7 +2881,10 @@ async function updateGroup(logicalId, physicalId, resourceType, properties, prev
2723
2881
  return {
2724
2882
  physicalId,
2725
2883
  wasReplaced: false,
2726
- attributes: { Arn: getGroupResponse.Group?.Arn }
2884
+ attributes: {
2885
+ Arn: getGroupResponse.Group?.Arn,
2886
+ ...definedAttributes({ GroupId: userOrGroupIdentityToken(getGroupResponse.Group?.GroupId) })
2887
+ }
2727
2888
  };
2728
2889
  } catch (error) {
2729
2890
  const cause = error instanceof Error ? error : void 0;
@@ -2736,9 +2897,24 @@ async function deleteGroup(logicalId, physicalId, resourceType, context) {
2736
2897
  log.debug(`Deleting IAM group ${logicalId}: ${v(physicalId)}`);
2737
2898
  const progress = { stripped: false };
2738
2899
  try {
2900
+ let members = [];
2901
+ const readGroup = async () => {
2902
+ const response = await this.iamClient.send(new GetGroupCommand({ GroupName: physicalId }));
2903
+ members = response.Users ?? [];
2904
+ return response.Group?.GroupName?.toLowerCase() === physicalId.toLowerCase() ? response.Group.GroupId : void 0;
2905
+ };
2906
+ await assertRecordedIdentity({
2907
+ label: "IAM group",
2908
+ resourceType,
2909
+ logicalId,
2910
+ physicalId,
2911
+ liveId: await readGroup(),
2912
+ reread: readGroup,
2913
+ context
2914
+ });
2739
2915
  await this.detachAllGroupPolicies(physicalId, log, progress);
2740
2916
  await this.deleteAllGroupInlinePolicies(physicalId, log, progress);
2741
- await this.removeAllUsersFromGroup(physicalId, log, progress);
2917
+ await this.removeAllUsersFromGroup(physicalId, log, progress, members);
2742
2918
  await this.iamClient.send(new DeleteGroupCommand({ GroupName: physicalId }));
2743
2919
  log.debug(`Successfully deleted IAM group ${logicalId}`);
2744
2920
  } catch (error) {
@@ -2749,6 +2925,7 @@ async function deleteGroup(logicalId, physicalId, resourceType, context) {
2749
2925
  else log.debug(`Group ${v(physicalId)} does not exist, skipping deletion`);
2750
2926
  return;
2751
2927
  }
2928
+ if (error instanceof RecordedIdentityError) throw error;
2752
2929
  const cause = error instanceof Error ? error : void 0;
2753
2930
  const failure = this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(log.mask(`Failed to delete IAM group ${logicalId}: ${text}`), resourceType, logicalId, physicalId, cause));
2754
2931
  throw progress.stripped ? markDeleteStarted(failure) : failure;
@@ -2773,10 +2950,9 @@ async function detachAllGroupPolicies(groupName, log, progress) {
2773
2950
  throw error;
2774
2951
  }
2775
2952
  }
2776
- async function removeAllUsersFromGroup(groupName, log, progress) {
2953
+ async function removeAllUsersFromGroup(groupName, log, progress, users) {
2777
2954
  const { value: v } = log;
2778
2955
  try {
2779
- const users = (await this.iamClient.send(new GetGroupCommand({ GroupName: groupName }))).Users || [];
2780
2956
  for (const user of users) if (user.UserName) try {
2781
2957
  await this.iamClient.send(new RemoveUserFromGroupCommand({
2782
2958
  GroupName: groupName,
@@ -3089,15 +3265,15 @@ async function readIdIfExists(resourceType, name) {
3089
3265
  }
3090
3266
  async function readCurrentState$39(physicalId, logicalId, resourceType, properties, context) {
3091
3267
  switch (resourceType) {
3092
- case "AWS::IAM::User": return this.readUserCurrentState(physicalId, properties, context);
3093
- case "AWS::IAM::Group": return this.readGroupCurrentState(physicalId, properties, context);
3268
+ case "AWS::IAM::User": return this.readUserCurrentState(physicalId, properties, context, logicalId);
3269
+ case "AWS::IAM::Group": return this.readGroupCurrentState(physicalId, properties, context, logicalId);
3094
3270
  case "AWS::IAM::UserToGroupAddition": return;
3095
3271
  default:
3096
3272
  this.logger.debug(`readCurrentState: unsupported resource type ${resourceType} for ${logicalId}`);
3097
3273
  return;
3098
3274
  }
3099
3275
  }
3100
- async function readUserCurrentState(physicalId, properties, context) {
3276
+ async function readUserCurrentState(physicalId, properties, context, logicalId = physicalId) {
3101
3277
  let user;
3102
3278
  try {
3103
3279
  user = (await this.iamClient.send(new GetUserCommand({ UserName: physicalId }))).User;
@@ -3110,26 +3286,47 @@ async function readUserCurrentState(physicalId, properties, context) {
3110
3286
  if (user.UserName !== void 0) result["UserName"] = user.UserName;
3111
3287
  if (user.Path !== void 0) result["Path"] = user.Path;
3112
3288
  result["PermissionsBoundary"] = user.PermissionsBoundary?.PermissionsBoundaryArn ?? "";
3289
+ const reads = userMemberReads.call(this, physicalId, properties, context);
3113
3290
  try {
3114
- const arns = ((await this.iamClient.send(new ListAttachedUserPoliciesCommand({ UserName: physicalId }))).AttachedPolicies ?? []).map((p) => p.PolicyArn).filter((arn) => !!arn);
3115
- result["ManagedPolicyArns"] = withoutSiblingAttachedArns(arns, collectManagedPolicyArnsAttachedBySiblings(physicalId, context, "Users"), properties);
3291
+ result["ManagedPolicyArns"] = await reads.managedPolicyArns();
3116
3292
  } catch (err) {
3117
3293
  if (!(err instanceof NoSuchEntityException)) throw err;
3118
3294
  }
3119
3295
  try {
3120
- const names = ((await this.iamClient.send(new ListGroupsForUserCommand({ UserName: physicalId }))).Groups ?? []).map((g) => g.GroupName).filter((n) => !!n);
3121
- result["Groups"] = withoutSiblingOwned(names, collectGroupsAddedBySiblings(physicalId, context), properties, "Groups", true);
3296
+ result["Groups"] = await reads.groups();
3122
3297
  } catch (err) {
3123
3298
  if (!(err instanceof NoSuchEntityException)) throw err;
3124
3299
  }
3125
3300
  try {
3126
- result["Policies"] = await this.collectInlinePolicies("user", physicalId, properties?.["Policies"] ?? [], context);
3301
+ result["Policies"] = await reads.policies();
3127
3302
  } catch (err) {
3128
3303
  if (!(err instanceof NoSuchEntityException)) throw err;
3129
3304
  }
3305
+ if (context?.afterOwnWrite === true && properties !== void 0) await settleOwnWriteMembers(result, principalOwnWriteMembers(properties, {
3306
+ boundary: async () => {
3307
+ const resp = await this.iamClient.send(new GetUserCommand({ UserName: physicalId }));
3308
+ return resp.User ? { value: resp.User.PermissionsBoundary?.PermissionsBoundaryArn ?? "" } : "failed";
3309
+ },
3310
+ managedPolicyArns: async () => ({ value: await reads.managedPolicyArns() }),
3311
+ groups: async () => ({ value: await reads.groups() }),
3312
+ policies: async () => ({ value: await reads.policies() })
3313
+ }), this.ownWriteRereadDelaysMs, (key) => warnUnsettledMember(this.logger, logicalId, "AWS::IAM::User", key));
3130
3314
  return result;
3131
3315
  }
3132
- async function readGroupCurrentState(physicalId, properties, context) {
3316
+ function userMemberReads(physicalId, properties, context) {
3317
+ return {
3318
+ managedPolicyArns: async () => {
3319
+ const arns = ((await this.iamClient.send(new ListAttachedUserPoliciesCommand({ UserName: physicalId }))).AttachedPolicies ?? []).map((p) => p.PolicyArn).filter((arn) => !!arn);
3320
+ return withoutSiblingAttachedArns(arns, collectManagedPolicyArnsAttachedBySiblings(physicalId, context, "Users"), properties);
3321
+ },
3322
+ groups: async () => {
3323
+ const names = ((await this.iamClient.send(new ListGroupsForUserCommand({ UserName: physicalId }))).Groups ?? []).map((g) => g.GroupName).filter((n) => !!n);
3324
+ return withoutSiblingOwned(names, collectGroupsAddedBySiblings(physicalId, context), properties, "Groups", true);
3325
+ },
3326
+ policies: () => this.collectInlinePolicies("user", physicalId, properties?.["Policies"] ?? [], context)
3327
+ };
3328
+ }
3329
+ async function readGroupCurrentState(physicalId, properties, context, logicalId = physicalId) {
3133
3330
  let group;
3134
3331
  try {
3135
3332
  group = (await this.iamClient.send(new GetGroupCommand({ GroupName: physicalId }))).Group;
@@ -3141,17 +3338,25 @@ async function readGroupCurrentState(physicalId, properties, context) {
3141
3338
  const result = {};
3142
3339
  if (group.GroupName !== void 0) result["GroupName"] = group.GroupName;
3143
3340
  if (group.Path !== void 0) result["Path"] = group.Path;
3144
- try {
3341
+ const managedPolicyArns = async () => {
3145
3342
  const arns = ((await this.iamClient.send(new ListAttachedGroupPoliciesCommand({ GroupName: physicalId }))).AttachedPolicies ?? []).map((p) => p.PolicyArn).filter((arn) => !!arn);
3146
- result["ManagedPolicyArns"] = withoutSiblingAttachedArns(arns, collectManagedPolicyArnsAttachedBySiblings(physicalId, context, "Groups"), properties);
3343
+ return withoutSiblingAttachedArns(arns, collectManagedPolicyArnsAttachedBySiblings(physicalId, context, "Groups"), properties);
3344
+ };
3345
+ const policies = () => this.collectInlinePolicies("group", physicalId, properties?.["Policies"] ?? [], context);
3346
+ try {
3347
+ result["ManagedPolicyArns"] = await managedPolicyArns();
3147
3348
  } catch (err) {
3148
3349
  if (!(err instanceof NoSuchEntityException)) throw err;
3149
3350
  }
3150
3351
  try {
3151
- result["Policies"] = await this.collectInlinePolicies("group", physicalId, properties?.["Policies"] ?? [], context);
3352
+ result["Policies"] = await policies();
3152
3353
  } catch (err) {
3153
3354
  if (!(err instanceof NoSuchEntityException)) throw err;
3154
3355
  }
3356
+ if (context?.afterOwnWrite === true && properties !== void 0) await settleOwnWriteMembers(result, principalOwnWriteMembers(properties, {
3357
+ managedPolicyArns: async () => ({ value: await managedPolicyArns() }),
3358
+ policies: async () => ({ value: await policies() })
3359
+ }), this.ownWriteRereadDelaysMs, (key) => warnUnsettledMember(this.logger, logicalId, "AWS::IAM::Group", key));
3155
3360
  return result;
3156
3361
  }
3157
3362
  async function collectInlinePolicies(kind, physicalId, statePolicies, context) {
@@ -3224,7 +3429,10 @@ async function importUser(input) {
3224
3429
  const resp = await this.iamClient.send(new GetUserCommand({ UserName: explicit }));
3225
3430
  return {
3226
3431
  physicalId: explicit,
3227
- attributes: definedAttributes({ Arn: resp.User?.Arn })
3432
+ attributes: definedAttributes({
3433
+ Arn: resp.User?.Arn,
3434
+ UserId: userOrGroupIdentityToken(resp.User?.UserId)
3435
+ })
3228
3436
  };
3229
3437
  } catch (err) {
3230
3438
  if (err instanceof NoSuchEntityException) return null;
@@ -3238,7 +3446,10 @@ async function importGroup(input) {
3238
3446
  const resp = await this.iamClient.send(new GetGroupCommand({ GroupName: explicit }));
3239
3447
  return {
3240
3448
  physicalId: explicit,
3241
- attributes: definedAttributes({ Arn: resp.Group?.Arn })
3449
+ attributes: definedAttributes({
3450
+ Arn: resp.Group?.Arn,
3451
+ GroupId: userOrGroupIdentityToken(resp.Group?.GroupId)
3452
+ })
3242
3453
  };
3243
3454
  } catch (err) {
3244
3455
  if (err instanceof NoSuchEntityException) return null;
@@ -3259,6 +3470,7 @@ var IAMUserGroupProvider = class {
3259
3470
  iamClient;
3260
3471
  createClient = new IamCreateClientCache(() => this.iamClient);
3261
3472
  logger = getLogger().child("IAMUserGroupProvider");
3473
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
3262
3474
  wrapMaskedError(mask, error, build) {
3263
3475
  return wrapMaskedError$4.call(this, mask, error, build);
3264
3476
  }
@@ -3345,8 +3557,8 @@ var IAMUserGroupProvider = class {
3345
3557
  detachAllGroupPolicies(groupName, log, progress) {
3346
3558
  return detachAllGroupPolicies.call(this, groupName, log, progress);
3347
3559
  }
3348
- removeAllUsersFromGroup(groupName, log, progress) {
3349
- return removeAllUsersFromGroup.call(this, groupName, log, progress);
3560
+ removeAllUsersFromGroup(groupName, log, progress, users) {
3561
+ return removeAllUsersFromGroup.call(this, groupName, log, progress, users);
3350
3562
  }
3351
3563
  updateGroupManagedPolicies(groupName, newPolicies, oldPolicies, log) {
3352
3564
  return updateGroupManagedPolicies.call(this, groupName, newPolicies, oldPolicies, log);
@@ -3375,14 +3587,17 @@ var IAMUserGroupProvider = class {
3375
3587
  readIdIfExists(resourceType, name) {
3376
3588
  return readIdIfExists.call(this, resourceType, name);
3377
3589
  }
3590
+ getDriftUnorderedPaths(resourceType) {
3591
+ return resourceType === "AWS::IAM::User" ? ["Groups"] : [];
3592
+ }
3378
3593
  readCurrentState(physicalId, logicalId, resourceType, properties, context) {
3379
3594
  return readCurrentState$39.call(this, physicalId, logicalId, resourceType, properties, context);
3380
3595
  }
3381
- readUserCurrentState(physicalId, properties, context) {
3382
- return readUserCurrentState.call(this, physicalId, properties, context);
3596
+ readUserCurrentState(physicalId, properties, context, logicalId) {
3597
+ return readUserCurrentState.call(this, physicalId, properties, context, logicalId);
3383
3598
  }
3384
- readGroupCurrentState(physicalId, properties, context) {
3385
- return readGroupCurrentState.call(this, physicalId, properties, context);
3599
+ readGroupCurrentState(physicalId, properties, context, logicalId) {
3600
+ return readGroupCurrentState.call(this, physicalId, properties, context, logicalId);
3386
3601
  }
3387
3602
  collectInlinePolicies(kind, physicalId, statePolicies, context) {
3388
3603
  return collectInlinePolicies.call(this, kind, physicalId, statePolicies, context);
@@ -3412,16 +3627,16 @@ function abacStatusOf(properties) {
3412
3627
  return properties["AbacStatus"] ?? "Disabled";
3413
3628
  }
3414
3629
  function metadataBag(value) {
3415
- return isPlainObject$3(value) ? value : void 0;
3630
+ return isPlainObject$4(value) ? value : void 0;
3416
3631
  }
3417
3632
  function metadataConfigurationRefusal(value) {
3418
3633
  if (value === void 0) return void 0;
3419
3634
  const root = "MetadataConfiguration";
3420
- if (!isPlainObject$3(value)) return `${root} must be an object`;
3635
+ if (!isPlainObject$4(value)) return `${root} must be an object`;
3421
3636
  const journal = value["JournalTableConfiguration"];
3422
- if (!isPlainObject$3(journal)) return `${root}.JournalTableConfiguration must be an object`;
3637
+ if (!isPlainObject$4(journal)) return `${root}.JournalTableConfiguration must be an object`;
3423
3638
  const expiration = journal["RecordExpiration"];
3424
- if (!isPlainObject$3(expiration)) return `${root}.JournalTableConfiguration.RecordExpiration must be an object`;
3639
+ if (!isPlainObject$4(expiration)) return `${root}.JournalTableConfiguration.RecordExpiration must be an object`;
3425
3640
  if (typeof expiration["Expiration"] !== "string") return `${root}.JournalTableConfiguration.RecordExpiration.Expiration must be a string`;
3426
3641
  const days = expiration["Days"];
3427
3642
  if (days !== void 0 && (days === "" || days === null || !Number.isInteger(Number(days)))) return `${root}.JournalTableConfiguration.RecordExpiration.Days must be an integer`;
@@ -3432,11 +3647,11 @@ function metadataConfigurationRefusal(value) {
3432
3647
  ];
3433
3648
  for (const [member, table] of tables) {
3434
3649
  if (table === void 0) continue;
3435
- if (!isPlainObject$3(table)) return `${root}.${member} must be an object`;
3650
+ if (!isPlainObject$4(table)) return `${root}.${member} must be an object`;
3436
3651
  if (member !== "JournalTableConfiguration" && typeof table["ConfigurationState"] !== "string") return `${root}.${member}.ConfigurationState must be a string`;
3437
3652
  const encryption = table["EncryptionConfiguration"];
3438
3653
  if (encryption === void 0) continue;
3439
- if (!isPlainObject$3(encryption) || typeof encryption["SseAlgorithm"] !== "string") return `${root}.${member}.EncryptionConfiguration must be an object with an SseAlgorithm`;
3654
+ if (!isPlainObject$4(encryption) || typeof encryption["SseAlgorithm"] !== "string") return `${root}.${member}.EncryptionConfiguration must be an object with an SseAlgorithm`;
3440
3655
  }
3441
3656
  }
3442
3657
  function metadataEncryptionToSdk(table) {
@@ -4597,7 +4812,7 @@ async function applyLifecycleConfiguration(bucketName, lifecycleConfig, onUnusab
4597
4812
  if (!(exp?.["Days"] !== void 0 || exp?.["Date"] !== void 0)) sdkRule.Expiration = { ExpiredObjectDeleteMarker: true };
4598
4813
  else this.logger.warn(`Lifecycle rule ${shownLifecycleRuleId(maskDeep(rule["Id"], this.shownMask))} on ${this.shown(bucketName)} sets ExpiredObjectDeleteMarker alongside an expiration Days/Date; S3 forbids combining them, so the delete-marker cleanup was not applied.`);
4599
4814
  }
4600
- const nve = isPlainObject$3(rule["NoncurrentVersionExpiration"]) ? rule["NoncurrentVersionExpiration"] : void 0;
4815
+ const nve = isPlainObject$4(rule["NoncurrentVersionExpiration"]) ? rule["NoncurrentVersionExpiration"] : void 0;
4601
4816
  const legacyNveDays = rule["NoncurrentVersionExpirationInDays"];
4602
4817
  if (nve) sdkRule.NoncurrentVersionExpiration = {
4603
4818
  NoncurrentDays: nve["NoncurrentDays"],
@@ -4622,7 +4837,7 @@ async function applyLifecycleConfiguration(bucketName, lifecycleConfig, onUnusab
4622
4837
  const singularTransition = rule["Transition"];
4623
4838
  const allTransitions = mergeLegacySingular(transitions, singularTransition, (sc) => this.logger.warn(`Lifecycle rule ${shownLifecycleRuleId(maskDeep(rule["Id"], this.shownMask))} on ${this.shown(bucketName)} declares both Transitions and the legacy Transition for storage class ${this.shown(sc)}; S3 rejects duplicates, so the legacy singular was ignored.`));
4624
4839
  if (allTransitions.length > 0) sdkRule.Transitions = allTransitions.map(toSdkTransition);
4625
- const abort = isPlainObject$3(rule["AbortIncompleteMultipartUpload"]) ? rule["AbortIncompleteMultipartUpload"] : void 0;
4840
+ const abort = isPlainObject$4(rule["AbortIncompleteMultipartUpload"]) ? rule["AbortIncompleteMultipartUpload"] : void 0;
4626
4841
  if (abort) sdkRule.AbortIncompleteMultipartUpload = { DaysAfterInitiation: abort["DaysAfterInitiation"] };
4627
4842
  const { prefix, tagFilters, sizeGt, sizeLt } = lifecycleRuleScope(rule);
4628
4843
  const hasTags = tagFilters != null && tagFilters.length > 0;
@@ -4857,7 +5072,7 @@ function resolveS3BucketDestination(dest, destinationPath, onUnusable, maskSecre
4857
5072
  throw new Error(message);
4858
5073
  };
4859
5074
  if (dest === void 0 || dest === null) return;
4860
- if (!isPlainObject$3(dest)) return drop(`${destinationPath} must be an object (got ${describeValue$1(dest, maskSecrets)}) — check for an unresolved intrinsic or a mis-nested template value; the destination would otherwise be dropped from the request with no error`);
5075
+ if (!isPlainObject$4(dest)) return drop(`${destinationPath} must be an object (got ${describeValue$1(dest, maskSecrets)}) — check for an unresolved intrinsic or a mis-nested template value; the destination would otherwise be dropped from the request with no error`);
4861
5076
  if (!dest["BucketArn"]) return drop(`${destinationPath} has no destination bucket (BucketArn) (got ${describeValue$1(dest, maskSecrets)}) — the request would be rejected by S3, or silently carry no destination`);
4862
5077
  return dest;
4863
5078
  }
@@ -5528,6 +5743,7 @@ function getDriftUnknownPaths$12() {
5528
5743
  return [
5529
5744
  "BucketNamePrefix",
5530
5745
  "BucketNamespace",
5746
+ "ObjectLockEnabled",
5531
5747
  "MetadataConfiguration.JournalTableConfiguration.EncryptionConfiguration",
5532
5748
  "MetadataConfiguration.InventoryTableConfiguration.EncryptionConfiguration",
5533
5749
  "MetadataConfiguration.AnnotationTableConfiguration.EncryptionConfiguration"
@@ -6595,6 +6811,17 @@ function ownPolicyHolder(logicalId, bucketName) {
6595
6811
  for (const [otherId, record] of getStackRecords()?.live() ?? []) if (otherId !== logicalId && record.resourceType === "AWS::S3::BucketPolicy" && record.physicalId === bucketName) return otherId;
6596
6812
  }
6597
6813
 
6814
+ // src/provisioning/providers/s3-bucket-policy-own-write.ts
6815
+ const NO_BASELINE = {};
6816
+ async function settleBucketPolicyRead(first, read, options) {
6817
+ const declared = options.context?.afterOwnWrite === true ? declaredPolicyDocument(options.properties) : void 0;
6818
+ if (declared === void 0 || first === void 0) return first;
6819
+ const asMember = (answer) => answer === RESOURCE_NOT_FOUND ? "absent" : answer === void 0 ? "failed" : { value: answer };
6820
+ const settled = await settleDeclaredMember(asMember(first), async () => asMember(await read()), (value) => policyDocumentMatchesDeclared(value["PolicyDocument"], declared), NO_BASELINE, options.delaysMs, () => warnUnsettledMember(options.logger, options.logicalId, "AWS::S3::BucketPolicy", "PolicyDocument"));
6821
+ if (typeof settled !== "object") return first;
6822
+ return settled.value === NO_BASELINE ? void 0 : settled.value;
6823
+ }
6824
+
6598
6825
  // src/provisioning/providers/s3-bucket-policy-provider.ts
6599
6826
  const OAI_USER_ARN_RE = /^arn:aws[a-z-]*:iam::cloudfront:user\/CloudFront Origin Access Identity ([A-Z0-9]+)$/;
6600
6827
  const IAM_UNIQUE_ID_RE = /^AIDA[A-Z0-9]{12,}$/;
@@ -6633,6 +6860,7 @@ function findTemplateCanonicalUser(awsStmt, templateStmts) {
6633
6860
  var S3BucketPolicyProvider = class {
6634
6861
  s3Client;
6635
6862
  logger = getLogger().child("S3BucketPolicyProvider");
6863
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
6636
6864
  sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
6637
6865
  handledProperties = /* @__PURE__ */ new Map([["AWS::S3::BucketPolicy", /* @__PURE__ */ new Set(["Bucket", "PolicyDocument"])]]);
6638
6866
  constructor() {
@@ -6845,7 +7073,18 @@ var S3BucketPolicyProvider = class {
6845
7073
  const stamped = cause !== void 0 ? markRedactedCause(wrapped) : wrapped;
6846
7074
  return operation === "delete" && cause !== void 0 && cause.name.includes("NotFound") ? markNotGone(stamped) : stamped;
6847
7075
  }
6848
- async readCurrentState(physicalId, _logicalId, _resourceType, properties, context) {
7076
+ async readCurrentState(physicalId, logicalId, _resourceType, properties, context) {
7077
+ const read = () => this.readPolicyOnce(physicalId, properties, context);
7078
+ const options = {
7079
+ logicalId,
7080
+ properties,
7081
+ context,
7082
+ delaysMs: this.ownWriteRereadDelaysMs,
7083
+ logger: this.logger
7084
+ };
7085
+ return settleBucketPolicyRead(await read(), read, options);
7086
+ }
7087
+ async readPolicyOnce(physicalId, properties, context) {
6849
7088
  let policyJson;
6850
7089
  try {
6851
7090
  policyJson = (await this.s3Client.send(new GetBucketPolicyCommand({ Bucket: physicalId }))).Policy;
@@ -11202,7 +11441,7 @@ async function readCurrentState$35(physicalId, _logicalId, _resourceType, proper
11202
11441
  result["Tags"] = tags;
11203
11442
  return result;
11204
11443
  }
11205
- async function canonicalizeDriftPair$5(_resourceType, baseline, aws, properties) {
11444
+ async function canonicalizeDriftPair$6(_resourceType, baseline, aws, properties) {
11206
11445
  const key = "SelfManagedKafkaEventSourceConfig";
11207
11446
  const block = baseline[key];
11208
11447
  if (typeof block !== "object" || block === null || Array.isArray(block) || "ConsumptionMode" in block || consumptionModeOf(aws) !== "Stream" || consumptionModeOf(properties ?? {}) !== "Stream" || aws[key]?.["ConsumptionMode"] === void 0) return {
@@ -11354,7 +11593,7 @@ var LambdaEventSourceMappingProvider = class {
11354
11593
  return readCurrentState$35.call(this, physicalId, logicalId, resourceType, properties);
11355
11594
  }
11356
11595
  canonicalizeDriftPair(resourceType, baseline, aws, properties) {
11357
- return canonicalizeDriftPair$5.call(this, resourceType, baseline, aws, properties);
11596
+ return canonicalizeDriftPair$6.call(this, resourceType, baseline, aws, properties);
11358
11597
  }
11359
11598
  import(input) {
11360
11599
  return importImpl$34.call(this, input);
@@ -12177,7 +12416,7 @@ function recordedFunctionNameSpelling(recorded, liveFunctionArn) {
12177
12416
  return liveFunctionArn;
12178
12417
  }
12179
12418
  function projectOntoRecorded(recorded, live) {
12180
- if (!isPlainRecord$4(recorded) || !isPlainRecord$4(live)) return live;
12419
+ if (!isPlainRecord$3(recorded) || !isPlainRecord$3(live)) return live;
12181
12420
  const out = {};
12182
12421
  for (const key of Object.keys(recorded)) {
12183
12422
  if (!Object.prototype.hasOwnProperty.call(live, key)) continue;
@@ -12185,7 +12424,7 @@ function projectOntoRecorded(recorded, live) {
12185
12424
  }
12186
12425
  return out;
12187
12426
  }
12188
- function isPlainRecord$4(value) {
12427
+ function isPlainRecord$3(value) {
12189
12428
  return typeof value === "object" && value !== null && !Array.isArray(value);
12190
12429
  }
12191
12430
  const LAMBDA_WEB_MAX_POLL_ATTEMPTS = 1200;
@@ -12393,15 +12632,15 @@ var LambdaWebFunctionRevisionProvider = class {
12393
12632
  const functionName = properties["FunctionName"];
12394
12633
  if (typeof functionName !== "string" || functionName === "") fail("FunctionName must be a non-empty string");
12395
12634
  const build = properties["BuildConfig"];
12396
- if (!isPlainRecord$4(build)) fail("BuildConfig must be an object");
12635
+ if (!isPlainRecord$3(build)) fail("BuildConfig must be an object");
12397
12636
  const code = build["CodeConfig"];
12398
- const s3 = isPlainRecord$4(code) ? code["S3Object"] : void 0;
12399
- if (!isPlainRecord$4(s3) || typeof s3["Bucket"] !== "string" || typeof s3["Key"] !== "string") fail("BuildConfig.CodeConfig.S3Object.Bucket and .Key are required strings");
12637
+ const s3 = isPlainRecord$3(code) ? code["S3Object"] : void 0;
12638
+ if (!isPlainRecord$3(s3) || typeof s3["Bucket"] !== "string" || typeof s3["Key"] !== "string") fail("BuildConfig.CodeConfig.S3Object.Bucket and .Key are required strings");
12400
12639
  const runtimeConfig = build["RuntimeConfig"];
12401
- const runtime = isPlainRecord$4(runtimeConfig) ? runtimeConfig["Runtime"] : void 0;
12640
+ const runtime = isPlainRecord$3(runtimeConfig) ? runtimeConfig["Runtime"] : void 0;
12402
12641
  if (typeof runtime !== "string") fail("BuildConfig.RuntimeConfig.Runtime is a required string");
12403
12642
  const service = properties["ServiceConfig"];
12404
- if (!isPlainRecord$4(service) || typeof service["ExecutionRoleArn"] !== "string") fail("ServiceConfig.ExecutionRoleArn is a required string");
12643
+ if (!isPlainRecord$3(service) || typeof service["ExecutionRoleArn"] !== "string") fail("ServiceConfig.ExecutionRoleArn is a required string");
12405
12644
  const s3Object = s3;
12406
12645
  const input = {
12407
12646
  functionName,
@@ -12440,15 +12679,15 @@ var LambdaWebFunctionRevisionProvider = class {
12440
12679
  if (typeof service["EgressNetworkConnectorArn"] === "string") out.egressNetworkConnectorArn = service["EgressNetworkConnectorArn"];
12441
12680
  const env = service["EnvironmentVariables"];
12442
12681
  if (env !== void 0) {
12443
- if (isPlainRecord$4(env) && Object.values(env).every((v) => typeof v === "string")) out.environmentVariables = { ...env };
12682
+ if (isPlainRecord$3(env) && Object.values(env).every((v) => typeof v === "string")) out.environmentVariables = { ...env };
12444
12683
  else if (context?.replayingState) this.logger.warn(safeMsg`ServiceConfig.EnvironmentVariables must be an object of string values; omitting it while replaying a state record`);
12445
12684
  else fail("ServiceConfig.EnvironmentVariables must be an object of string values");
12446
12685
  }
12447
12686
  const telemetry = service["TelemetryConfig"];
12448
- if (isPlainRecord$4(telemetry)) {
12687
+ if (isPlainRecord$3(telemetry)) {
12449
12688
  const telemetryConfig = {};
12450
12689
  const logging = telemetry["LoggingConfig"];
12451
- if (isPlainRecord$4(logging)) {
12690
+ if (isPlainRecord$3(logging)) {
12452
12691
  const loggingConfig = {};
12453
12692
  if (typeof logging["LogGroup"] === "string") loggingConfig.logGroup = logging["LogGroup"];
12454
12693
  if (typeof logging["ApplicationLogLevel"] === "string") loggingConfig.applicationLogLevel = logging["ApplicationLogLevel"];
@@ -12780,7 +13019,7 @@ var LambdaWebFunctionEndpointProvider = class {
12780
13019
  }
12781
13020
  return fail(message);
12782
13021
  };
12783
- if (!isPlainRecord$4(value)) return bad(`${blockKey} must be an object`);
13022
+ if (!isPlainRecord$3(value)) return bad(`${blockKey} must be an object`);
12784
13023
  if (value[memberKey] === void 0) return { present: false };
12785
13024
  const n = coerceCfnInteger(value[memberKey]);
12786
13025
  if (n === void 0) return bad(`${blockKey}.${memberKey} must be an integer`);
@@ -12849,7 +13088,7 @@ function readRevisionWeights(value, fail) {
12849
13088
  if (value === void 0) return void 0;
12850
13089
  if (!Array.isArray(value)) return fail("RevisionWeights must be a list");
12851
13090
  return value.map((entry, i) => {
12852
- if (!isPlainRecord$4(entry) || typeof entry["RevisionId"] !== "string") return fail(`RevisionWeights[${i}].RevisionId must be a string`);
13091
+ if (!isPlainRecord$3(entry) || typeof entry["RevisionId"] !== "string") return fail(`RevisionWeights[${i}].RevisionId must be a string`);
12853
13092
  const weight = coerceCfnInteger(entry["Weight"]);
12854
13093
  if (weight === void 0) return fail(`RevisionWeights[${i}].Weight must be an integer`);
12855
13094
  return {
@@ -13112,8 +13351,8 @@ var LambdaNetworkConnectorProvider = class {
13112
13351
  throw new ProvisioningError(`${message} for Lambda network connector ${logicalIdShown(logicalId)}`, resourceType, logicalId, physicalId);
13113
13352
  };
13114
13353
  const config = properties["Configuration"];
13115
- const vpc = isPlainRecord$4(config) ? config["VpcEgressConfiguration"] : void 0;
13116
- if (!isPlainRecord$4(vpc)) return fail("Configuration.VpcEgressConfiguration must be an object");
13354
+ const vpc = isPlainRecord$3(config) ? config["VpcEgressConfiguration"] : void 0;
13355
+ if (!isPlainRecord$3(vpc)) return fail("Configuration.VpcEgressConfiguration must be an object");
13117
13356
  const strings = (key) => {
13118
13357
  const value = vpc[key];
13119
13358
  if (value === void 0) return void 0;
@@ -13135,7 +13374,7 @@ var LambdaNetworkConnectorProvider = class {
13135
13374
  readElasticIp(properties, logicalId, resourceType, physicalId, context) {
13136
13375
  const eip = declaredElasticIp(properties);
13137
13376
  if (eip === void 0) return void 0;
13138
- if (isPlainRecord$4(eip) && typeof eip["Type"] === "string" && ELASTIC_IP_TYPES.has(eip["Type"])) return { Type: eip["Type"] };
13377
+ if (isPlainRecord$3(eip) && typeof eip["Type"] === "string" && ELASTIC_IP_TYPES.has(eip["Type"])) return { Type: eip["Type"] };
13139
13378
  const message = `Configuration.VpcEgressConfiguration.${ELASTIC_IP_KEY} must be an object whose Type is ${[...ELASTIC_IP_TYPES].join(" or ")} for Lambda network connector ${logicalIdShown(logicalId)}`;
13140
13379
  if (context?.replayingState === true || context !== void 0 && "desiredFromAwsReadback" in context && context.desiredFromAwsReadback === true) {
13141
13380
  this.logger.warn(safeMsg`${message}; omitting it while applying a state-borne bag`);
@@ -13220,11 +13459,11 @@ const ELASTIC_IP_KEY = "ElasticIpConfiguration";
13220
13459
  const ELASTIC_IP_TYPES = /* @__PURE__ */ new Set(["None", "ServiceManaged"]);
13221
13460
  function declaredElasticIp(properties) {
13222
13461
  const config = properties["Configuration"];
13223
- const vpc = isPlainRecord$4(config) ? config["VpcEgressConfiguration"] : void 0;
13224
- return isPlainRecord$4(vpc) ? vpc[ELASTIC_IP_KEY] : void 0;
13462
+ const vpc = isPlainRecord$3(config) ? config["VpcEgressConfiguration"] : void 0;
13463
+ return isPlainRecord$3(vpc) ? vpc[ELASTIC_IP_KEY] : void 0;
13225
13464
  }
13226
13465
  function isNoneElasticIp(value) {
13227
- return isPlainRecord$4(value) && value["Type"] === "None";
13466
+ return isPlainRecord$3(value) && value["Type"] === "None";
13228
13467
  }
13229
13468
  function withoutElasticIp(properties) {
13230
13469
  const config = properties["Configuration"];
@@ -13242,7 +13481,7 @@ function elasticIpForUpdate(fromDesired, properties, previousProperties) {
13242
13481
  if (fromDesired !== void 0 || declaredElasticIp(properties) !== void 0) return fromDesired;
13243
13482
  const previous = declaredElasticIp(previousProperties);
13244
13483
  if (previous === void 0) return void 0;
13245
- if (isPlainRecord$4(previous) && previous["Type"] === "None") return void 0;
13484
+ if (isPlainRecord$3(previous) && previous["Type"] === "None") return void 0;
13246
13485
  return { Type: "None" };
13247
13486
  }
13248
13487
  var TerminalConnectorStateError = class extends Error {};
@@ -14049,7 +14288,7 @@ function canonicalizeDriftProperties$3(resourceType, properties) {
14049
14288
  }
14050
14289
  return result;
14051
14290
  }
14052
- async function canonicalizeDriftPair$4(resourceType, baseline, aws, properties) {
14291
+ async function canonicalizeDriftPair$5(resourceType, baseline, aws, properties) {
14053
14292
  if (resourceType !== "AWS::DynamoDB::Table") return {
14054
14293
  baseline,
14055
14294
  aws
@@ -14626,7 +14865,7 @@ async function waitForKinesisDestinationSettled(tableName, streamArn, expectedPr
14626
14865
  function isTransientStreamReadFailure(err) {
14627
14866
  return isThrottlingError(err) || isTransientServerError(err) || isAmbiguousOutcomeError(err) || err instanceof ResourceNotFoundException$1;
14628
14867
  }
14629
- async function readCurrentState$34(physicalId, _logicalId, _resourceType, properties, context) {
14868
+ async function readCurrentState$34(physicalId, logicalId, _resourceType, properties, context) {
14630
14869
  try {
14631
14870
  const table = (await this.dynamoDBClient.send(new DescribeTableCommand({ TableName: physicalId }))).Table;
14632
14871
  if (!table) return void 0;
@@ -14679,8 +14918,10 @@ async function readCurrentState$34(physicalId, _logicalId, _resourceType, proper
14679
14918
  if (table.DeletionProtectionEnabled !== void 0) result["DeletionProtectionEnabled"] = table.DeletionProtectionEnabled;
14680
14919
  if (table.TableClassSummary?.TableClass) result["TableClass"] = table.TableClassSummary.TableClass;
14681
14920
  const tableArn = table.TableArn;
14921
+ const tagsWritten = context?.afterOwnWrite === true && tableArn !== void 0 ? takeTagWrite("AWS::DynamoDB::Table", tableArn) : void 0;
14922
+ const tagsSettle = properties !== void 0 && bagInformative ? tagsWritten : void 0;
14682
14923
  const [tags, pitr, ttl, resourcePolicy, kinesis, contributorInsights] = await Promise.all([
14683
- tableArn ? this.readTableTags(tableArn) : Promise.resolve(void 0),
14924
+ tableArn ? tagsSettle === void 0 ? this.readTableTags(tableArn) : this.readTableTagsBaseline(tableArn, tagsSettle, logicalId) : Promise.resolve(void 0),
14684
14925
  this.readPointInTimeRecovery(physicalId),
14685
14926
  this.readTimeToLive(physicalId),
14686
14927
  tableArn ? this.readTableResourcePolicy(physicalId, tableArn, false, properties !== void 0 && bagInformative ? {
@@ -14994,6 +15235,7 @@ async function applyTagDiff$17(tableArn, resourceType, logicalId, oldTagsRaw, ne
14994
15235
  ResourceArn: tableArn,
14995
15236
  TagKeys: tagsToRemove
14996
15237
  }));
15238
+ recordTagWrite("AWS::DynamoDB::Table", tableArn, [], tagsToRemove);
14997
15239
  this.logger.debug(`Removed ${tagsToRemove.length} tag(s) from DynamoDB table ${tableArn}`);
14998
15240
  }
14999
15241
  if (tagsToAdd.length > 0) {
@@ -15001,6 +15243,7 @@ async function applyTagDiff$17(tableArn, resourceType, logicalId, oldTagsRaw, ne
15001
15243
  ResourceArn: tableArn,
15002
15244
  Tags: tagsToAdd
15003
15245
  }));
15246
+ recordTagWrite("AWS::DynamoDB::Table", tableArn, tagsToAdd.map((t) => [t.Key, t.Value]), []);
15004
15247
  let recordedKeys;
15005
15248
  try {
15006
15249
  recordedKeys = /* @__PURE__ */ new Set([...planTagDiff(void 0, oldTagsRaw).set.keys()]);
@@ -15371,6 +15614,8 @@ async function applyIndexUpdates(logicalId, physicalId, resourceType, properties
15371
15614
 
15372
15615
  // src/provisioning/providers/dynamodb-table/update.ts
15373
15616
  async function update$35(logicalId, physicalId, resourceType, properties, previousProperties, context) {
15617
+ const region = await this.dynamoDBClient.config.region().catch(() => void 0);
15618
+ clearTagWrites("AWS::DynamoDB::Table", (arn) => region === void 0 ? isDynamoDBTableArnIn(arn, physicalId, /* @__PURE__ */ new Set([arn.split(":")[3] ?? ""])) : isDynamoDBTableArnIn(arn, physicalId, /* @__PURE__ */ new Set([region])));
15374
15619
  const markUnsettled = (key) => context?.markUnsettled?.(key);
15375
15620
  const maskSecrets = context?.maskSecrets ?? ((text) => text);
15376
15621
  const warn = (message) => this.logger.warn(maskSecrets(message));
@@ -15782,7 +16027,7 @@ var DynamoDBTableProvider = class {
15782
16027
  return canonicalizeDriftProperties$3.call(this, resourceType, properties);
15783
16028
  }
15784
16029
  async canonicalizeDriftPair(resourceType, baseline, aws, properties) {
15785
- return canonicalizeDriftPair$4.call(this, resourceType, baseline, aws, properties);
16030
+ return canonicalizeDriftPair$5.call(this, resourceType, baseline, aws, properties);
15786
16031
  }
15787
16032
  async readUnsettled(physicalId, logicalId, resourceType, names, recordedProperties, desiredProperties, attemptedItems) {
15788
16033
  return readUnsettled$6.call(this, physicalId, logicalId, resourceType, names, recordedProperties, desiredProperties, attemptedItems);
@@ -15796,6 +16041,11 @@ var DynamoDBTableProvider = class {
15796
16041
  readTableTags(...args) {
15797
16042
  return readTableTags.call(this, ...args);
15798
16043
  }
16044
+ tagsBaselineRereadDelaysMs = TAGS_BASELINE_REREAD_DELAYS_MS;
16045
+ readTableTagsBaseline(tableArn, written, logicalId) {
16046
+ const read = () => this.readTableTags(tableArn);
16047
+ return settleWrittenTags(read, read, written, this.tagsBaselineRereadDelaysMs, () => warnUnsettledMember(this.logger, logicalId, "AWS::DynamoDB::Table", "Tags"), (answer) => answer === RESOURCE_NOT_FOUND);
16048
+ }
15799
16049
  readPointInTimeRecovery(...args) {
15800
16050
  return readPointInTimeRecovery.call(this, ...args);
15801
16051
  }
@@ -15898,6 +16148,41 @@ function assertUsableRetention(raw, coerced, logicalId, resourceType) {
15898
16148
  throw new ProvisioningError(`${logicalId} (${resourceType}): RetentionInDays must be a positive CloudFormation Integer (optional sign then decimal digits, as a number or a string — 30 or '30'); ${detail}`, resourceType, logicalId);
15899
16149
  }
15900
16150
 
16151
+ // src/provisioning/providers/logs-loggroup/own-replay.ts
16152
+ const createLogGroupLatch = new AmbiguousCreateLatch("CreateLogGroup");
16153
+ const createClients = /* @__PURE__ */ new WeakMap();
16154
+ function logGroupCreateClient(shared) {
16155
+ if (!(shared instanceof CloudWatchLogsClient)) return Promise.resolve(shared);
16156
+ let client = createClients.get(shared);
16157
+ if (client === void 0) {
16158
+ client = shared.config.region().then((region) => withoutServerErrorRetries(new CloudWatchLogsClient({
16159
+ ...ambientClientDefaults(),
16160
+ region
16161
+ })), (error) => {
16162
+ createClients.delete(shared);
16163
+ throw error;
16164
+ });
16165
+ createClients.set(shared, client);
16166
+ }
16167
+ return client;
16168
+ }
16169
+ async function ownReplayedGroup(logGroupName, createError, carried, attemptStartMs, shownName) {
16170
+ const replayedInSend = hasReplayMayCollide(createError);
16171
+ if (carried === void 0 && !replayedInSend) return false;
16172
+ const window = {
16173
+ floorMs: Math.min(carried?.floorMs ?? Number.POSITIVE_INFINITY, replayedInSend ? attemptStartMs - CREATION_DATE_SKEW_MARGIN_MS : Number.POSITIVE_INFINITY),
16174
+ ceilingMs: replayedInSend || carried === void 0 ? Date.now() + CREATION_DATE_SKEW_MARGIN_MS : carried.ceilingMs
16175
+ };
16176
+ let createdAt;
16177
+ try {
16178
+ createdAt = await this.holderCreatedAt("AWS::Logs::LogGroup", logGroupName);
16179
+ } catch (readError) {
16180
+ this.logger.debug(safeMsg`Could not read when log group ${shownName} was created (${describeAwsFailure(readError).summary}); refusing it`);
16181
+ return false;
16182
+ }
16183
+ return isInsideWindow(createdAt === void 0 ? void 0 : new Date(createdAt), window);
16184
+ }
16185
+
15901
16186
  // src/provisioning/providers/logs-loggroup/create.ts
15902
16187
  async function create$33(logicalId, resourceType, properties, context) {
15903
16188
  this.logger.debug(`Creating log group ${logicalId}`);
@@ -15911,14 +16196,26 @@ async function create$33(logicalId, resourceType, properties, context) {
15911
16196
  if (properties["DeletionProtectionEnabled"] !== void 0) createParams.deletionProtectionEnabled = properties["DeletionProtectionEnabled"];
15912
16197
  if (desiredTags.length > 0) createParams.tags = Object.fromEntries(desiredTags.map((t) => [t.Key, t.Value]));
15913
16198
  let createdNewLogGroup = false;
16199
+ const carried = createLogGroupLatch.take(logicalId);
16200
+ const attemptStartMs = Date.now();
15914
16201
  try {
15915
- await this.logsClient.send(new CreateLogGroupCommand(createParams));
16202
+ await (await logGroupCreateClient(this.logsClient)).send(new CreateLogGroupCommand(createParams));
15916
16203
  createdNewLogGroup = true;
15917
16204
  leftBehind = true;
15918
16205
  reportCreatedResource(logicalId, resourceType, logGroupName);
15919
16206
  } catch (createError) {
15920
- if (createError instanceof ResourceAlreadyExistsException) this.logger.debug(`Log group ${logGroupName} already exists, using existing`);
15921
- else throw createError;
16207
+ if (!(createError instanceof ResourceAlreadyExistsException)) {
16208
+ createLogGroupLatch.noteFailure(logicalId, createError, attemptStartMs, carried);
16209
+ throw createError;
16210
+ }
16211
+ const shownName = maskerOrIdentity(context?.maskSecrets)(logGroupName);
16212
+ if (licensedNameHolder() === logGroupName) this.logger.debug(safeMsg`Log group ${shownName} already exists and is this stack's own: taking it back`);
16213
+ else if (await ownReplayedGroup.call(this, logGroupName, createError, carried, attemptStartMs, shownName)) {
16214
+ createdNewLogGroup = true;
16215
+ leftBehind = true;
16216
+ reportCreatedResource(logicalId, resourceType, logGroupName);
16217
+ this.logger.debug(safeMsg`Log group ${shownName} was created by an earlier attempt of this create whose answer was lost: using it`);
16218
+ } else throw createError;
15922
16219
  }
15923
16220
  try {
15924
16221
  const rawRetention = properties["RetentionInDays"];
@@ -16409,7 +16706,7 @@ var LogsLogGroupProvider = class {
16409
16706
  function isLogsNotFound(error) {
16410
16707
  return error instanceof Error && error.name === "ResourceNotFoundException";
16411
16708
  }
16412
- function isPlainRecord$3(value) {
16709
+ function isPlainRecord$2(value) {
16413
16710
  return typeof value === "object" && value !== null && !Array.isArray(value);
16414
16711
  }
16415
16712
  function isStateBorne(context) {
@@ -16460,7 +16757,7 @@ var PropertyReader = class {
16460
16757
  optionalStringMap(key) {
16461
16758
  const value = this.properties[key];
16462
16759
  if (value === void 0) return void 0;
16463
- if (isPlainRecord$3(value) && Object.values(value).every((v) => typeof v === "string")) return { ...value };
16760
+ if (isPlainRecord$2(value) && Object.values(value).every((v) => typeof v === "string")) return { ...value };
16464
16761
  return this.refuse(`${key} must be a map of string values`);
16465
16762
  }
16466
16763
  optionalBoolean(key) {
@@ -16621,7 +16918,7 @@ var LogsDeliverySourceProvider = class {
16621
16918
  const liveConfig = source.deliverySourceConfiguration;
16622
16919
  if (liveConfig !== void 0 && Object.keys(liveConfig).length > 0) {
16623
16920
  const declared = properties?.["DeliverySourceConfiguration"];
16624
- result["DeliverySourceConfiguration"] = isPlainRecord$3(declared) ? Object.fromEntries(Object.entries(liveConfig).filter(([k]) => k in declared)) : { ...liveConfig };
16921
+ result["DeliverySourceConfiguration"] = isPlainRecord$2(declared) ? Object.fromEntries(Object.entries(liveConfig).filter(([k]) => k in declared)) : { ...liveConfig };
16625
16922
  }
16626
16923
  if (source.arn) try {
16627
16924
  result["Tags"] = await readTags$1(this.client, source.arn);
@@ -16799,10 +17096,10 @@ var LogsDeliveryDestinationProvider = class {
16799
17096
  if (destination.outputFormat !== void 0) result["OutputFormat"] = destination.outputFormat;
16800
17097
  let policy = await this.readDestinationPolicy(physicalId);
16801
17098
  const declared = properties?.["DeliveryDestinationPolicy"];
16802
- const declaredDocument = context?.afterOwnWrite === true && isPlainRecord$3(declared) ? declared["DeliveryDestinationPolicy"] : void 0;
16803
- 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"));
17099
+ const declaredDocument = context?.afterOwnWrite === true && isPlainRecord$2(declared) ? declared["DeliveryDestinationPolicy"] : void 0;
17100
+ if (isPlainRecord$2(declaredDocument)) policy = await settleDeclaredMember(policy, () => this.readDestinationPolicy(physicalId), (document) => policyDocumentMatchesDeclared(document, declaredDocument), declaredDocument, this.ownWriteRereadDelaysMs, () => warnUnsettledMember(this.logger, logicalId, "AWS::Logs::DeliveryDestination", "DeliveryDestinationPolicy"));
16804
17101
  if (typeof policy === "object") result["DeliveryDestinationPolicy"] = {
16805
- ...isPlainRecord$3(declared) && declared["DeliveryDestinationName"] !== void 0 && { DeliveryDestinationName: physicalId },
17102
+ ...isPlainRecord$2(declared) && declared["DeliveryDestinationName"] !== void 0 && { DeliveryDestinationName: physicalId },
16806
17103
  DeliveryDestinationPolicy: policy.value
16807
17104
  };
16808
17105
  try {
@@ -16834,7 +17131,7 @@ var LogsDeliveryDestinationProvider = class {
16834
17131
  if (block === void 0) return void 0;
16835
17132
  let problem;
16836
17133
  const document = policyDocument$1(block);
16837
- if (!isPlainRecord$3(block)) problem = "DeliveryDestinationPolicy must be an object";
17134
+ if (!isPlainRecord$2(block)) problem = "DeliveryDestinationPolicy must be an object";
16838
17135
  else if (block["DeliveryDestinationName"] !== void 0 && block["DeliveryDestinationName"] !== name) problem = "DeliveryDestinationPolicy.DeliveryDestinationName must equal the destination Name";
16839
17136
  else if (document === void 0) problem = "DeliveryDestinationPolicy.DeliveryDestinationPolicy must be a policy document object";
16840
17137
  if (problem === void 0) return document;
@@ -16857,9 +17154,9 @@ var LogsDeliveryDestinationProvider = class {
16857
17154
  }
16858
17155
  };
16859
17156
  function policyDocument$1(block) {
16860
- if (!isPlainRecord$3(block)) return void 0;
17157
+ if (!isPlainRecord$2(block)) return void 0;
16861
17158
  const document = block["DeliveryDestinationPolicy"];
16862
- if (isPlainRecord$3(document)) return JSON.stringify(document);
17159
+ if (isPlainRecord$2(document)) return JSON.stringify(document);
16863
17160
  }
16864
17161
  function parsePolicy(policy) {
16865
17162
  try {
@@ -17730,6 +18027,7 @@ async function create$32(logicalId, resourceType, properties, context) {
17730
18027
 
17731
18028
  // src/provisioning/providers/secretsmanager-secret/update.ts
17732
18029
  async function update$33(logicalId, physicalId, resourceType, properties, previousProperties, context) {
18030
+ clearTagWrites("AWS::SecretsManager::Secret", (id) => id === physicalId);
17733
18031
  const log = this.operationSinks(context?.maskSecrets, [
17734
18032
  [properties["Name"], properties["Name"]],
17735
18033
  [properties["Name"], physicalId],
@@ -17761,17 +18059,23 @@ async function update$33(logicalId, physicalId, resourceType, properties, previo
17761
18059
  const tagPlan = planTagDiff(previousProperties["Tags"], properties["Tags"]);
17762
18060
  const tagWarning = tagPlanWarning(tagPlan, resourceType, logicalId);
17763
18061
  if (tagWarning !== void 0) log.warn(tagWarning);
17764
- if (tagPlan.remove.length > 0) await this.smClient.send(new UntagResourceCommand$5({
17765
- SecretId: physicalId,
17766
- TagKeys: tagPlan.remove
17767
- }));
17768
- if (tagPlan.set.size > 0) await this.smClient.send(new TagResourceCommand$5({
17769
- SecretId: physicalId,
17770
- Tags: [...tagPlan.set].map(([Key, Value]) => ({
17771
- Key,
17772
- Value
17773
- }))
17774
- }));
18062
+ if (tagPlan.remove.length > 0) {
18063
+ await this.smClient.send(new UntagResourceCommand$5({
18064
+ SecretId: physicalId,
18065
+ TagKeys: tagPlan.remove
18066
+ }));
18067
+ recordTagWrite("AWS::SecretsManager::Secret", physicalId, [], tagPlan.remove);
18068
+ }
18069
+ if (tagPlan.set.size > 0) {
18070
+ await this.smClient.send(new TagResourceCommand$5({
18071
+ SecretId: physicalId,
18072
+ Tags: [...tagPlan.set].map(([Key, Value]) => ({
18073
+ Key,
18074
+ Value
18075
+ }))
18076
+ }));
18077
+ recordTagWrite("AWS::SecretsManager::Secret", physicalId, [...tagPlan.set], []);
18078
+ }
17775
18079
  if (tagPlan.remove.length > 0 || tagPlan.set.size > 0) log.debug(`Updated tags for secret ${v(physicalId)}`);
17776
18080
  const newReplicas = properties["ReplicaRegions"];
17777
18081
  const oldReplicas = previousProperties["ReplicaRegions"];
@@ -17945,7 +18249,9 @@ function generateSecretString(config, options) {
17945
18249
  }
17946
18250
 
17947
18251
  // src/provisioning/providers/secretsmanager-secret/read-state.ts
17948
- async function readCurrentState$32(physicalId, _logicalId, _resourceType) {
18252
+ async function readCurrentState$32(physicalId, logicalId, _resourceType, properties, context) {
18253
+ const tagsWritten = context?.afterOwnWrite === true ? takeTagWrite("AWS::SecretsManager::Secret", physicalId) : void 0;
18254
+ const tagsSettle = properties !== void 0 && Object.keys(properties).length > 0 ? tagsWritten : void 0;
17949
18255
  try {
17950
18256
  const resp = await this.smClient.send(new DescribeSecretCommand({ SecretId: physicalId }));
17951
18257
  const result = {};
@@ -17958,7 +18264,8 @@ async function readCurrentState$32(physicalId, _logicalId, _resourceType) {
17958
18264
  if (r.KmsKeyId) out["KmsKeyId"] = r.KmsKeyId;
17959
18265
  return out;
17960
18266
  });
17961
- result["Tags"] = normalizeAwsTagsToCfn(resp.Tags);
18267
+ const tags = normalizeAwsTagsToCfn(resp.Tags);
18268
+ result["Tags"] = tagsSettle === void 0 ? tags : await this.settleSecretTags(physicalId, logicalId, tags, tagsSettle);
17962
18269
  if (resp.Type !== void 0) result["Type"] = resp.Type;
17963
18270
  return result;
17964
18271
  } catch (err) {
@@ -17966,6 +18273,9 @@ async function readCurrentState$32(physicalId, _logicalId, _resourceType) {
17966
18273
  throw err;
17967
18274
  }
17968
18275
  }
18276
+ async function settleSecretTags(physicalId, logicalId, first, written) {
18277
+ return settleWrittenTags(() => Promise.resolve(first), async () => normalizeAwsTagsToCfn((await this.smClient.send(new DescribeSecretCommand({ SecretId: physicalId }))).Tags), written, this.tagsBaselineRereadDelaysMs, () => warnUnsettledMember(this.logger, logicalId, "AWS::SecretsManager::Secret", "Tags"));
18278
+ }
17969
18279
  async function importImpl$32(input) {
17970
18280
  if (input.knownPhysicalId) try {
17971
18281
  const resp = await this.smClient.send(new DescribeSecretCommand({ SecretId: input.knownPhysicalId }));
@@ -18067,8 +18377,12 @@ var SecretsManagerSecretProvider = class {
18067
18377
  generateSecretString(config, options) {
18068
18378
  return generateSecretString.call(this, config, options);
18069
18379
  }
18070
- readCurrentState(physicalId, logicalId, resourceType) {
18071
- return readCurrentState$32.call(this, physicalId, logicalId, resourceType);
18380
+ readCurrentState(physicalId, logicalId, resourceType, properties, context) {
18381
+ return readCurrentState$32.call(this, physicalId, logicalId, resourceType, properties, context);
18382
+ }
18383
+ tagsBaselineRereadDelaysMs = TAGS_BASELINE_REREAD_DELAYS_MS;
18384
+ settleSecretTags(...args) {
18385
+ return settleSecretTags.call(this, ...args);
18072
18386
  }
18073
18387
  getDriftUnknownPaths() {
18074
18388
  return ["SecretString", "GenerateSecretString"];
@@ -18882,6 +19196,7 @@ function sortKeys$1(value) {
18882
19196
  var EventBridgeBusProvider = class {
18883
19197
  eventBridgeClient;
18884
19198
  logger = getLogger().child("EventBridgeBusProvider");
19199
+ ownWriteRereadDelaysMs = OWN_WRITE_REREAD_DELAYS_MS;
18885
19200
  handledProperties = /* @__PURE__ */ new Map([["AWS::Events::EventBus", /* @__PURE__ */ new Set([
18886
19201
  "Name",
18887
19202
  "Tags",
@@ -19111,7 +19426,18 @@ var EventBridgeBusProvider = class {
19111
19426
  if (attributeName === "Name") return Promise.resolve(physicalId);
19112
19427
  return Promise.resolve(void 0);
19113
19428
  }
19114
- async readCurrentState(physicalId, _logicalId, _resourceType) {
19429
+ async readCurrentState(physicalId, logicalId, _resourceType, properties, context) {
19430
+ const result = await this.readBus(physicalId);
19431
+ const declared = context?.afterOwnWrite === true ? declaredMemberDocument(properties?.["Policy"]) : void 0;
19432
+ if (declared === void 0 || typeof result !== "object") return result;
19433
+ const settled = await settleDeclaredMember(result["Policy"] === void 0 ? "absent" : { value: result["Policy"] }, async () => {
19434
+ const resp = await this.eventBridgeClient.send(new DescribeEventBusCommand({ Name: physicalId }));
19435
+ return resp.Policy ? { value: parseBusPolicy(resp.Policy) } : "absent";
19436
+ }, (value) => declaredStatementsRead(value, declared), declared, this.ownWriteRereadDelaysMs, () => warnUnsettledMember(this.logger, logicalId, "AWS::Events::EventBus", "Policy"));
19437
+ if (typeof settled === "object") result["Policy"] = settled.value;
19438
+ return result;
19439
+ }
19440
+ async readBus(physicalId) {
19115
19441
  try {
19116
19442
  const resp = await this.eventBridgeClient.send(new DescribeEventBusCommand({ Name: physicalId }));
19117
19443
  const result = {};
@@ -19125,11 +19451,7 @@ var EventBridgeBusProvider = class {
19125
19451
  if (resp.LogConfig.Level !== void 0) lc["Level"] = resp.LogConfig.Level;
19126
19452
  if (Object.keys(lc).length > 0) result["LogConfig"] = lc;
19127
19453
  }
19128
- if (resp.Policy) try {
19129
- result["Policy"] = JSON.parse(resp.Policy);
19130
- } catch {
19131
- result["Policy"] = resp.Policy;
19132
- }
19454
+ if (resp.Policy) result["Policy"] = parseBusPolicy(resp.Policy);
19133
19455
  if (resp.Arn) try {
19134
19456
  const tagsResp = await this.eventBridgeClient.send(new ListTagsForResourceCommand$1({ ResourceARN: resp.Arn }));
19135
19457
  result["Tags"] = normalizeAwsTagsToCfn(tagsResp.Tags);
@@ -19161,6 +19483,24 @@ var EventBridgeBusProvider = class {
19161
19483
  function isBusHasRulesRefusal(error) {
19162
19484
  return error instanceof Error && error.name === "ValidationException" && /has rules/i.test(error.message);
19163
19485
  }
19486
+ function parseBusPolicy(policy) {
19487
+ try {
19488
+ return JSON.parse(policy);
19489
+ } catch {
19490
+ return policy;
19491
+ }
19492
+ }
19493
+ function declaredStatementsRead(value, declared) {
19494
+ const statements = (doc) => {
19495
+ if (typeof doc !== "object" || doc === null || Array.isArray(doc)) return void 0;
19496
+ const s = doc["Statement"];
19497
+ return s === void 0 ? void 0 : Array.isArray(s) ? s : [s];
19498
+ };
19499
+ const read = statements(value);
19500
+ const want = statements(declared);
19501
+ if (read === void 0 || want === void 0) return policyDocumentMatchesDeclared(value, declared);
19502
+ return want.every((statement) => read.some((entry) => policyDocumentMatchesDeclared({ Statement: [entry] }, { Statement: [statement] })));
19503
+ }
19164
19504
 
19165
19505
  // src/provisioning/providers/eventbridge-archive-provider.ts
19166
19506
  const RESOURCE_TYPE = "AWS::Events::Archive";
@@ -19425,272 +19765,6 @@ var EventBridgeArchiveProvider = class {
19425
19765
  }
19426
19766
  };
19427
19767
 
19428
- // src/provisioning/providers/ec2/sg-support.ts
19429
- const SG_INGRESS_IP_PROTOCOL_DEFAULT = "-1";
19430
- const SG_INGRESS_IP_PROTOCOL_PATH = "AWS::EC2::SecurityGroupIngress IpProtocol";
19431
- const SG_READBACK_RETRY_DELAY_MS = 1e3;
19432
- const securityGroupReadbackDelays = {};
19433
- const SG_RULE_PAGE_SIZE = 1e3;
19434
- const SG_RULE_ID_PATTERN = /^sgr-[0-9a-f]+$/;
19435
- function narrowIngressIpProtocol(properties, onUnusable) {
19436
- const declared = properties["IpProtocol"];
19437
- const ipProtocol = requireConfigString(declared, SG_INGRESS_IP_PROTOCOL_DEFAULT, SG_INGRESS_IP_PROTOCOL_PATH, {
19438
- coerceNumber: true,
19439
- ...onUnusable && { onUnusable }
19440
- });
19441
- if (declared === void 0 || declared === ipProtocol) return {
19442
- ipProtocol,
19443
- narrowed: properties
19444
- };
19445
- return {
19446
- ipProtocol,
19447
- narrowed: {
19448
- ...properties,
19449
- IpProtocol: ipProtocol
19450
- }
19451
- };
19452
- }
19453
- function canonicalizeSgRuleProtocol(rule) {
19454
- if (!("IpProtocol" in rule)) return rule;
19455
- const next = canonicalizeIpProtocolValue(rule["IpProtocol"]);
19456
- if (next === rule["IpProtocol"]) return rule;
19457
- return {
19458
- ...rule,
19459
- IpProtocol: next
19460
- };
19461
- }
19462
- function canonicalizeSgInlineRuleProtocols(properties) {
19463
- let out = properties;
19464
- for (const key of ["SecurityGroupIngress", "SecurityGroupEgress"]) {
19465
- const list = out[key];
19466
- if (!Array.isArray(list)) continue;
19467
- let changed = false;
19468
- const mapped = list.map((el) => {
19469
- if (el === null || typeof el !== "object" || Array.isArray(el)) return el;
19470
- const next = canonicalizeSgRuleProtocol(el);
19471
- if (next !== el) changed = true;
19472
- return next;
19473
- });
19474
- if (changed) out = {
19475
- ...out,
19476
- [key]: mapped
19477
- };
19478
- }
19479
- return out;
19480
- }
19481
- function flattenIpPermissions(perms, direction) {
19482
- const out = [];
19483
- for (const p of perms) {
19484
- const base = {};
19485
- if (p.IpProtocol !== void 0) base["IpProtocol"] = p.IpProtocol;
19486
- if (p.FromPort !== void 0) base["FromPort"] = p.FromPort;
19487
- if (p.ToPort !== void 0) base["ToPort"] = p.ToPort;
19488
- for (const ip of p.IpRanges ?? []) {
19489
- const rule = { ...base };
19490
- if (ip.CidrIp !== void 0) rule["CidrIp"] = ip.CidrIp;
19491
- if (ip.Description !== void 0) rule["Description"] = ip.Description;
19492
- out.push(rule);
19493
- }
19494
- for (const ipv6 of p.Ipv6Ranges ?? []) {
19495
- const rule = { ...base };
19496
- if (ipv6.CidrIpv6 !== void 0) rule["CidrIpv6"] = ipv6.CidrIpv6;
19497
- if (ipv6.Description !== void 0) rule["Description"] = ipv6.Description;
19498
- out.push(rule);
19499
- }
19500
- for (const grp of p.UserIdGroupPairs ?? []) {
19501
- const rule = { ...base };
19502
- if (direction === "ingress") {
19503
- if (grp.GroupId !== void 0) rule["SourceSecurityGroupId"] = grp.GroupId;
19504
- if (grp.UserId !== void 0) rule["SourceSecurityGroupOwnerId"] = grp.UserId;
19505
- } else if (grp.GroupId !== void 0) rule["DestinationSecurityGroupId"] = grp.GroupId;
19506
- if (grp.Description !== void 0) rule["Description"] = grp.Description;
19507
- out.push(rule);
19508
- }
19509
- for (const pl of p.PrefixListIds ?? []) {
19510
- const rule = { ...base };
19511
- if (direction === "ingress") {
19512
- if (pl.PrefixListId !== void 0) rule["SourcePrefixListId"] = pl.PrefixListId;
19513
- } else if (pl.PrefixListId !== void 0) rule["DestinationPrefixListId"] = pl.PrefixListId;
19514
- if (pl.Description !== void 0) rule["Description"] = pl.Description;
19515
- out.push(rule);
19516
- }
19517
- if ((p.IpRanges?.length ?? 0) === 0 && (p.Ipv6Ranges?.length ?? 0) === 0 && (p.UserIdGroupPairs?.length ?? 0) === 0 && (p.PrefixListIds?.length ?? 0) === 0) out.push({ ...base });
19518
- }
19519
- return out;
19520
- }
19521
- function ingressRuleIdentity(groupId, properties) {
19522
- const source = (key) => properties[key] ?? null;
19523
- return JSON.stringify({
19524
- g: groupId ?? null,
19525
- p: sgProtocolKey(properties["IpProtocol"]),
19526
- f: cfnIngressPortValue(properties["FromPort"]),
19527
- t: cfnIngressPortValue(properties["ToPort"]),
19528
- c4: source("CidrIp"),
19529
- c6: source("CidrIpv6"),
19530
- sg: source("SourceSecurityGroupId"),
19531
- sgName: source("SourceSecurityGroupName"),
19532
- sgOwner: source("SourceSecurityGroupOwnerId"),
19533
- pl: source("SourcePrefixListId")
19534
- });
19535
- }
19536
- const INGRESS_IDENTITY_KEYS = [
19537
- "IpProtocol",
19538
- "FromPort",
19539
- "ToPort",
19540
- "CidrIp",
19541
- "CidrIpv6",
19542
- "SourceSecurityGroupId",
19543
- "SourceSecurityGroupName",
19544
- "SourceSecurityGroupOwnerId",
19545
- "SourcePrefixListId"
19546
- ];
19547
- function comparableIngressIdentity(group, rule) {
19548
- if (!isPlainRecord$2(rule) || typeof group !== "string" || group === "" || isRedactedRecordedValue(group) || !INGRESS_IDENTITY_KEYS.every((key) => !isRedactedRecordedValue(rule[key])) || !Number.isFinite(cfnIngressPortValue(rule["FromPort"])) || !Number.isFinite(cfnIngressPortValue(rule["ToPort"]))) return;
19549
- return ingressRuleIdentity(group, rule);
19550
- }
19551
- function recordedSgRuleId(attributes) {
19552
- const recorded = attributes?.["Id"];
19553
- return typeof recorded === "string" && SG_RULE_ID_PATTERN.test(recorded) ? recorded : void 0;
19554
- }
19555
- function survivingRecordOfRuleId(records, selfLogicalId, ruleId) {
19556
- for (const [lid, record] of records ?? []) {
19557
- if (lid === selfLogicalId || record.resourceType !== "AWS::EC2::SecurityGroupIngress") continue;
19558
- if (recordedSgRuleId(record.attributes) === ruleId) return lid;
19559
- }
19560
- }
19561
- function stackIngressRuleHolder(records, selfLogicalId, groupId, rule, idCheck) {
19562
- if (records === void 0) return void 0;
19563
- const wanted = comparableIngressIdentity(groupId, rule);
19564
- if (wanted === void 0) return void 0;
19565
- for (const [lid, record] of records) {
19566
- if (lid === selfLogicalId) continue;
19567
- const props = record.properties;
19568
- if (record.resourceType === "AWS::EC2::SecurityGroupIngress") {
19569
- if (!isPlainRecord$2(props) || comparableIngressIdentity(props["GroupId"], props) !== wanted) continue;
19570
- const ruleId = recordedSgRuleId(record.attributes);
19571
- if (ruleId !== void 0 && idCheck !== void 0) {
19572
- if ("live" in idCheck && ruleId !== idCheck.live) continue;
19573
- if ("own" in idCheck && idCheck.own !== void 0 && ruleId !== idCheck.own) continue;
19574
- }
19575
- return lid;
19576
- }
19577
- if (record.resourceType === "AWS::EC2::SecurityGroup" && record.physicalId === groupId) {
19578
- const inline = isPlainRecord$2(props) ? props["SecurityGroupIngress"] : void 0;
19579
- if (Array.isArray(inline) && inline.some((entry) => comparableIngressIdentity(groupId, entry) === wanted)) return lid;
19580
- }
19581
- }
19582
- }
19583
- function tagListsMatch(live, declared) {
19584
- const pairs = (list) => list.every((entry) => isPlainRecord$2(entry) && typeof entry["Key"] === "string") ? list.map((entry) => {
19585
- const tag = entry;
19586
- return JSON.stringify([tag["Key"], tag["Value"] ?? ""]);
19587
- }).sort() : void 0;
19588
- const a = pairs(live);
19589
- const b = pairs(declared);
19590
- return a !== void 0 && b !== void 0 && JSON.stringify(a) === JSON.stringify(b);
19591
- }
19592
- function isPlainRecord$2(value) {
19593
- return typeof value === "object" && value !== null && !Array.isArray(value);
19594
- }
19595
- function descriptionKey(value) {
19596
- return typeof value === "string" ? value : "";
19597
- }
19598
- const NEVER_CONNECTED_SOCKET_CODES = /* @__PURE__ */ new Set([
19599
- "ECONNREFUSED",
19600
- "ENOTFOUND",
19601
- "EHOSTUNREACH",
19602
- "ENETUNREACH",
19603
- "EAI_AGAIN"
19604
- ]);
19605
- const RESENDABLE_SOCKET_CODES = /* @__PURE__ */ new Set([
19606
- "ECONNRESET",
19607
- "EPIPE",
19608
- "ETIMEDOUT",
19609
- "EADDRNOTAVAIL"
19610
- ]);
19611
- function errorCode(error) {
19612
- return error?.code;
19613
- }
19614
- function isConnectTimeout(error) {
19615
- const e = error;
19616
- return e?.name === "TimeoutError" && e.code === void 0 && typeof e.message === "string" && e.message.includes("did not establish a connection");
19617
- }
19618
- function neverReachedAws(error) {
19619
- if (isConnectTimeout(error)) return true;
19620
- const code = errorCode(error);
19621
- if (typeof code === "string" && NEVER_CONNECTED_SOCKET_CODES.has(code)) return true;
19622
- return error?.name === "CredentialsProviderError";
19623
- }
19624
- function isResendableSocketFailure(error) {
19625
- if (isConnectTimeout(error)) return false;
19626
- const code = errorCode(error);
19627
- if (typeof code === "string" && RESENDABLE_SOCKET_CODES.has(code)) return true;
19628
- return error?.name === "TimeoutError";
19629
- }
19630
- function authorizeDefinitelyNotApplied(error) {
19631
- if (neverReachedAws(error)) return true;
19632
- const e = error;
19633
- if (typeof e?.name === "string" && THROTTLING_ERROR_NAMES.has(e.name)) return true;
19634
- if (e?.$retryable?.throttling === true) return true;
19635
- const status = e?.$metadata?.httpStatusCode;
19636
- return typeof status === "number" && status >= 400 && status < 500;
19637
- }
19638
- function singleSecurityGroupRuleId(rules) {
19639
- const ids = (rules ?? []).map((rule) => rule.SecurityGroupRuleId).filter((id) => typeof id === "string" && id.trim() !== "");
19640
- return ids.length === 1 ? ids[0] : void 0;
19641
- }
19642
- function securityGroupRuleMatchesCfnIngress(rule, properties) {
19643
- if (sgProtocolKey(rule.IpProtocol) !== sgProtocolKey(properties["IpProtocol"])) return false;
19644
- if ((rule.FromPort ?? -1) !== cfnIngressPortValue(properties["FromPort"])) return false;
19645
- if ((rule.ToPort ?? -1) !== cfnIngressPortValue(properties["ToPort"])) return false;
19646
- const sources = [
19647
- [properties["CidrIp"], rule.CidrIpv4],
19648
- [properties["CidrIpv6"], rule.CidrIpv6],
19649
- [properties["SourceSecurityGroupId"], rule.ReferencedGroupInfo?.GroupId],
19650
- [properties["SourcePrefixListId"], rule.PrefixListId]
19651
- ];
19652
- for (const [declared, actual] of sources) if (declared !== void 0 && declared !== null && declared !== actual) return false;
19653
- return true;
19654
- }
19655
- function sgRuleKey(rule, direction) {
19656
- const peerKey = direction === "egress" ? rule["DestinationSecurityGroupId"] : rule["SourceSecurityGroupId"];
19657
- const prefixKey = direction === "egress" ? rule["DestinationPrefixListId"] : rule["SourcePrefixListId"];
19658
- const peerOwner = direction === "ingress" ? rule["SourceSecurityGroupOwnerId"] : void 0;
19659
- return JSON.stringify({
19660
- p: sgProtocolKey(rule["IpProtocol"]),
19661
- f: rule["FromPort"] ?? null,
19662
- t: rule["ToPort"] ?? null,
19663
- c4: rule["CidrIp"] ?? null,
19664
- c6: rule["CidrIpv6"] ?? null,
19665
- peer: peerKey ?? null,
19666
- peerOwner: peerOwner ?? null,
19667
- pl: prefixKey ?? null,
19668
- d: rule["Description"] ?? null
19669
- });
19670
- }
19671
- function reconcileSgRules(awsRules, stateRules, direction) {
19672
- if (!stateRules || stateRules.length === 0) return awsRules;
19673
- const remaining = [...awsRules];
19674
- const reordered = [];
19675
- for (const sr of stateRules) {
19676
- const key = sgRuleKey(sr, direction);
19677
- const idx = remaining.findIndex((ar) => sgRuleKey(ar, direction) === key);
19678
- if (idx >= 0) reordered.push(remaining.splice(idx, 1)[0]);
19679
- }
19680
- return [...reordered, ...remaining];
19681
- }
19682
- function isDefaultEgressRule(rule) {
19683
- if (rule["IpProtocol"] !== "-1") return false;
19684
- if (rule["CidrIp"] !== "0.0.0.0/0") return false;
19685
- if (rule["CidrIpv6"] !== void 0) return false;
19686
- if (rule["DestinationSecurityGroupId"] !== void 0) return false;
19687
- if (rule["DestinationPrefixListId"] !== void 0) return false;
19688
- if (rule["Description"] !== void 0) return false;
19689
- if (rule["FromPort"] !== void 0 && rule["FromPort"] !== -1) return false;
19690
- if (rule["ToPort"] !== void 0 && rule["ToPort"] !== -1) return false;
19691
- return true;
19692
- }
19693
-
19694
19768
  // src/provisioning/providers/ec2/common.ts
19695
19769
  function isEc2NotFoundCode(error) {
19696
19770
  const name = error?.name;
@@ -22310,6 +22384,7 @@ async function applyInlineEgress(groupId, egressRules) {
22310
22384
  async function updateSecurityGroup(logicalId, physicalId, resourceType, properties, previousProperties, context) {
22311
22385
  this.logger.debug(`Updating SecurityGroup ${logicalId}: ${physicalId}`);
22312
22386
  refuseMalformedDesiredTags(properties["Tags"], resourceType, logicalId, physicalId);
22387
+ if (context?.desiredFromAwsReadback === true && (context.siblingSgRuleIds?.size ?? 0) > 0) await refuseRevertRevokingSiblingRules((group) => this.listGroupRules(group), logicalId, physicalId, resourceType, properties, previousProperties, context.siblingSgRuleIds);
22313
22388
  try {
22314
22389
  await this.applyTagDiff(physicalId, resourceType, logicalId, previousProperties["Tags"], properties["Tags"], maskerOrIdentity(context?.maskSecrets));
22315
22390
  await this.applySecurityGroupRuleDiff(physicalId, previousProperties["SecurityGroupIngress"] ?? [], properties["SecurityGroupIngress"] ?? [], "ingress", logicalId);
@@ -22447,23 +22522,7 @@ function buildIpPermission(properties, direction = "ingress", inline = false) {
22447
22522
  return permission;
22448
22523
  }
22449
22524
  async function applySecurityGroupRuleDiff(groupId, previousRules, nextRules, direction, logicalId) {
22450
- const ruleKey = (rule) => {
22451
- const peerKey = direction === "egress" ? rule["DestinationSecurityGroupId"] : rule["SourceSecurityGroupId"];
22452
- const prefixKey = direction === "egress" ? rule["DestinationPrefixListId"] : rule["SourcePrefixListId"];
22453
- const peerOwner = direction === "ingress" ? rule["SourceSecurityGroupOwnerId"] : void 0;
22454
- const peerName = direction === "ingress" ? rule["SourceSecurityGroupName"] : void 0;
22455
- return JSON.stringify({
22456
- p: sgProtocolKey(rule["IpProtocol"]),
22457
- f: rule["FromPort"] ?? null,
22458
- t: rule["ToPort"] ?? null,
22459
- c4: rule["CidrIp"] ?? null,
22460
- c6: rule["CidrIpv6"] ?? null,
22461
- peer: peerKey ?? null,
22462
- peerName: peerKey ? null : peerName ?? null,
22463
- peerOwner: peerOwner ?? null,
22464
- pl: prefixKey ?? null
22465
- });
22466
- };
22525
+ const ruleKey = (rule) => sgRuleDiffKey(rule, direction);
22467
22526
  const prevByKey = /* @__PURE__ */ new Map();
22468
22527
  for (const rule of previousRules) prevByKey.set(ruleKey(rule), rule);
22469
22528
  const nextByKey = /* @__PURE__ */ new Map();
@@ -22678,12 +22737,15 @@ async function settledInFlightIngressHolder(logicalId, resourceType, groupId, de
22678
22737
  }
22679
22738
  }
22680
22739
  async function listGroupRules(groupId) {
22740
+ return listSecurityGroupRules(this.ec2Client, groupId);
22741
+ }
22742
+ async function listSecurityGroupRules(client, groupId) {
22681
22743
  const rules = [];
22682
22744
  let nextToken;
22683
22745
  let pages = 0;
22684
22746
  do {
22685
22747
  if (pages >= 20) return void 0;
22686
- const resp = await this.ec2Client.send(new DescribeSecurityGroupRulesCommand({
22748
+ const resp = await client.send(new DescribeSecurityGroupRulesCommand({
22687
22749
  Filters: [{
22688
22750
  Name: "group-id",
22689
22751
  Values: [groupId]
@@ -25079,7 +25141,7 @@ async function readUnsettled$5(physicalId, logicalId, resourceType, names, recor
25079
25141
  if (resourceType === "AWS::EC2::Subnet") return this.readSubnetCurrentState(physicalId, names, recordedProperties);
25080
25142
  return this.readCurrentState(physicalId, logicalId, resourceType, recordedProperties);
25081
25143
  }
25082
- async function canonicalizeDriftPair$3(resourceType, baseline, aws, properties) {
25144
+ async function canonicalizeDriftPair$4(resourceType, baseline, aws, properties) {
25083
25145
  if (resourceType === "AWS::EC2::Instance") {
25084
25146
  const declared = declaredBlockDeviceNames(properties);
25085
25147
  const recorded = baseline["BlockDeviceMappings"];
@@ -25253,7 +25315,7 @@ const driftMethods = {
25253
25315
  subnetIpv6InTransition,
25254
25316
  unsettledInTransition: unsettledInTransition$4,
25255
25317
  readUnsettled: readUnsettled$5,
25256
- canonicalizeDriftPair: canonicalizeDriftPair$3,
25318
+ canonicalizeDriftPair: canonicalizeDriftPair$4,
25257
25319
  canonicalizeUnsettledProperties: canonicalizeUnsettledProperties$1,
25258
25320
  readCurrentState: readCurrentState$30,
25259
25321
  readCurrentStateOnce,
@@ -25379,20 +25441,50 @@ async function readRouteTableCurrentState(physicalId) {
25379
25441
  async function readSecurityGroupCurrentState(physicalId, properties, context) {
25380
25442
  const sg = (await this.ec2Client.send(new DescribeSecurityGroupsCommand({ GroupIds: [physicalId] }))).SecurityGroups?.[0];
25381
25443
  if (!sg) return RESOURCE_NOT_FOUND;
25444
+ const idOwned = await siblingIdOwnedSgRules(this, physicalId, properties, context);
25382
25445
  const result = {};
25383
25446
  if (sg.GroupName !== void 0) result["GroupName"] = sg.GroupName;
25384
25447
  if (sg.Description !== void 0) result["GroupDescription"] = sg.Description;
25385
25448
  if (sg.VpcId !== void 0) result["VpcId"] = sg.VpcId;
25386
25449
  const tags = normalizeAwsTagsToCfn(sg.Tags);
25387
25450
  if (tags.length > 0) result["Tags"] = tags;
25451
+ Object.assign(result, sgRuleLists(sg, physicalId, properties, context, idOwned));
25452
+ if (context?.afterOwnWrite === true && properties !== void 0) {
25453
+ const members = [];
25454
+ for (const [key, direction] of [["SecurityGroupIngress", "ingress"], ["SecurityGroupEgress", "egress"]]) {
25455
+ const declared = properties[key];
25456
+ if (!Array.isArray(declared)) continue;
25457
+ members.push({
25458
+ key,
25459
+ declared,
25460
+ matches: (value) => declaredSgRulesRead(value, declared, direction),
25461
+ whenUnsettled: (newest) => reconcileSgRules(mergeDeclaredSgRules(newest, declared, direction), declared, direction),
25462
+ read: async () => {
25463
+ const group = (await this.ec2Client.send(new DescribeSecurityGroupsCommand({ GroupIds: [physicalId] }))).SecurityGroups?.[0];
25464
+ return group ? { value: sgRuleLists(group, physicalId, properties, context, idOwned)[key] } : "failed";
25465
+ }
25466
+ });
25467
+ }
25468
+ await settleOwnWriteMembers(result, members, OWN_WRITE_REREAD_DELAYS_MS, (key) => warnUnsettledMember(this.logger, physicalId, "AWS::EC2::SecurityGroup", key));
25469
+ }
25470
+ return result;
25471
+ }
25472
+ function sgRuleLists(sg, physicalId, properties, context, idOwned) {
25473
+ const owned = (direction) => {
25474
+ if (idOwned === void 0) return siblingOwnedSgRuleIdentities(physicalId, direction, properties, context);
25475
+ const out = siblingOwnedSgRuleIdentities(physicalId, direction, properties, context, (lid) => idOwned.decided.has(lid));
25476
+ for (const identity of idOwned.owned[direction]) out.add(identity);
25477
+ return out;
25478
+ };
25388
25479
  const stateIngress = Array.isArray(properties?.["SecurityGroupIngress"]) ? properties["SecurityGroupIngress"] : void 0;
25389
- const ingressRules = withoutSiblingOwnedSgRules(flattenIpPermissions(sg.IpPermissions ?? [], "ingress"), siblingOwnedSgRuleIdentities(physicalId, "ingress", properties, context), "ingress");
25390
- result["SecurityGroupIngress"] = reconcileSgRules(ingressRules, stateIngress, "ingress");
25480
+ const ingressRules = withoutSiblingOwnedSgRules(flattenIpPermissions(sg.IpPermissions ?? [], "ingress"), owned("ingress"), "ingress");
25391
25481
  const stateEgress = Array.isArray(properties?.["SecurityGroupEgress"]) ? properties["SecurityGroupEgress"] : void 0;
25392
- let egressRules = withoutSiblingOwnedSgRules(flattenIpPermissions(sg.IpPermissionsEgress ?? [], "egress"), siblingOwnedSgRuleIdentities(physicalId, "egress", properties, context), "egress");
25482
+ let egressRules = withoutSiblingOwnedSgRules(flattenIpPermissions(sg.IpPermissionsEgress ?? [], "egress"), owned("egress"), "egress");
25393
25483
  if (stateEgress === void 0) egressRules = egressRules.filter((r) => !isDefaultEgressRule(r));
25394
- result["SecurityGroupEgress"] = reconcileSgRules(egressRules, stateEgress, "egress");
25395
- return result;
25484
+ return {
25485
+ SecurityGroupIngress: reconcileSgRules(ingressRules, stateIngress, "ingress"),
25486
+ SecurityGroupEgress: reconcileSgRules(egressRules, stateEgress, "egress")
25487
+ };
25396
25488
  }
25397
25489
  async function readNetworkAclCurrentState(physicalId) {
25398
25490
  const acl = (await this.ec2Client.send(new DescribeNetworkAclsCommand({ NetworkAclIds: [physicalId] }))).NetworkAcls?.[0];
@@ -25484,6 +25576,14 @@ async function readSecurityGroupIngressCurrentState(physicalId, properties, cont
25484
25576
  const protocol = parts[1];
25485
25577
  const fromPort = parts[2] === "-1" ? void 0 : parseInt(parts[2], 10);
25486
25578
  const toPort = parts[3] === "-1" ? void 0 : parseInt(parts[3], 10);
25579
+ if (properties && Object.keys(properties).length > 0) {
25580
+ const byId = await readSgIngressById(this, groupId, properties, context);
25581
+ if (byId === "gone") return RESOURCE_NOT_FOUND;
25582
+ if (byId !== "fallback") return {
25583
+ GroupId: groupId,
25584
+ ...byId
25585
+ };
25586
+ }
25487
25587
  const sg = (await this.ec2Client.send(new DescribeSecurityGroupsCommand({ GroupIds: [groupId] }))).SecurityGroups?.[0];
25488
25588
  if (!sg) return RESOURCE_NOT_FOUND;
25489
25589
  const wantedProtocol = sgProtocolKey(protocol);
@@ -28580,7 +28680,7 @@ function getDriftUnknownPaths$8(resourceType, properties) {
28580
28680
  if (resourceType === "AWS::ApiGatewayV2::Integration" && properties !== void 0 && Object.keys(properties).length > 0 && properties["ConnectionType"] !== "VPC_LINK") return ["TlsConfig"];
28581
28681
  return [];
28582
28682
  }
28583
- async function canonicalizeDriftPair$2(resourceType, baseline, aws, properties = {}) {
28683
+ async function canonicalizeDriftPair$3(resourceType, baseline, aws, properties = {}) {
28584
28684
  if (resourceType !== "AWS::ApiGatewayV2::Api" && resourceType !== "AWS::ApiGatewayV2::Stage") return {
28585
28685
  baseline,
28586
28686
  aws
@@ -30025,7 +30125,7 @@ var ApiGatewayV2Provider = class {
30025
30125
  return getDriftUnknownPaths$8.call(this, resourceType, properties);
30026
30126
  }
30027
30127
  canonicalizeDriftPair(resourceType, baseline, aws, properties = {}) {
30028
- return canonicalizeDriftPair$2.call(this, resourceType, baseline, aws, properties);
30128
+ return canonicalizeDriftPair$3.call(this, resourceType, baseline, aws, properties);
30029
30129
  }
30030
30130
  readCurrentState(physicalId, _logicalId, resourceType, properties) {
30031
30131
  return readCurrentState$28.call(this, physicalId, _logicalId, resourceType, properties);
@@ -35962,7 +36062,7 @@ function getDriftUnorderedPaths$4(resourceType) {
35962
36062
  if (resourceType !== "AWS::ElasticLoadBalancingV2::TargetGroup") return [];
35963
36063
  return ["Targets"];
35964
36064
  }
35965
- async function canonicalizeDriftPair$1(resourceType, baseline, aws, properties) {
36065
+ async function canonicalizeDriftPair$2(resourceType, baseline, aws, properties) {
35966
36066
  const unchanged = {
35967
36067
  baseline,
35968
36068
  aws
@@ -36365,7 +36465,7 @@ var ELBv2Provider = class {
36365
36465
  return getDriftUnorderedPaths$4.call(this, resourceType);
36366
36466
  }
36367
36467
  canonicalizeDriftPair(resourceType, baseline, aws, properties) {
36368
- return canonicalizeDriftPair$1.call(this, resourceType, baseline, aws, properties);
36468
+ return canonicalizeDriftPair$2.call(this, resourceType, baseline, aws, properties);
36369
36469
  }
36370
36470
  readListener(physicalId) {
36371
36471
  return readListener.call(this, physicalId);
@@ -39594,7 +39694,7 @@ var DocDBSubnetGroupProvider = class {
39594
39694
  };
39595
39695
 
39596
39696
  // src/provisioning/providers/appconfig-environment-provider.ts
39597
- const TYPE = "AWS::AppConfig::Environment";
39697
+ const TYPE$2 = "AWS::AppConfig::Environment";
39598
39698
  const DELETION_PROTECTION_CHECKS = /* @__PURE__ */ new Set([
39599
39699
  "ACCOUNT_DEFAULT",
39600
39700
  "APPLY",
@@ -39620,7 +39720,7 @@ var AppConfigEnvironmentProvider = class {
39620
39720
  return this.appConfigClient;
39621
39721
  }
39622
39722
  assertType(resourceType, logicalId, physicalId) {
39623
- if (resourceType !== TYPE) throw new ProvisioningError(`Unsupported resource type: ${resourceType}`, resourceType, logicalId, physicalId);
39723
+ if (resourceType !== TYPE$2) throw new ProvisioningError(`Unsupported resource type: ${resourceType}`, resourceType, logicalId, physicalId);
39624
39724
  }
39625
39725
  splitId(physicalId, resourceType, logicalId) {
39626
39726
  const idx = physicalId.indexOf("|");
@@ -39746,7 +39846,7 @@ var AppConfigEnvironmentProvider = class {
39746
39846
  }
39747
39847
  }
39748
39848
  async import(input) {
39749
- if (input.resourceType !== TYPE || !input.knownPhysicalId) return null;
39849
+ if (input.resourceType !== TYPE$2 || !input.knownPhysicalId) return null;
39750
39850
  const { applicationId, environmentId } = this.splitId(input.knownPhysicalId, input.resourceType, input.logicalId);
39751
39851
  try {
39752
39852
  await this.getClient().send(new GetEnvironmentCommand({
@@ -39881,11 +39981,6 @@ function recordSetCompositeId(hostedZoneId, name, type) {
39881
39981
  type
39882
39982
  ].map(String).join("|");
39883
39983
  }
39884
- const UNDECODABLE_OCTAL_ESCAPES = /* @__PURE__ */ new Set(["056", "134"]);
39885
- function normalizeRecordName(name) {
39886
- const lowered = name.replace(/\\([0-7]{3})/g, (match, oct) => UNDECODABLE_OCTAL_ESCAPES.has(oct) ? match : String.fromCharCode(parseInt(oct, 8))).toLowerCase();
39887
- return lowered.endsWith(".") ? lowered : `${lowered}.`;
39888
- }
39889
39984
  function isIntrinsicOnly(value) {
39890
39985
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
39891
39986
  const keys = Object.keys(value);
@@ -39970,6 +40065,23 @@ function withTemplateAliasConflicts(recordSet, properties) {
39970
40065
  ...declaresRecords && { ResourceRecords: records.map((r) => typeof r === "string" ? { Value: r } : r) }
39971
40066
  };
39972
40067
  }
40068
+ function revertedRecordMode(properties, previousProperties) {
40069
+ const isAlias = (bag) => bag["AliasTarget"] != null;
40070
+ const isSimple = (bag) => bag["ResourceRecords"] != null || bag["TTL"] != null;
40071
+ if (!isAlias(properties) || !isSimple(properties)) return properties;
40072
+ if (isAlias(previousProperties) && !isSimple(previousProperties)) {
40073
+ const { AliasTarget: _alias, ...simple } = properties;
40074
+ return simple;
40075
+ }
40076
+ if (isSimple(previousProperties) && !isAlias(previousProperties)) {
40077
+ const { TTL: _ttl, ResourceRecords: _records, ...alias } = properties;
40078
+ return alias;
40079
+ }
40080
+ return properties;
40081
+ }
40082
+ function isMatchableSetIdentifier(value) {
40083
+ return typeof value === "string" && !value.includes("{{resolve:");
40084
+ }
39973
40085
 
39974
40086
  // src/provisioning/providers/route53/hosted-zone.ts
39975
40087
  async function createHostedZone(logicalId, resourceType, properties, mask, context) {
@@ -40457,7 +40569,7 @@ async function updateRecordSet(logicalId, physicalId, resourceType, properties,
40457
40569
  const compositeId = recordSetCompositeId(hostedZoneId, recordName, recordType);
40458
40570
  const identityChanged = context?.desiredFromAwsReadback !== true && recordIdentityChanged(previousProperties, properties);
40459
40571
  try {
40460
- const resourceRecordSet = stateBorne ? this.buildResourceRecordSet(properties) : withTemplateAliasConflicts(this.buildResourceRecordSet(properties), properties);
40572
+ const resourceRecordSet = stateBorne ? this.buildResourceRecordSet(context?.desiredFromAwsReadback === true ? revertedRecordMode(properties, previousProperties) : properties) : withTemplateAliasConflicts(this.buildResourceRecordSet(properties), properties);
40461
40573
  const comment = properties["Comment"];
40462
40574
  const liveOldRecord = identityChanged ? await this.findLiveRecordSet(hostedZoneId, previousProperties) : void 0;
40463
40575
  if (identityChanged && !liveOldRecord) this.logger.debug(safeMsg`Record set ${logicalId}: the previous record is not live in ${hostedZoneId}; writing the renamed record only`);
@@ -40966,7 +41078,8 @@ async function readRecordSetGroup(physicalId, logicalId, properties) {
40966
41078
  name,
40967
41079
  type
40968
41080
  }, recordBag(record));
40969
- if (live === void 0 || live === RESOURCE_NOT_FOUND) return live;
41081
+ if (live === void 0) return void 0;
41082
+ if (live === RESOURCE_NOT_FOUND) continue;
40970
41083
  const { HostedZoneId: _zoneId, ...rest } = live;
40971
41084
  observed.push({
40972
41085
  ...rest,
@@ -40974,11 +41087,40 @@ async function readRecordSetGroup(physicalId, logicalId, properties) {
40974
41087
  ...record["HostedZoneName"] !== void 0 ? { HostedZoneName: record["HostedZoneName"] } : {}
40975
41088
  });
40976
41089
  }
40977
- return { RecordSets: observed };
41090
+ if (observed.length === 0 && parsed.records.length > 0) return RESOURCE_NOT_FOUND;
41091
+ const groupZone = {};
41092
+ for (const key of ["HostedZoneId", "HostedZoneName"]) if (properties?.[key] !== void 0) groupZone[key] = properties[key];
41093
+ return {
41094
+ ...groupZone,
41095
+ RecordSets: observed
41096
+ };
41097
+ }
41098
+ async function importRecordSetGroupFromTemplate(input) {
41099
+ const parsed = groupRecordSets(input.properties);
41100
+ if ("refusal" in parsed || parsed.records.length === 0) return null;
41101
+ const zoneProps = groupZoneProperties(input.properties, parsed.records);
41102
+ if ("refusal" in zoneProps) return null;
41103
+ if (parsed.records.some((r) => r["SetIdentifier"] !== void 0 && !isMatchableSetIdentifier(r["SetIdentifier"]))) return null;
41104
+ let hostedZoneId;
41105
+ try {
41106
+ hostedZoneId = await this.resolveHostedZoneId(zoneProps.zone, input.logicalId, input.resourceType, input.logicalId, {
41107
+ requireUnambiguousZoneName: true,
41108
+ subject: groupSubject
41109
+ });
41110
+ } catch {
41111
+ return null;
41112
+ }
41113
+ const physicalId = recordSetGroupCompositeId(hostedZoneId, input.logicalId);
41114
+ const observed = await readRecordSetGroup.call(this, physicalId, input.logicalId, input.properties);
41115
+ if (!observed || observed === RESOURCE_NOT_FOUND || !Array.isArray(observed["RecordSets"]) || observed["RecordSets"].length !== parsed.records.length) return null;
41116
+ return {
41117
+ physicalId,
41118
+ attributes: {}
41119
+ };
40978
41120
  }
40979
41121
  async function importRecordSetGroup(input) {
40980
41122
  const known = input.knownPhysicalId;
40981
- if (!known) return null;
41123
+ if (!known) return importRecordSetGroupFromTemplate.call(this, input);
40982
41124
  const adoptVerbatim = (reason) => {
40983
41125
  this.logger.warn(safeMsg`Record set group ${input.logicalId}: could not verify physical id '${known}' (${reason}). Adopting it as-is.`);
40984
41126
  return {
@@ -41013,7 +41155,7 @@ async function importRecordSetGroup(input) {
41013
41155
  const head = `Record set group ${input.logicalId}: verification of '${known}' failed: `;
41014
41156
  return unverified(`verification failed: ${this.warnFailureText(head, err, void 0).replace(/\.$/, "")}`);
41015
41157
  }
41016
- if (!observed || observed === RESOURCE_NOT_FOUND) return unverified("not every record was found under the resolved hosted zone");
41158
+ if (!observed || observed === RESOURCE_NOT_FOUND || !Array.isArray(observed["RecordSets"]) || observed["RecordSets"].length !== parsed.records.length) return unverified("not every record was found under the resolved hosted zone");
41017
41159
  return {
41018
41160
  physicalId: recordSetGroupCompositeId(hostedZoneId, existingGroupName(known, input.logicalId)),
41019
41161
  attributes: {}
@@ -41328,7 +41470,43 @@ async function readHostedZone(physicalId, properties, throwOnFailedQueryLoggingR
41328
41470
  async function readRecordSet(physicalId, properties) {
41329
41471
  const identity = await this.resolveRecordSetIdentity(physicalId, properties);
41330
41472
  if (!identity) return void 0;
41331
- return this.readRecordSetAt(identity, properties);
41473
+ const zoneIsCertain = identity.hostedZoneId === parseRecordSetCompositeId(physicalId)?.hostedZoneId || typeof properties?.["HostedZoneId"] === "string" && bareHostedZoneId(properties["HostedZoneId"]) === bareHostedZoneId(identity.hostedZoneId);
41474
+ return this.readRecordSetAt(zoneIsCertain ? identity : {
41475
+ ...identity,
41476
+ zoneMayBeAmbiguous: true
41477
+ }, properties);
41478
+ }
41479
+ const POSITIONABLE_RECORD_NAME = /^[a-z0-9_.*|-]+$/;
41480
+ const ABSENCE_SCAN_MAX_PAGES = 10;
41481
+ async function recordProvablyAbsent(hostedZoneId, name, type, setIdentifier) {
41482
+ if (!POSITIONABLE_RECORD_NAME.test(name.toLowerCase())) return false;
41483
+ const queryName = canonicalizeRoute53QueryName(name);
41484
+ const wantedName = normalizeRecordName(name);
41485
+ let start = {
41486
+ name: queryName,
41487
+ type
41488
+ };
41489
+ for (let page = 0; page < ABSENCE_SCAN_MAX_PAGES; page++) {
41490
+ const resp = await this.getClient().send(new ListResourceRecordSetsCommand({
41491
+ HostedZoneId: hostedZoneId,
41492
+ StartRecordName: start.name,
41493
+ StartRecordType: start.type,
41494
+ ...start.identifier !== void 0 && { StartRecordIdentifier: start.identifier },
41495
+ MaxItems: 100
41496
+ }));
41497
+ for (const r of resp.ResourceRecordSets ?? []) {
41498
+ if (r.Name === void 0 || normalizeRecordName(r.Name) !== wantedName || r.Type !== type) return true;
41499
+ if (r.SetIdentifier === setIdentifier) return false;
41500
+ }
41501
+ if (resp.IsTruncated !== true) return true;
41502
+ if (resp.NextRecordName === void 0 || resp.NextRecordType === void 0) return false;
41503
+ start = {
41504
+ name: resp.NextRecordName,
41505
+ type: resp.NextRecordType,
41506
+ ...resp.NextRecordIdentifier !== void 0 && { identifier: resp.NextRecordIdentifier }
41507
+ };
41508
+ }
41509
+ return false;
41332
41510
  }
41333
41511
  async function readRecordSetAt(identity, properties) {
41334
41512
  const { hostedZoneId, name, type } = identity;
@@ -41350,7 +41528,7 @@ async function readRecordSetAt(identity, properties) {
41350
41528
  }
41351
41529
  const wantedName = normalizeRecordName(name);
41352
41530
  const recordSet = resp.ResourceRecordSets?.find((r) => r.Name !== void 0 && normalizeRecordName(r.Name) === wantedName && r.Type === type && (!matchSetIdentifier || r.SetIdentifier === setIdentifier));
41353
- if (!recordSet) return void 0;
41531
+ if (!recordSet) return matchSetIdentifier && identity.zoneMayBeAmbiguous !== true && await recordProvablyAbsent.call(this, hostedZoneId, name, type, setIdentifier) ? RESOURCE_NOT_FOUND : void 0;
41354
41532
  const result = {
41355
41533
  HostedZoneId: hostedZoneId,
41356
41534
  Name: name,
@@ -41422,7 +41600,7 @@ function compositeAgreesWithTemplate(parsed, properties) {
41422
41600
  }
41423
41601
  async function importRecordSet(input) {
41424
41602
  const known = input.knownPhysicalId;
41425
- if (!known) return null;
41603
+ if (!known) return importRecordSetFromTemplate.call(this, input);
41426
41604
  const parsedKnown = parseRecordSetCompositeId(known);
41427
41605
  if (parsedKnown && this.compositeAgreesWithTemplate(parsedKnown, input.properties)) return {
41428
41606
  physicalId: known,
@@ -41442,7 +41620,7 @@ async function importRecordSet(input) {
41442
41620
  const compositeId = recordSetCompositeId(identity.hostedZoneId, identity.name, identity.type);
41443
41621
  let observed;
41444
41622
  try {
41445
- observed = await this.readRecordSetAt(identity);
41623
+ observed = await this.readRecordSetAt(identity, input.properties);
41446
41624
  } catch (err) {
41447
41625
  const head = `Record set ${input.logicalId}: verification of '${known}' failed: `;
41448
41626
  return adoptVerbatim(`verification failed: ${this.warnFailureText(head, err, void 0).replace(/\.$/, "")}`);
@@ -41453,6 +41631,19 @@ async function importRecordSet(input) {
41453
41631
  attributes: {}
41454
41632
  };
41455
41633
  }
41634
+ async function importRecordSetFromTemplate(input) {
41635
+ const { Name: name, Type: type, SetIdentifier: setIdentifier } = input.properties;
41636
+ if (typeof name !== "string" || !name || typeof type !== "string" || !type) return null;
41637
+ if (setIdentifier !== void 0 && !isMatchableSetIdentifier(setIdentifier)) return null;
41638
+ const identity = await this.resolveRecordSetIdentity(name, input.properties, { requireUnambiguousZoneName: true });
41639
+ if (!identity) return null;
41640
+ const observed = await this.readRecordSetAt(identity, input.properties);
41641
+ if (!observed || observed === RESOURCE_NOT_FOUND) return null;
41642
+ return {
41643
+ physicalId: recordSetCompositeId(identity.hostedZoneId, identity.name, identity.type),
41644
+ attributes: {}
41645
+ };
41646
+ }
41456
41647
  async function hostedZoneImportAttributes(zoneId, logicalId) {
41457
41648
  try {
41458
41649
  return {
@@ -41700,21 +41891,21 @@ function sanitizeDescription(value) {
41700
41891
  if (typeof value === "string" && value.length === 0) return void 0;
41701
41892
  return value;
41702
41893
  }
41703
- function isPlainObject$2(value) {
41894
+ function isPlainObject$3(value) {
41704
41895
  return typeof value === "object" && value !== null && !Array.isArray(value);
41705
41896
  }
41706
41897
  const DATA_PROTECTION_FALSE_DEFAULTS = ["ExcludeRuleMatchDetails", "ExcludeRateBasedDetails"];
41707
41898
  function toCfnDataProtectionConfig(config, baseline) {
41708
41899
  const entries = config["DataProtections"];
41709
41900
  if (!Array.isArray(entries)) return config;
41710
- const baseEntries = isPlainObject$2(baseline) && Array.isArray(baseline["DataProtections"]) ? baseline["DataProtections"] : [];
41901
+ const baseEntries = isPlainObject$3(baseline) && Array.isArray(baseline["DataProtections"]) ? baseline["DataProtections"] : [];
41711
41902
  return {
41712
41903
  ...config,
41713
41904
  DataProtections: entries.map((entry, i) => {
41714
- if (!isPlainObject$2(entry)) return entry;
41905
+ if (!isPlainObject$3(entry)) return entry;
41715
41906
  const base = baseEntries[i];
41716
41907
  const converted = { ...entry };
41717
- for (const key of DATA_PROTECTION_FALSE_DEFAULTS) if (converted[key] === false && !(isPlainObject$2(base) && key in base)) delete converted[key];
41908
+ for (const key of DATA_PROTECTION_FALSE_DEFAULTS) if (converted[key] === false && !(isPlainObject$3(base) && key in base)) delete converted[key];
41718
41909
  return converted;
41719
41910
  })
41720
41911
  };
@@ -41740,10 +41931,10 @@ const ARN_REFERENCE_STATEMENT_KEYS = [
41740
41931
  function toSdkStatement(statement) {
41741
41932
  const converted = { ...statement };
41742
41933
  const byteMatchStatement = converted["ByteMatchStatement"];
41743
- if (isPlainObject$2(byteMatchStatement)) converted["ByteMatchStatement"] = toSdkByteMatchStatement(byteMatchStatement);
41934
+ if (isPlainObject$3(byteMatchStatement)) converted["ByteMatchStatement"] = toSdkByteMatchStatement(byteMatchStatement);
41744
41935
  for (const key of ARN_REFERENCE_STATEMENT_KEYS) {
41745
41936
  const reference = converted[key];
41746
- if (!isPlainObject$2(reference) || !("Arn" in reference)) continue;
41937
+ if (!isPlainObject$3(reference) || !("Arn" in reference)) continue;
41747
41938
  const { Arn: arn, ...rest } = reference;
41748
41939
  converted[key] = {
41749
41940
  ...rest,
@@ -41751,28 +41942,28 @@ function toSdkStatement(statement) {
41751
41942
  };
41752
41943
  }
41753
41944
  const notStatement = converted["NotStatement"];
41754
- if (isPlainObject$2(notStatement)) {
41945
+ if (isPlainObject$3(notStatement)) {
41755
41946
  const nested = notStatement["Statement"];
41756
- if (isPlainObject$2(nested)) converted["NotStatement"] = {
41947
+ if (isPlainObject$3(nested)) converted["NotStatement"] = {
41757
41948
  ...notStatement,
41758
41949
  Statement: toSdkStatement(nested)
41759
41950
  };
41760
41951
  }
41761
41952
  for (const key of ["AndStatement", "OrStatement"]) {
41762
41953
  const combined = converted[key];
41763
- if (!isPlainObject$2(combined)) continue;
41954
+ if (!isPlainObject$3(combined)) continue;
41764
41955
  const nested = combined["Statements"];
41765
41956
  if (!Array.isArray(nested)) continue;
41766
41957
  converted[key] = {
41767
41958
  ...combined,
41768
- Statements: nested.map((item) => isPlainObject$2(item) ? toSdkStatement(item) : item)
41959
+ Statements: nested.map((item) => isPlainObject$3(item) ? toSdkStatement(item) : item)
41769
41960
  };
41770
41961
  }
41771
41962
  for (const key of ["RateBasedStatement", "ManagedRuleGroupStatement"]) {
41772
41963
  const scoping = converted[key];
41773
- if (!isPlainObject$2(scoping)) continue;
41964
+ if (!isPlainObject$3(scoping)) continue;
41774
41965
  const nested = scoping["ScopeDownStatement"];
41775
- if (!isPlainObject$2(nested)) continue;
41966
+ if (!isPlainObject$3(nested)) continue;
41776
41967
  converted[key] = {
41777
41968
  ...scoping,
41778
41969
  ScopeDownStatement: toSdkStatement(nested)
@@ -41784,9 +41975,9 @@ function toSdkRules(rules) {
41784
41975
  if (!rules) return [];
41785
41976
  if (!Array.isArray(rules)) return rules;
41786
41977
  return rules.map((rule) => {
41787
- if (!isPlainObject$2(rule)) return rule;
41978
+ if (!isPlainObject$3(rule)) return rule;
41788
41979
  const statement = rule["Statement"];
41789
- if (!isPlainObject$2(statement)) return rule;
41980
+ if (!isPlainObject$3(statement)) return rule;
41790
41981
  return {
41791
41982
  ...rule,
41792
41983
  Statement: toSdkStatement(statement)
@@ -41798,7 +41989,7 @@ function toCfnByteMatchStatement(byteMatchStatement, baseline) {
41798
41989
  if (raw === void 0) return byteMatchStatement;
41799
41990
  const bytes = raw instanceof Uint8Array ? Buffer.from(raw) : typeof raw === "string" ? Buffer.from(raw, "utf8") : void 0;
41800
41991
  if (!bytes) return byteMatchStatement;
41801
- const base = isPlainObject$2(baseline) ? baseline : void 0;
41992
+ const base = isPlainObject$3(baseline) ? baseline : void 0;
41802
41993
  const baseEncoded = base?.["SearchStringBase64"];
41803
41994
  const basePlain = base?.["SearchString"];
41804
41995
  const converted = { ...byteMatchStatement };
@@ -41823,12 +42014,12 @@ function toCfnByteMatchStatement(byteMatchStatement, baseline) {
41823
42014
  }
41824
42015
  function toCfnStatement(statement, baseline) {
41825
42016
  const converted = { ...statement };
41826
- const base = isPlainObject$2(baseline) ? baseline : void 0;
42017
+ const base = isPlainObject$3(baseline) ? baseline : void 0;
41827
42018
  const byteMatchStatement = converted["ByteMatchStatement"];
41828
- if (isPlainObject$2(byteMatchStatement)) converted["ByteMatchStatement"] = toCfnByteMatchStatement(byteMatchStatement, base?.["ByteMatchStatement"]);
42019
+ if (isPlainObject$3(byteMatchStatement)) converted["ByteMatchStatement"] = toCfnByteMatchStatement(byteMatchStatement, base?.["ByteMatchStatement"]);
41829
42020
  for (const key of ARN_REFERENCE_STATEMENT_KEYS) {
41830
42021
  const reference = converted[key];
41831
- if (!isPlainObject$2(reference) || !("ARN" in reference)) continue;
42022
+ if (!isPlainObject$3(reference) || !("ARN" in reference)) continue;
41832
42023
  const { ARN: arn, ...rest } = reference;
41833
42024
  converted[key] = {
41834
42025
  ...rest,
@@ -41836,37 +42027,37 @@ function toCfnStatement(statement, baseline) {
41836
42027
  };
41837
42028
  }
41838
42029
  const notStatement = converted["NotStatement"];
41839
- if (isPlainObject$2(notStatement)) {
42030
+ if (isPlainObject$3(notStatement)) {
41840
42031
  const nested = notStatement["Statement"];
41841
- if (isPlainObject$2(nested)) {
42032
+ if (isPlainObject$3(nested)) {
41842
42033
  const baseNot = base?.["NotStatement"];
41843
42034
  converted["NotStatement"] = {
41844
42035
  ...notStatement,
41845
- Statement: toCfnStatement(nested, isPlainObject$2(baseNot) ? baseNot["Statement"] : void 0)
42036
+ Statement: toCfnStatement(nested, isPlainObject$3(baseNot) ? baseNot["Statement"] : void 0)
41846
42037
  };
41847
42038
  }
41848
42039
  }
41849
42040
  for (const key of ["AndStatement", "OrStatement"]) {
41850
42041
  const combined = converted[key];
41851
- if (!isPlainObject$2(combined)) continue;
42042
+ if (!isPlainObject$3(combined)) continue;
41852
42043
  const nested = combined["Statements"];
41853
42044
  if (!Array.isArray(nested)) continue;
41854
42045
  const baseCombined = base?.[key];
41855
- const baseList = isPlainObject$2(baseCombined) && Array.isArray(baseCombined["Statements"]) ? baseCombined["Statements"] : void 0;
42046
+ const baseList = isPlainObject$3(baseCombined) && Array.isArray(baseCombined["Statements"]) ? baseCombined["Statements"] : void 0;
41856
42047
  converted[key] = {
41857
42048
  ...combined,
41858
- Statements: nested.map((item, i) => isPlainObject$2(item) ? toCfnStatement(item, baseList?.[i]) : item)
42049
+ Statements: nested.map((item, i) => isPlainObject$3(item) ? toCfnStatement(item, baseList?.[i]) : item)
41859
42050
  };
41860
42051
  }
41861
42052
  for (const key of ["RateBasedStatement", "ManagedRuleGroupStatement"]) {
41862
42053
  const scoping = converted[key];
41863
- if (!isPlainObject$2(scoping)) continue;
42054
+ if (!isPlainObject$3(scoping)) continue;
41864
42055
  const nested = scoping["ScopeDownStatement"];
41865
- if (!isPlainObject$2(nested)) continue;
42056
+ if (!isPlainObject$3(nested)) continue;
41866
42057
  const baseScoping = base?.[key];
41867
42058
  converted[key] = {
41868
42059
  ...scoping,
41869
- ScopeDownStatement: toCfnStatement(nested, isPlainObject$2(baseScoping) ? baseScoping["ScopeDownStatement"] : void 0)
42060
+ ScopeDownStatement: toCfnStatement(nested, isPlainObject$3(baseScoping) ? baseScoping["ScopeDownStatement"] : void 0)
41870
42061
  };
41871
42062
  }
41872
42063
  return converted;
@@ -41875,13 +42066,13 @@ function toCfnRules(rules, baselineRules) {
41875
42066
  if (!Array.isArray(rules)) return [];
41876
42067
  const baseList = Array.isArray(baselineRules) ? baselineRules : void 0;
41877
42068
  return rules.map((rule, i) => {
41878
- if (!isPlainObject$2(rule)) return rule;
42069
+ if (!isPlainObject$3(rule)) return rule;
41879
42070
  const statement = rule["Statement"];
41880
- if (!isPlainObject$2(statement)) return rule;
42071
+ if (!isPlainObject$3(statement)) return rule;
41881
42072
  const baseRule = baseList?.[i];
41882
42073
  return {
41883
42074
  ...rule,
41884
- Statement: toCfnStatement(statement, isPlainObject$2(baseRule) ? baseRule["Statement"] : void 0)
42075
+ Statement: toCfnStatement(statement, isPlainObject$3(baseRule) ? baseRule["Statement"] : void 0)
41885
42076
  };
41886
42077
  });
41887
42078
  }
@@ -44279,10 +44470,10 @@ function unappliedDnsConfigMembers(properties, previousProperties, changedProper
44279
44470
  if (changedProperties !== void 0 && !changedProperties.has("DnsConfig")) return [];
44280
44471
  const desired = properties["DnsConfig"];
44281
44472
  const previous = previousProperties["DnsConfig"];
44282
- if (!isPlainObject$1(desired) || !isPlainObject$1(previous)) return [];
44473
+ if (!isPlainObject$2(desired) || !isPlainObject$2(previous)) return [];
44283
44474
  return ["NamespaceId", "RoutingPolicy"].filter((member) => !sameAsRecorded(desired[member], previous[member]));
44284
44475
  }
44285
- function isPlainObject$1(value) {
44476
+ function isPlainObject$2(value) {
44286
44477
  return typeof value === "object" && value !== null && !Array.isArray(value);
44287
44478
  }
44288
44479
  function isRecordedStandIn(value) {
@@ -51152,7 +51343,7 @@ function budgetFromSdk(budget) {
51152
51343
  if (raw["BillingViewArn"] !== void 0) out["BillingViewArn"] = raw["BillingViewArn"];
51153
51344
  return out;
51154
51345
  }
51155
- async function canonicalizeDriftPair(resourceType, baseline, aws) {
51346
+ async function canonicalizeDriftPair$1(resourceType, baseline, aws) {
51156
51347
  if (resourceType !== "AWS::Budgets::Budget") return {
51157
51348
  baseline,
51158
51349
  aws
@@ -51401,7 +51592,7 @@ var BudgetsBudgetProvider = class {
51401
51592
  return resourceType === "AWS::Budgets::Budget" ? canonicalizeBudgetDriftBag(side) : side;
51402
51593
  }
51403
51594
  canonicalizeDriftPair(resourceType, baseline, aws) {
51404
- return canonicalizeDriftPair.call(this, resourceType, baseline, aws);
51595
+ return canonicalizeDriftPair$1.call(this, resourceType, baseline, aws);
51405
51596
  }
51406
51597
  import(input) {
51407
51598
  return importImpl$13.call(this, input);
@@ -56076,11 +56267,11 @@ const CLOUDWATCH_LOG_CONFIGURATION_MEMBERS = /* @__PURE__ */ new Set([
56076
56267
  ]);
56077
56268
  const toSdkMonitoringConfiguration = (value, onUnknown) => {
56078
56269
  if (value === void 0 || value === null) return void 0;
56079
- if (!isPlainObject(value)) return value;
56270
+ if (!isPlainObject$1(value)) return value;
56080
56271
  for (const key of Object.keys(value)) if (!MONITORING_CONFIGURATION_MEMBERS.has(key)) onUnknown(`MonitoringConfiguration.${key}`);
56081
56272
  const cw = value["CloudWatchLogConfiguration"];
56082
56273
  if (cw === void 0 || cw === null) return {};
56083
- if (!isPlainObject(cw)) return { CloudWatchLogConfiguration: cw };
56274
+ if (!isPlainObject$1(cw)) return { CloudWatchLogConfiguration: cw };
56084
56275
  for (const key of Object.keys(cw)) if (!CLOUDWATCH_LOG_CONFIGURATION_MEMBERS.has(key)) onUnknown(`MonitoringConfiguration.CloudWatchLogConfiguration.${key}`);
56085
56276
  return { CloudWatchLogConfiguration: {
56086
56277
  Enabled: toBoolean(cw["Enabled"]),
@@ -56091,11 +56282,11 @@ const toSdkMonitoringConfiguration = (value, onUnknown) => {
56091
56282
  } };
56092
56283
  };
56093
56284
  const jsonEqual$2 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
56094
- const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
56285
+ const isPlainObject$1 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
56095
56286
  function withRecordedReferences(next, prev, mask) {
56096
56287
  if (typeof prev === "string" && typeof next === "string") return next !== prev && onlySecretReferencesDiffer(next, prev, mask) ? prev : next;
56097
56288
  if (Array.isArray(prev) && Array.isArray(next) && prev.length === next.length) return next.map((item, i) => withRecordedReferences(item, prev[i], mask));
56098
- if (isPlainObject(prev) && isPlainObject(next)) return Object.fromEntries(Object.entries(next).map(([key, value]) => [key, withRecordedReferences(value, prev[key], mask)]));
56289
+ if (isPlainObject$1(prev) && isPlainObject$1(next)) return Object.fromEntries(Object.entries(next).map(([key, value]) => [key, withRecordedReferences(value, prev[key], mask)]));
56099
56290
  return next;
56100
56291
  }
56101
56292
  const NO_INSTANCES_TARGETS = {
@@ -56119,8 +56310,8 @@ const EMPTY_INSTANCES_PLAN = {
56119
56310
  const GROUP_IN_PLACE_MEMBERS = ["InstanceCount", "AutoScalingPolicy"];
56120
56311
  const FLEET_IN_PLACE_MEMBERS = ["TargetOnDemandCapacity", "TargetSpotCapacity"];
56121
56312
  function planInstancesInPlace(prev, next) {
56122
- const moved = (a, b, keys) => keys.some((key) => !jsonEqual$2(isPlainObject(a) ? a[key] : void 0, isPlainObject(b) ? b[key] : void 0));
56123
- const asBag = (value) => isPlainObject(value) ? value : {};
56313
+ const moved = (a, b, keys) => keys.some((key) => !jsonEqual$2(isPlainObject$1(a) ? a[key] : void 0, isPlainObject$1(b) ? b[key] : void 0));
56314
+ const asBag = (value) => isPlainObject$1(value) ? value : {};
56124
56315
  const entries = (single, list, keys) => {
56125
56316
  const out = [];
56126
56317
  if (next[single] !== void 0 && moved(prev[single], next[single], keys)) out.push({
@@ -60589,6 +60780,57 @@ async function importImpl$4(input) {
60589
60780
  return null;
60590
60781
  }
60591
60782
 
60783
+ // src/provisioning/providers/codebuild/drift.ts
60784
+ const TYPE$1 = "AWS::CodeBuild::Project";
60785
+ function canonicalizeDriftPair(resourceType, baseline, aws) {
60786
+ if (resourceType !== TYPE$1) return {
60787
+ baseline,
60788
+ aws
60789
+ };
60790
+ const recorded = s3LogsOf(baseline);
60791
+ const live = s3LogsOf(aws);
60792
+ if (recorded === void 0 || live === void 0) return {
60793
+ baseline,
60794
+ aws
60795
+ };
60796
+ const recordedValue = recorded["EncryptionDisabled"];
60797
+ const liveValue = live["EncryptionDisabled"];
60798
+ if (recordedValue === void 0 && liveValue === false) return {
60799
+ baseline: withEncryptionDisabledFalse(baseline, recorded),
60800
+ aws
60801
+ };
60802
+ if (liveValue === void 0 && recordedValue === false) return {
60803
+ baseline,
60804
+ aws: withEncryptionDisabledFalse(aws, live)
60805
+ };
60806
+ return {
60807
+ baseline,
60808
+ aws
60809
+ };
60810
+ }
60811
+ function isPlainObject(value) {
60812
+ return typeof value === "object" && value !== null && !Array.isArray(value);
60813
+ }
60814
+ function s3LogsOf(bag) {
60815
+ const logs = bag["LogsConfig"];
60816
+ if (!isPlainObject(logs)) return void 0;
60817
+ const s3 = logs["S3Logs"];
60818
+ return isPlainObject(s3) ? s3 : void 0;
60819
+ }
60820
+ function withEncryptionDisabledFalse(bag, s3Logs) {
60821
+ const logs = bag["LogsConfig"];
60822
+ return {
60823
+ ...bag,
60824
+ LogsConfig: {
60825
+ ...logs,
60826
+ S3Logs: {
60827
+ ...s3Logs,
60828
+ EncryptionDisabled: false
60829
+ }
60830
+ }
60831
+ };
60832
+ }
60833
+
60592
60834
  // src/provisioning/providers/codebuild-provider.ts
60593
60835
  var CodeBuildProvider = class {
60594
60836
  client;
@@ -60687,6 +60929,9 @@ var CodeBuildProvider = class {
60687
60929
  readCurrentState(physicalId, _logicalId, _resourceType, properties, context) {
60688
60930
  return readCurrentState$4.call(this, physicalId, _logicalId, _resourceType, properties, context);
60689
60931
  }
60932
+ canonicalizeDriftPair(resourceType, baseline, aws) {
60933
+ return Promise.resolve(canonicalizeDriftPair(resourceType, baseline, aws));
60934
+ }
60690
60935
  getDriftUnknownPaths() {
60691
60936
  return ["Source.Auth", "Triggers"];
60692
60937
  }
@@ -64920,14 +65165,25 @@ var NestedStackProvider = class {
64920
65165
  };
64921
65166
 
64922
65167
  // src/provisioning/providers/wait-condition-handle-provider.ts
65168
+ const SHORT_URL_LIFETIME_MS = 432e5;
64923
65169
  var WaitConditionHandleProvider = class {
64924
65170
  logger = getLogger().child("WaitConditionHandleProvider");
64925
65171
  handledProperties = /* @__PURE__ */ new Map([["AWS::CloudFormation::WaitConditionHandle", /* @__PURE__ */ new Set([])]]);
64926
- async create(logicalId, _resourceType, _properties) {
64927
- const physicalId = `cdkd-wait-condition-handle-${logicalId}-${randomUUID()}`;
64928
- this.logger.debug(`Created no-op WaitConditionHandle placeholder ${logicalId} (${physicalId})`);
65172
+ signals;
65173
+ constructor(signals = new WaitConditionSignalStore()) {
65174
+ this.signals = signals;
65175
+ }
65176
+ async create(logicalId, resourceType, _properties) {
65177
+ let issued;
65178
+ try {
65179
+ issued = await this.signals.issueSignalUrl(logicalId);
65180
+ } catch (error) {
65181
+ throw markNonRetryable(new ProvisioningError(`Failed to issue the signal URL for WaitConditionHandle ${logicalId}: ${error instanceof Error ? error.message : safeStringify(error)}`, resourceType, logicalId, void 0, error instanceof Error ? error : void 0));
65182
+ }
65183
+ this.logger.debug(safeMsg`Issued WaitConditionHandle ${logicalId} signal URL for ${issued.key}`);
65184
+ if (issued.expiresAt.getTime() - Date.now() < SHORT_URL_LIFETIME_MS) this.logger.warn(safeMsg`WaitConditionHandle ${logicalId}: its signal URL is signed with temporary credentials and stops accepting signals at ${issued.expiresAt.toISOString()}. Deploy with longer-lived credentials if anything signals it later than that.`);
64929
65185
  return {
64930
- physicalId,
65186
+ physicalId: issued.url,
64931
65187
  attributes: {}
64932
65188
  };
64933
65189
  }
@@ -64939,8 +65195,20 @@ var WaitConditionHandleProvider = class {
64939
65195
  attributes: {}
64940
65196
  };
64941
65197
  }
64942
- async delete(logicalId, _physicalId, _resourceType) {
64943
- this.logger.debug(`No-op delete for WaitConditionHandle ${logicalId}`);
65198
+ async delete(logicalId, physicalId, _resourceType) {
65199
+ let bucket;
65200
+ try {
65201
+ bucket = this.signals.requireBucket();
65202
+ } catch {
65203
+ this.logger.debug(`No state bucket configured; nothing to remove for WaitConditionHandle ${logicalId}`);
65204
+ return;
65205
+ }
65206
+ const verdict = classifyHandleUrl(physicalId, bucket);
65207
+ if (verdict.kind !== "ours") {
65208
+ this.logger.debug(`No cdkd signal object behind WaitConditionHandle ${logicalId}`);
65209
+ return;
65210
+ }
65211
+ await this.signals.deleteSignals(verdict.key);
64944
65212
  }
64945
65213
  async getAttribute(physicalId, resourceType, attributeName, logicalId) {
64946
65214
  throw new ProvisioningError(`AWS::CloudFormation::WaitConditionHandle has no Fn::GetAtt attributes (requested: ${attributeName})`, resourceType, logicalId, physicalId);
@@ -64950,11 +65218,167 @@ var WaitConditionHandleProvider = class {
64950
65218
  }
64951
65219
  async import(input) {
64952
65220
  return {
64953
- physicalId: input.knownPhysicalId ?? `cdkd-wait-condition-handle-${input.logicalId}-${randomUUID()}`,
65221
+ physicalId: input.knownPhysicalId ?? `${"cdkd-wait-condition-handle-"}${input.logicalId}-${randomUUID()}`,
65222
+ attributes: {}
65223
+ };
65224
+ }
65225
+ };
65226
+
65227
+ // src/provisioning/providers/wait-condition-provider.ts
65228
+ const TYPE = "AWS::CloudFormation::WaitCondition";
65229
+ const MAX_WAIT_CONDITION_TIMEOUT_SECONDS = 43200;
65230
+ const INITIAL_POLL_INTERVAL_MS = 2e3;
65231
+ const MAX_POLL_INTERVAL_MS = 1e4;
65232
+ const REASON_DISPLAY_CAP = 512;
65233
+ var WaitConditionProvider = class {
65234
+ logger = getLogger().child("WaitConditionProvider");
65235
+ handledProperties = /* @__PURE__ */ new Map([["AWS::CloudFormation::WaitCondition", /* @__PURE__ */ new Set([
65236
+ "Handle",
65237
+ "Count",
65238
+ "Timeout"
65239
+ ])]]);
65240
+ now = () => Date.now();
65241
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms));
65242
+ signals;
65243
+ constructor(signals = new WaitConditionSignalStore()) {
65244
+ this.signals = signals;
65245
+ }
65246
+ getMinResourceTimeoutMs() {
65247
+ return 435e5;
65248
+ }
65249
+ async create(logicalId, _resourceType, properties) {
65250
+ const spec = this.readSpec(logicalId, properties);
65251
+ const data = await this.waitForSignals(logicalId, spec);
65252
+ return {
65253
+ physicalId: `cdkd-wait-condition-${logicalId}-${randomUUID()}`,
65254
+ attributes: { Data: JSON.stringify(data) }
65255
+ };
65256
+ }
65257
+ async update(logicalId, physicalId, _resourceType, properties, previousProperties, context) {
65258
+ if (context?.replayingState === true || context?.desiredFromAwsReadback === true) {
65259
+ this.logger.debug(safeMsg`WaitCondition ${logicalId}: restoring a recorded wait, not waiting`);
65260
+ return {
65261
+ physicalId,
65262
+ wasReplaced: false
65263
+ };
65264
+ }
65265
+ const differs = (a, b) => JSON.stringify(a) !== JSON.stringify(b);
65266
+ if (!(differs(properties["Handle"], previousProperties["Handle"]) || differs(properties["Count"], previousProperties["Count"]) || differs(properties["Timeout"], previousProperties["Timeout"]))) return {
65267
+ physicalId,
65268
+ wasReplaced: false
65269
+ };
65270
+ const spec = this.readSpec(logicalId, properties);
65271
+ const data = await this.waitForSignals(logicalId, spec);
65272
+ return {
65273
+ physicalId,
65274
+ wasReplaced: false,
65275
+ attributes: { Data: JSON.stringify(data) }
65276
+ };
65277
+ }
65278
+ async delete(logicalId, _physicalId, _resourceType) {
65279
+ this.logger.debug(safeMsg`No-op delete for WaitCondition ${logicalId}`);
65280
+ }
65281
+ async getAttribute(physicalId, resourceType, attributeName, logicalId) {
65282
+ throw new ProvisioningError(`AWS::CloudFormation::WaitCondition attribute ${attributeName} can only be read from the value recorded when the wait completed`, resourceType, logicalId, physicalId);
65283
+ }
65284
+ async readCurrentState() {
65285
+ return {};
65286
+ }
65287
+ async import(input) {
65288
+ if (input.knownPhysicalId === void 0) return null;
65289
+ return {
65290
+ physicalId: input.knownPhysicalId,
64954
65291
  attributes: {}
64955
65292
  };
64956
65293
  }
65294
+ refuse(logicalId, message) {
65295
+ throw markNonRetryable(new ProvisioningError(message, TYPE, logicalId));
65296
+ }
65297
+ readSpec(logicalId, properties) {
65298
+ const handle = properties["Handle"];
65299
+ if (handle === void 0 || handle === null) this.refuse(logicalId, `WaitCondition ${logicalId} has no Handle. cdkd supports only the handle form (a WaitConditionHandle whose URL is signalled); a CreationPolicy-signalled wait condition is not supported.`);
65300
+ if (typeof handle !== "string") this.refuse(logicalId, `WaitCondition ${logicalId}: Handle must resolve to a string.`);
65301
+ const timeoutSeconds = integerOf(properties["Timeout"]);
65302
+ if (timeoutSeconds === void 0 || timeoutSeconds < 1 || timeoutSeconds > 43200) this.refuse(logicalId, `WaitCondition ${logicalId}: Timeout must be a whole number of seconds from 1 to ${MAX_WAIT_CONDITION_TIMEOUT_SECONDS}.`);
65303
+ const rawCount = properties["Count"];
65304
+ const count = rawCount === void 0 || rawCount === null ? 1 : integerOf(rawCount);
65305
+ if (count === void 0 || count < 1) this.refuse(logicalId, `WaitCondition ${logicalId}: Count must be a whole number of at least 1.`);
65306
+ return {
65307
+ handle,
65308
+ count,
65309
+ timeoutSeconds
65310
+ };
65311
+ }
65312
+ async waitForSignals(logicalId, spec) {
65313
+ const verdict = classifyHandleUrl(spec.handle, this.signals.requireBucket());
65314
+ if (verdict.kind === "legacy") this.refuse(logicalId, `WaitCondition ${logicalId}: its Handle was created by a cdkd version that issued no signal URL. Give the WaitConditionHandle a new logical id (or remove it, deploy, and add it back) so cdkd issues one, then deploy again.`);
65315
+ if (verdict.kind === "foreign") this.refuse(logicalId, `WaitCondition ${logicalId}: its Handle is not a signal URL cdkd issued for this state bucket (for example a CloudFormation-issued handle), so cdkd cannot read its signals. Give the WaitConditionHandle a new logical id so cdkd issues one.`);
65316
+ const perTypeCapMs = resolvedPerTypeResourceTimeoutMs(TYPE);
65317
+ const waitMs = Math.min(spec.timeoutSeconds * 1e3, perTypeCapMs ?? Infinity);
65318
+ const deadline = this.now() + waitMs;
65319
+ const maxVersions = spec.count * 10 + 100;
65320
+ const seen = /* @__PURE__ */ new Map();
65321
+ const watch = startInterruptWatch(`WaitCondition ${logicalId}`);
65322
+ let interval = INITIAL_POLL_INTERVAL_MS;
65323
+ let received = 0;
65324
+ this.logger.info(safeMsg`Waiting for ${spec.count} signal(s) on WaitCondition ${logicalId} (timeout ${spec.timeoutSeconds}s)`);
65325
+ try {
65326
+ for (;;) {
65327
+ if (watch.isInterrupted()) throw watch.onInterrupted();
65328
+ let signals;
65329
+ try {
65330
+ signals = await this.signals.readSignals(verdict.key, seen, maxVersions);
65331
+ } catch (error) {
65332
+ const name = error instanceof Error ? error.name : "unknown error";
65333
+ if (!isTransientReadFailure(error)) throw markNonRetryable(new ProvisioningError(safeMsg`WaitCondition ${logicalId} could not read its signals from the cdkd state bucket (${name}).`, TYPE, logicalId, void 0, error instanceof Error ? error : void 0));
65334
+ this.logger.debug(safeMsg`WaitCondition ${logicalId} signal read failed: ${name}`);
65335
+ }
65336
+ if (signals !== void 0) {
65337
+ const result = evaluateSignals(signals, spec.count);
65338
+ if (result.state === "succeeded") return result.data;
65339
+ if (result.state === "failed") {
65340
+ const reason = bounded(result.signal.reason, REASON_DISPLAY_CAP);
65341
+ const from = bounded(result.signal.uniqueId, 128);
65342
+ this.refuse(logicalId, `WaitCondition ${logicalId} received a FAILURE signal` + (from !== "" ? ` from ${from}` : "") + (reason !== "" ? `: ${reason}` : ""));
65343
+ }
65344
+ received = result.successes;
65345
+ }
65346
+ const remaining = deadline - this.now();
65347
+ if (remaining <= 0) this.refuse(logicalId, `WaitCondition ${logicalId} timed out after ${Math.round(waitMs / 1e3)}s with ${received} of ${spec.count} SUCCESS signal(s) received.`);
65348
+ await this.sleep(Math.min(interval, remaining));
65349
+ interval = Math.min(Math.ceil(interval * 1.5), MAX_POLL_INTERVAL_MS);
65350
+ }
65351
+ } finally {
65352
+ watch.dispose();
65353
+ }
65354
+ }
64957
65355
  };
65356
+ const TRANSIENT_READ_ERROR_NAMES = /* @__PURE__ */ new Set([
65357
+ "NoSuchKey",
65358
+ "NoSuchVersion",
65359
+ "RequestTimeout",
65360
+ "TimeoutError",
65361
+ "NetworkingError",
65362
+ "ECONNRESET",
65363
+ "ECONNREFUSED",
65364
+ "ETIMEDOUT",
65365
+ "EPIPE",
65366
+ "EAI_AGAIN",
65367
+ "ENOTFOUND"
65368
+ ]);
65369
+ function isTransientReadFailure(error) {
65370
+ if (isThrottlingError(error) || isTransientServerError(error)) return true;
65371
+ const e = error;
65372
+ return typeof e?.name === "string" && TRANSIENT_READ_ERROR_NAMES.has(e.name) || typeof e?.code === "string" && TRANSIENT_READ_ERROR_NAMES.has(e.code);
65373
+ }
65374
+ function bounded(value, cap) {
65375
+ const { text, truncated } = truncateCodePoints(displaySafe(value), cap);
65376
+ return truncated ? `${text}...` : text;
65377
+ }
65378
+ function integerOf(value) {
65379
+ const n = typeof value === "number" ? value : typeof value === "string" && /^\s*\d+\s*$/.test(value) ? Number(value) : NaN;
65380
+ return Number.isSafeInteger(n) && n >= 0 ? n : void 0;
65381
+ }
64958
65382
 
64959
65383
  // src/provisioning/providers/acm-certificate/shared.ts
64960
65384
  function certificateInUseByName(error) {
@@ -65403,5 +65827,5 @@ var ACMCertificateProvider = class {
65403
65827
  }
65404
65828
  };
65405
65829
 
65406
- 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 };
65407
- //# sourceMappingURL=provider-classes-CwIe3PGY.js.map
65830
+ 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, WaitConditionProvider };
65831
+ //# sourceMappingURL=provider-classes-DhmwW7hI.js.map