@cdkd/cli 0.334.2 → 0.334.3

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 (27) hide show
  1. package/dist/{asg-provider-DTZ_iFWa.js → asg-provider-Gu-qQLG9.js} +3 -3
  2. package/dist/{asg-provider-DTZ_iFWa.js.map → asg-provider-Gu-qQLG9.js.map} +1 -1
  3. package/dist/cli.js +2 -2
  4. package/dist/{db-instance-modify-retry-zm23duXt.js → db-instance-modify-retry-AJiRFAXa.js} +3 -3
  5. package/dist/{db-instance-modify-retry-zm23duXt.js.map → db-instance-modify-retry-AJiRFAXa.js.map} +1 -1
  6. package/dist/{deploy-engine-Dq_RyFZd.js → deploy-engine-BktCSZdi.js} +11425 -11278
  7. package/dist/deploy-engine-BktCSZdi.js.map +1 -0
  8. package/dist/{iam-role-provider-DwAhjMfG.js → iam-role-provider-BJ5XgxFH.js} +3 -3
  9. package/dist/{iam-role-provider-DwAhjMfG.js.map → iam-role-provider-BJ5XgxFH.js.map} +1 -1
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +3 -3
  12. package/dist/{neptune-provider-BFDPuF1_.js → neptune-provider-6SGPWYUE.js} +68 -24
  13. package/dist/{neptune-provider-BFDPuF1_.js.map → neptune-provider-6SGPWYUE.js.map} +1 -1
  14. package/dist/{program-Be87SvBg.js → program-Dm0zFrcG.js} +888 -730
  15. package/dist/program-Dm0zFrcG.js.map +1 -0
  16. package/dist/{provider-classes-D0isRHVc.js → provider-classes-BDPm7luc.js} +44 -20
  17. package/dist/{provider-classes-D0isRHVc.js.map → provider-classes-BDPm7luc.js.map} +1 -1
  18. package/dist/{rds-provider-CYwGhhxE.js → rds-provider--9aIoAY-.js} +4 -5
  19. package/dist/rds-provider--9aIoAY-.js.map +1 -0
  20. package/dist/{update-removal-C_x1-FM4.js → update-removal-73OUGFVU.js} +3 -2
  21. package/dist/{update-removal-C_x1-FM4.js.map → update-removal-73OUGFVU.js.map} +1 -1
  22. package/dist/{version-CagOv0Ke.js → version-CO5muce9.js} +2 -2
  23. package/dist/{version-CagOv0Ke.js.map → version-CO5muce9.js.map} +1 -1
  24. package/package.json +1 -1
  25. package/dist/deploy-engine-Dq_RyFZd.js.map +0 -1
  26. package/dist/program-Be87SvBg.js.map +0 -1
  27. package/dist/rds-provider-CYwGhhxE.js.map +0 -1
@@ -1,9 +1,9 @@
1
1
  import { a as runWithStackAwsClients, i as resetAwsClients, l as s3ClientDefaults, o as setAwsClients, s as resolveS3ClientDefaults, t as AwsClients, u as setS3ClientDefaultsDebugLog } from "./aws-clients-ez_oXu6x.js";
2
2
  import { $ as safeMsg, B as SAFE_MSG_ALTERED_CHAR, C as PATTERN_B_RESOURCE_TYPES, F as isNameGeneration, G as cutMarker, H as STACK_REF_MAX_CODE_POINTS, J as displaySafe, K as displayAwsMessage, L as withSkipPrefix, Q as plainIdentOr, R as withStackScope, S as PATTERN_B_NAME_PROPERTIES, T as generateResourceName, U as UNRENDERABLE, V as SECRET_REF_MAX_CODE_POINTS, W as asIsMessage, X as isPasteableIdent, Y as displayStackName, _ as explicitNamePropertyFor, a as safeStringify, c as isStdoutReservedForPayload, d as runStackBuffered, et as stringifyJsonPayload, l as reserveStdoutForPayload, m as getLiveRenderer, n as describeAwsFailure, nt as truncateCodePoints, q as displayIdent, s as getLogger, tt as terminalSafe, w as derivesPatternBName, x as PATTERN_B_NAME_OPTIONS } from "./aws-failure-text-CoS1huLy.js";
3
- import { $n as markNonRetryable, $t as formatLockExpiry, Ar as shellQuote, Bn as stripForDisplay, Dn as StackHasActiveImportsError, Dr as plainOrDescribed, En as ResourceUpdateNotSupportedError, Et as logicalIdShown, H as assertRegionMatch, Jn as isTransientServerError, M as VALUE_NOT_SHOWN, Mr as setPasteableRunFlags, Nr as setPasteableVerbFlags, On as StackTerminationProtectionError, Or as quotedOrDescribed, Ot as resourceTypeShown, Qn as isThrottlingError, Qt as forceQuitRecoveryClause, Rn as escapeRegExp, Sr as commandHole, Tn as PartialFailureError, Tr as pasteableCommand, U as isMarkedNotGone, V as RESOURCE_NOT_FOUND, Wn as isAmbiguousOutcomeError, Xt as buildForceUnlockCommand, Yn as retryClassificationText, Yt as UNREPRODUCIBLE_LOCK_CLAUSE, Zn as isMarkedNonRetryable, Zt as buildLockContentionMessage, _n as formatError, _t as beginCommandInterruptScope, an as DEFAULT_STATE_PREFIX, ar as MalformedProducerRecordRefusalError, bn as LocalStartServiceError, br as SHELL_ACTIVE_WHY, bt as isInterruptedWaitError, cn as producerCoordinateKey, cr as CdkdError, dn as withPasteableAwsProfile, dr as LocalInvokeBuildError$1, en as formatLockOperation, fn as ambientClientDefaults, gn as normalizeAwsError, gr as SynthesisError, hn as credentialFingerprint, hr as StateError, in as CUSTOM_RESOURCE_RESPONSE_PREFIX, ir as IntrinsicResolutionRefusalError, it as runDeleteAttempt, jr as withheldTargetClause, kr as shellBoundedDisplay, ln as producerRecordKey, lr as DeployCancelledError, m as RESOLVED_PREVIOUS_PRINCIPAL_KEYS, mn as clientDefaultsFor, mr as ResourceTimeoutError, nr as CrossAccountSecretRefusalError, on as injectiveKey, or as AccountIdUnavailableError, p as IAM_PRINCIPAL_NAME, pn as ambientCredentialConfig, pr as ProvisioningError, qn as isRetryableTransientError, rr as DynamicReferenceRegionAmbiguousError, tn as formatLockOwner, un as setPasteableAwsProfile, ut as isAwsCliLiteral, vr as TIMEOUT_FLAG_RESOURCE_TYPE, vt as endCommandInterruptScope, wn as NestedStackChildDirectDestroyError, wr as isInertUnquoted, y as readRecordedPrincipals, yn as withErrorHandling, yt as interruptWatchListenerCount, z as remedyLogicalId, zn as stripControlChars } from "./update-removal-C_x1-FM4.js";
3
+ import { $n as isThrottlingError, $t as forceQuitRecoveryClause, Ar as shellBoundedDisplay, Bn as stripControlChars, Cr as commandHole, Dn as ResourceUpdateNotSupportedError, Dt as logicalIdShown, En as PartialFailureError, Er as pasteableCommand, Gn as isAmbiguousOutcomeError, H as assertRegionMatch, Jn as isRetryableTransientError, M as VALUE_NOT_SHOWN, Mr as withheldTargetClause, Nr as setPasteableRunFlags, On as StackHasActiveImportsError, Or as plainOrDescribed, Pr as setPasteableVerbFlags, Qn as isMarkedNonRetryable, Qt as buildLockContentionMessage, Tn as NestedStackChildDirectDestroyError, Tr as isInertUnquoted, U as isMarkedNotGone, V as RESOURCE_NOT_FOUND, Vn as stripForDisplay, Xn as retryClassificationText, Xt as UNREPRODUCIBLE_LOCK_CLAUSE, Yn as isTransientServerError, Zt as buildForceUnlockCommand, _n as normalizeAwsError, _r as SynthesisError, an as CUSTOM_RESOURCE_RESPONSE_PREFIX, ar as IntrinsicResolutionRefusalError, at as runDeleteAttempt, bn as withErrorHandling, bt as interruptWatchListenerCount, dn as setPasteableAwsProfile, dt as isAwsCliLiteral, en as formatLockExpiry, er as markNonRetryable, fn as withPasteableAwsProfile, fr as LocalInvokeBuildError$1, gn as credentialFingerprint, gr as StateError, hn as clientDefaultsFor, hr as ResourceTimeoutError, ir as DynamicReferenceRegionAmbiguousError, jr as shellQuote, kn as StackTerminationProtectionError, kr as quotedOrDescribed, kt as resourceTypeShown, ln as producerCoordinateKey, lr as CdkdError, m as RESOLVED_PREVIOUS_PRINCIPAL_KEYS, mn as ambientCredentialConfig, mr as ProvisioningError, nn as formatLockOwner, on as DEFAULT_STATE_PREFIX, or as MalformedProducerRecordRefusalError, p as IAM_PRINCIPAL_NAME, pn as ambientClientDefaults, rr as CrossAccountSecretRefusalError, sn as injectiveKey, sr as AccountIdUnavailableError, tn as formatLockOperation, un as producerRecordKey, ur as DeployCancelledError, vn as formatError, vt as beginCommandInterruptScope, xn as LocalStartServiceError, xr as SHELL_ACTIVE_WHY, xt as isInterruptedWaitError, y as readRecordedPrincipals, yr as TIMEOUT_FLAG_RESOURCE_TYPE, yt as endCommandInterruptScope, z as remedyLogicalId, zn as escapeRegExp } from "./update-removal-73OUGFVU.js";
4
4
  import { a as setAssumedRoleCredentials, d as formatAuthority, i as getPreAssumeEnvCredentials, n as awsClientDefaults, r as getAssumedRoleCredentials, u as runInStackAwsScope } from "./aws-client-defaults-BLXFsfMa.js";
5
- import { $a as classifyRecordedSecretRegion, $l as importableOutputKeys, $n as demoteSupersededOrphans, $r as gray, $s as malformedOutputsWarning, $t as deleteJournaledOrphans, $u as runDockerForeground, Ad as AssemblyReader, Ai as extractDeploymentEventError, Al as recordPhysicalNameCopy, An as isPairableType, Ao as unsettledItemsField, Ar as secretBearing, As as refuseMalformedResourceEntriesForImport, At as recordRetainedForReadoption, Au as isCrossRegionRedirect, Ba as resolveDynamicReferences, Bc as maskAtCoordinates, Bd as ownValue, Bl as wholeStringLeavesOf, Bn as calculateResourceDrift, Bo as renderStatefulReason, Br as isExportAliasCollision, Bs as refuseMalformedResourcePropertiesForOrphan, Bt as sameMove, Bu as describeDockerExecFailure, Ca as deleteLeftInPlace, Cc as findHandledUnwrittenCreateOnly, Cd as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, Ci as orphanRecordsPrintingBag, Cl as spelledKeysOf, Cn as findDestructiveChanges, Co as carriesFetchableDynamicReference, Cr as computeParameterTaint, Cs as malformedLocalResourcesWarning, Ct as withResourceDeadline, Cu as createAssetRedirectResolver, Dc as NO_CC_HANDLERS_REASON, Dd as canonicalizeRegion, Di as secretNamedRecordNeedles, Dn as movedToHint, Do as withSharedDrainBudget, Dr as WITHHELD_NAME_DISPLAY, Ds as refuseMalformedResourceEntries, Dt as mergeNoChangeOutputs, Du as ensureAssetStorage, Ed as PARTITION_TABLE, El as inheritNestedStackParameterAssociations, En as hintSidesOf, Eo as keepsSecretReferenceToken, Er as resourcesNamingDeclaredParameter, Es as refuseMalformedResourceAttributesForOrphan, Et as keptWholeReasonText, Eu as AssetModeResolver, Fa as DiffCalculator, Fd as utf8ByteLength, Fi as isFinalSnapshotError, Fl as recordMaskOnlyValue, Fn as replayFailedOperations, Fo as findReplacedReadersOfRecreateTargets, Fr as exportNameSecretExposure, Fs as malformedDriftResourcePropertiesWarning, Ft as readRefactorMarker, Fu as validateContainerRepoName, Ga as assertSendableRoleArn, Gc as noEchoLeavesOf, Gd as resolveAssemblyPath, Gl as S3StateBackend, Gn as updatePartialReason, Gs as malformedOrphansWarning, Gt as refusePendingMovesOut, Gu as dockerSpawnEnvWithSensitive, Ha as refuseUnreadableCdkCrossAccountRefs, Hc as maskWholeValue, Hd as describeFileReadFailure, Hi as secretSegmentsOfState, Hl as isSingleDynamicReferenceToken, Hn as equalModuloMask, Hr as DEFAULT_RESOURCE_TIMEOUT_MS, Hs as UNREADABLE_ORPHANS_CONTAINER_ROW, Ht as hasPendingMovesOut, Hu as redactedCause, Ia as IntrinsicFunctionResolver, Ic as DagBuilder, Id as defineOwnKey, Ii as refusesFinalSnapshot, Il as recordMaskOnlyValuesIn, In as replayRollback, Io as shownType, Ir as isWholeDynamicReferenceValue, Is as malformedResourcePropertiesWarning, It as readRefactorMarkerOnce, Iu as BOOTSTRAP_MARKER_PREFIX, Ja as sendableAssumeRoleCommand, Jc as readbackPathFor, Jl as describeRegionValueKind, Js as repairMalformedOrphansForReadOnly, Jt as formatResourceLine, Ju as warnFinchArgvExposure, Ka as explicitRoleArnOrThrow, Kc as noEchoOutputsComparison, Kd as injectAwsRegion, Kl as splitImportedOps, Ko as coerceCfnBoolean, Ks as refuseMalformedOrphans, Ku as finchSecretArgvRefusal, La as isAlwaysLiveAttribute, Lc as TemplateParser, Ld as hasOwnKey, Li as unsupportedFinalSnapshotError, Ll as recordNoEchoAttributeValues, Ln as recordAfterRollbackUpdate, Lo as MULTI_REGION_RECREATE_BLOCKED_TYPES, Lr as noEchoParameterValueSeed, Ls as refuseMalformedResourcePropertiesForDestroy, Lt as refactorMarkerMovesOf, Lu as buildDockerImage, Md as processStackMessages, Mi as PRE_DELETE_SNAPSHOT_TYPES, Ml as splitGetAttStringForm, Mn as mappingPairs, Mo as unsettledPropertiesOf, Mr as secretSafeKeyDisplay, Ms as refuseMalformedResourceEntriesForOrphan, Mu as parseBootstrapMarker, Nd as describeJsonParseFailure, Ni as ccRoutedFinalSnapshotError, Nl as carriesSecretMask, Nn as parseMappingFile, No as withUnsettledProperties, Nr as carriedExportAliasExposure, Ns as repairMalformedResourceEntriesForReadOnly, Nu as readBootstrapMarkerBody, Oc as hasNoCloudControlHandlers, Od as derivePartitionAndUrlSuffix, Oi as stateSecretNameNeedles, Ol as physicalNameCopiesOf, On as rollbackOrphanIds, Oo as INTRINSIC_KEYS, Or as displayTextOrWithheld, Os as refuseMalformedResourceEntriesForDeploy, Ot as makeCanonicalizePropertiesFn, Ou as buildDenyExternalAccessPolicy, Pa as isWaitAbandonedError, Pd as parseFailureDebugDetail, Pi as effectiveDeletionPolicy, Pl as provenPublicValue, Pn as proposeRenames, Po as withoutUnsettledProperties, Pr as exportNameNoEchoParameters, Ps as unreadableResourceEntries, Pu as validateAssetBucketName, Qa as envCredentialsAreAssumedRole, Qc as liveMatchesUnresolvedTokenFrame, Ql as hasUnverifiableParameterRefusal, Qn as seedsDeleteFirstGuard, Qr as cyan, Qs as malformedOutputsRefusalMessage, Qt as resolvePendingCloudControlRequests, Qu as getDockerCmd, Ra as poisonRenderedSpellingsCollidingIn, Rc as canonicalCoordinates, Rd as hasPlainPrototype, Ri as createPreDeleteFinalSnapshot, Rl as recordNoEchoParameterFreshValue, Rn as settleUnsettledPrevious, Ro as isStatefulRecreateTargetForReplace, Rr as collectDeclaredOutputNames, Rs as refuseMalformedResourcePropertiesForDrift, Rt as refactorMarkerRefusalMessage, Ru as resolveDockerContextDirectory, Sa as deleteIndeterminateGuards, Sc as findActionableSdkUnwired, Sd as uploadCfnTemplate, Si as namingSecretsWithRecordedNoEcho, Sl as isUncertifiedBaselineMaskPosition, Sn as constructPathOf$1, So as isImpossibleEmptyStoredAttribute, Sr as inheritProducerRegions, Ss as malformedLocalResourceEntriesWarning, Su as buildAssetRedirectMap, Tc as unwrittenCreateOnlyReplacement, Td as expectedOwnerParam, Ti as secretNamePrintingBags, Tl as identityKeyFor, Tn as findRefactorHints, To as carriesDynamicReference, Tr as reachableDivergentParameters, Ts as malformedScrubResourceEntriesRefusalMessage, Tt as isSecretBearingReferenceString, Tu as rewriteTemplateAssetReferences, Ua as applyRoleArnIfSet, Uc as maskedLeafCoordinatesOf, Ud as displayAssemblyPath, Ui as withSecretPhysicalIdsMaskedInState, Ul as LockManager, Un as undeclaredEmptyObservedKeys, Ur as DEFAULT_RESOURCE_WARN_AFTER_MS, Us as hasReadableOrphans, Ut as pendingMovesOutOf, Uu as redactedDockerCause, Va as producerLookupOver, Vc as maskReadbackAtCoordinates, Vd as absoluteAssemblyPathEscape, Vl as WHOLE_DYNAMIC_REFERENCE_PATTERN, Vn as equalModuloMarkedMask, Vr as bindingSkippedOutputs, Vs as repairMalformedResourcePropertiesForReadOnly, Vt as updateRefactorMarker, Vu as describeDockerFailure, Wa as assertFlagRoleArn, Wc as noEchoCoordinatesOf, Wd as renderAssemblyPathEscape, Wl as isLockInfoExpired, Wn as updatePartialMessage, Wr as maskingRetryLogger, Ws as malformedOrphansRefusalMessage, Wt as pendingMovesRefusalMessage, Wu as redactDockerArgvValues, Xa as applyCallerIdentityCredentials, Xc as recordedNoEchoValuesOf, Xl as hasReadableExportSet, Xs as malformedExportSourceWarning, Xt as planOrphanAdoption, Xu as isMalformedEnvKey, Ya as AWS_CREDENTIAL_ENV_KEYS, Yc as readsNoEchoSource, Yd as resolveBucketRegion, Yl as exportNamesCarriedFrom, Yn as withCreateTokenLedger, Yr as withStackRecords, Ys as malformedExportNamesWarning, Yt as makeSiblingClaimReader, Yu as isDockerClientEnvKey, Za as callerEnvCredentials, Zc as valueAtCoordinate, Zl as hasReasonlessBaselineRefusal, Zn as planRollback, Zr as bold, Zs as malformedLocalOutputsWarning, Zt as pendingRequestCount, Zu as formatDockerLoginError, _c as STATE_RESOURCES_MALFORMED, _d as ssmResolvedValueType, _i as withAttemptedItemsMasked, _l as scrubResourceRecord, _n as collectNestedChildUnaddressed, _o as keepHeldTokenProvenance, _r as retiredAfterRollback, _s as refuseMalformedOrphansForOrphan, _t as conditionFingerprint, _u as withStackInstanceIdWithheld, a as isProtectionValueActive, aa as wouldReturnToSdkProvider, ac as refuseDivergentRecordRegionForDestroy, ad as getDefaultStateBucketName, ai as holdsSupersededResources, al as hasMaskableValues, an as sameJournaledOrphans, ar as replacementNeverSwapped, as as withRetry, at as computeImplicitDeleteEdges, au as stackInstanceIdCarriedFrom, ba as RollbackInlinePolicyWriters, bc as hasReadableOutputs, bd as MIGRATE_TMP_PREFIX, bi as journaledOrphanPrintingBag, bl as DYNAMIC_REFERENCE_TOKEN_SCAN, bn as DeploymentEventsReader, bo as recordedReferenceRegions, br as withNameGenerationReached, bs as unreadableOrphanRecords, bt as readRecordedConditionVerdicts, bu as stringifyValue, ca as customResourceResponseExpirationWarning, cc as malformedStateRefusalMessage, cd as resolveApp, ci as supersededAfterRollback, cl as printingCorpusOf, cn as displacedOpClause, co as coerceParameterTypedValue, cs as declaresNoEcho, ct as deferredServiceTokenWarning, cu as timePhase, da as isCustomResourceType$1, dc as refuseMalformedResourcesForExport, dd as resolveSkipPrefix, di as supersededResourcesOf, dl as shareLogOnlyValues, do as AWS_NO_VALUE, ds as malformedOrphanRecordsRefusalMessage, dt as childTemplateLoader, du as CrossPrefixScanCache, ed as runDockerStreaming, ei as green, el as redactForState, en as dropFailedCommands, eo as classifyReplaySecretRegion, er as isJournaledOrphan, eu as importableOutputs, fc as refuseMalformedState, fd as resolveStateBucketWithDefault, fi as withoutSuperseded, fl as unionOfSecretBags, fn as nestedChildStackName$1, fo as cfnRefValueFromPhysicalId, fr as removeProtectionTypeList, fs as malformedOrphanRecordsWarning, ft as findNestedTemplateTreeDefect, fu as applyCrossPrefixScan, gc as withheldAccountClause, gd as warnDeprecatedNoPrefixCliFlag, gi as noEchoParameterNamesOf, gl as maskSecretsInText, gn as withNestedRevertRun, gr as nameScopeOf, gs as refuseMalformedOrphanRecordsForDestroy, gt as templateIdentity, gu as stackInstanceIdOf, ha as CloudControlProvider, hc as accountArgs, hd as stateBucketExistenceConfirmed, hi as noEchoExactEchoLeavesOf, hl as maskSecretsInError, hn as revertedNestedRowIds, ho as refStateLookupFromResource, hr as nameGenerationHighWaterOf, hs as refuseMalformedOrphanRecords, ht as renderNestedTemplateTreeDefect, hu as isNotImplemented, i as PROTECTION_PROPERTY_BY_TYPE, ia as isCustomResource, ic as STATE_REGION_DIVERGED, id as synthesisStatusMessage, ii as deleteSupersededEntry, il as createUnionSecretMasker, in as loadJournaledOrphans, ir as recordUnderIdIsNotOwn, is as describeTypeWithThrottleRetry, it as IMPLICIT_DELETE_DEPENDENCIES, iu as shouldRetainResource, jd as StageLoadError, ji as ATOMIC_FINAL_SNAPSHOT_TYPES, jl as recordNestedStackParameterExpressions, jn as looselyEqual, jo as unsettledItemsOf, jr as secretBearingStateKeyWarning, js as refuseMalformedResourceEntriesForImportSave, ju as getBootstrapMarkerKey, kd as refuseFailedLookups, ki as storedSecretNameNeedles, kn as withMovedTo, kr as exportAliasCollisionScrubWarning, ks as refuseMalformedResourceEntriesForDestroy, kt as keptForRetainedRecord, ku as assertAssetBucketRegion, la as TemplateNoEchoReresolver, lc as refuseMalformedResourcesForDeploy, ld as resolveAutoAssetStorage, li as supersededHeldByOtherTypeWarning, ll as recordLogOnlyParameterValue, ln as displacedPhysicalIdShown, lo as isUnboundTemplateParameter, ls as deployRefusesOrphanRowsReason, lt as findServiceTokenRefusals, lu as rebuildClientForBucketRegion, mc as JSON_LISTING_HOLE_VALUE, md as resolveUseCdkBootstrapAssets, mi as noEchoComparisonForTemplate, ml as errorCauseChain, mo as lacksRecordedTableArn, mr as nameGenerationCarriedFrom, ms as previewableOrphanRecords, mt as listNestedTemplateRows, mu as isAccessDenied, n as recordedProtectionEvidence, na as ProviderRegistry, nc as refuseMalformedOutputsForDestroy, nd as getDockerImageBySourceHash, ni as yellow, nn as isHandledOrphan, no as regionLessSecretName, nr as planFailedOps, ns as prefetchCreateOnlyPropertyPaths, nu as orphansAfterRollback, o as perType, oa as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, oc as malformedRenderedContainersWarning, od as getLegacyStateBucketName, oi as isSupersededResourceRecord, ol as literalSplitDelimitersOf, on as makeForeignHolderScan, or as resolveReplacementOldType, os as parameterInputsFor, ot as crossStackOutputProvenanceSource, ou as PhaseClock, pa as withPrintingSecrets, pc as repairMalformedResourcesForReadOnly, pd as resolveStateBucketWithDefaultAndSource, pi as noEchoAttributeNamesOf, pl as createSecretMasker, pn as recordDisplacedSkips, po as isStalePlaceholderArnAttribute, pr as orphanNeedsIdentity, ps as malformedOrphanRowsKeptWarning, pt as isAbsoluteAssetPath, pu as crossPrefixDeniedWarning, qa as isIamRoleArn, qd as injectedAwsRegionValue, ql as acceptedCreateOnlyDropsOf, qn as ledgerForStack, qr as destroyStackRecordsView, qs as refuseMalformedOrphansForDestroy, qu as partitionSensitiveEnv, r as recordedProtectionNote, ra as ccBrokenReason, rc as repairMalformedOutputsForReadOnly, rd as Synthesizer, ri as addSuperseded, rl as carryLogOnlyValues, rn as journaledOrphanLines, rr as recheckFailedPlan, rs as templateResourceTypes, ru as orphansCarriedFrom, s as readProtection, sa as applyCustomResourceResponseExpiration, sc as malformedResourcesWarning, sd as loadCdkJson, si as removeSuperseded, sl as logOnlyValueCount, sn as NESTED_PENDING_PARENT_REASON, sr as findNestedStackTypeChanges, st as inheritedProvenanceForChildDiff, su as renderPhaseTimings, t as DeployEngine, ta as CC_BROKEN_REASON, tc as refuseMalformedOutputs, td as AssetManifestLoader, ti as red, tn as dropFailedHint, to as producerRegionsFromState, tr as isReplacementOrphan, tu as isReadableBag, ua as readsNoEchoDeleteValues, uc as refuseMalformedResourcesForDestroy, ud as resolveCaptureObservedState, ui as supersededHolderOf, ul as recordLogOnlyValue, un as dropSettledNestedJournals, uo as parameterTypeMayLoseSecretIdentity, us as isReadableOrphanRecord, ut as serviceTokenBlockingReason, uu as CrossPrefixReadError, va as setResolvedResourceTimeouts, vc as UNREADABLE_RESOURCES_MAP_ROW, vd as CFN_TEMPLATE_BODY_LIMIT, vi as createReadOnlyAttributeHealerFactory, vl as withPhysicalNameCopies, vn as getCurrentNestedStackContext, vr as retiredNameGenerationsAfter, vs as repairMalformedOrphanRecordsForReadOnly, vt as conditionInputsFrom, vu as AssetPublisher, wa as deleteSkipReason, wd as decodeListingKey, wi as secretNamePrintingBag, wl as pathCrossesDottedKey, wn as formatDestructiveChange, wo as isNamelessDynamicReferenceError, wr as namesAnyDeclaredParameter, ws as malformedResourceEntriesWarning, wt as diffSecurity, wu as loadPublishableAssetManifest, xa as UNSPECIFIED_SKIP_REASON, xc as hasReadableResources, xd as findLargeInlineResources, xi as maskEventTextWithBoundBags, xl as dynamicReferenceTokens, xn as DeploymentEventsStore, xo as getAccountInfo, xs as isReadableResourceEntry, xu as WorkGraph, ya as slowCcOperationTimeoutMs, yc as displayLogicalId, yd as CFN_TEMPLATE_URL_LIMIT, yi as completedReplayEntries, yn as withNestedStackContext, yo as recordedOutputReferenceRegions, yr as retiredNameGenerationsLeaving, ys as unpreviewableOrphanRecords, yt as parentSuppliedValues, yu as isSensitiveAttributeName, zc as isMarkedCoordinate, zd as nullPrototypeRecord, zi as buildFinalSnapshotIdentifier, zl as recordProvenPublicExpression, zn as withUnprovenUnsettled, zo as isStatefulRecreateTargetSync, zr as collectPublishedOutputNames, zs as refuseMalformedResourcePropertiesForExport, zt as refuseRefactorMarker, zu as describeDockerCapturedOutput } from "./deploy-engine-Dq_RyFZd.js";
6
- import { t as getCdkdVersion } from "./version-CagOv0Ke.js";
5
+ import { $a as classifyRecordedSecretRegion, $l as importableOutputKeys, $n as demoteSupersededOrphans, $r as gray, $s as malformedOutputsWarning, $t as deleteJournaledOrphans, $u as runDockerForeground, A as recordedProtectionEvidence, Ad as AssemblyReader, Ai as extractDeploymentEventError, Al as recordPhysicalNameCopy, An as isPairableType, Ao as unsettledItemsField, Ar as secretBearing, As as refuseMalformedResourceEntriesForImport, Au as isCrossRegionRedirect, Ba as resolveDynamicReferences, Bc as maskAtCoordinates, Bd as ownValue, Bl as wholeStringLeavesOf, Bn as calculateResourceDrift, Bo as renderStatefulReason, Br as isExportAliasCollision, Bs as refuseMalformedResourcePropertiesForOrphan, Bt as readRefactorMarkerOnce, Bu as describeDockerExecFailure, C as pendingMovesOutOf, Ca as deleteLeftInPlace, Cc as findHandledUnwrittenCreateOnly, Cd as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, Ci as orphanRecordsPrintingBag, Cl as spelledKeysOf, Cn as findDestructiveChanges, Co as carriesFetchableDynamicReference, Cr as computeParameterTaint, Cs as malformedLocalResourcesWarning, Cu as createAssetRedirectResolver, D as findServiceTokenRefusals, Dc as NO_CC_HANDLERS_REASON, Dd as canonicalizeRegion, Di as secretNamedRecordNeedles, Dn as movedToHint, Do as withSharedDrainBudget, Dr as WITHHELD_NAME_DISPLAY, Ds as refuseMalformedResourceEntries, Du as ensureAssetStorage, E as deferredServiceTokenWarning, Ed as PARTITION_TABLE, El as inheritNestedStackParameterAssociations, En as hintSidesOf, Eo as keepsSecretReferenceToken, Er as resourcesNamingDeclaredParameter, Es as refuseMalformedResourceAttributesForOrphan, Eu as AssetModeResolver, F as readProtection, Fa as DiffCalculator, Fd as utf8ByteLength, Fi as isFinalSnapshotError, Fl as recordMaskOnlyValue, Fn as replayFailedOperations, Fo as findReplacedReadersOfRecreateTargets, Fr as exportNameSecretExposure, Fs as malformedDriftResourcePropertiesWarning, Ft as IMPLICIT_DELETE_DEPENDENCIES, Fu as validateContainerRepoName, Ga as assertSendableRoleArn, Gc as noEchoLeavesOf, Gd as resolveAssemblyPath, Gl as S3StateBackend, Gn as updatePartialReason, Gs as malformedOrphansWarning, Gt as updateRefactorMarker, Gu as dockerSpawnEnvWithSensitive, Ha as refuseUnreadableCdkCrossAccountRefs, Hc as maskWholeValue, Hd as describeFileReadFailure, Hi as secretSegmentsOfState, Hl as isSingleDynamicReferenceToken, Hn as equalModuloMask, Hr as DEFAULT_RESOURCE_TIMEOUT_MS, Hs as UNREADABLE_ORPHANS_CONTAINER_ROW, Ht as refactorMarkerRefusalMessage, Hu as redactedCause, Ia as IntrinsicFunctionResolver, Ic as DagBuilder, Id as defineOwnKey, Ii as refusesFinalSnapshot, Il as recordMaskOnlyValuesIn, In as replayRollback, Io as shownType, Ir as isWholeDynamicReferenceValue, Is as malformedResourcePropertiesWarning, It as computeImplicitDeleteEdges, Iu as BOOTSTRAP_MARKER_PREFIX, Ja as sendableAssumeRoleCommand, Jc as readbackPathFor, Jl as describeRegionValueKind, Js as repairMalformedOrphansForReadOnly, Jt as formatResourceLine, Ju as warnFinchArgvExposure, Ka as explicitRoleArnOrThrow, Kc as noEchoOutputsComparison, Kd as injectAwsRegion, Kl as splitImportedOps, Ko as coerceCfnBoolean, Ks as refuseMalformedOrphans, Ku as finchSecretArgvRefusal, La as isAlwaysLiveAttribute, Lc as TemplateParser, Ld as hasOwnKey, Li as unsupportedFinalSnapshotError, Ll as recordNoEchoAttributeValues, Ln as recordAfterRollbackUpdate, Lo as MULTI_REGION_RECREATE_BLOCKED_TYPES, Lr as noEchoParameterValueSeed, Ls as refuseMalformedResourcePropertiesForDestroy, Lt as keptForRetainedRecord, Lu as buildDockerImage, M as PROTECTION_PROPERTY_BY_TYPE, Md as processStackMessages, Mi as PRE_DELETE_SNAPSHOT_TYPES, Ml as splitGetAttStringForm, Mn as mappingPairs, Mo as unsettledPropertiesOf, Mr as secretSafeKeyDisplay, Ms as refuseMalformedResourceEntriesForOrphan, Mu as parseBootstrapMarker, N as isProtectionValueActive, Nd as describeJsonParseFailure, Ni as ccRoutedFinalSnapshotError, Nl as carriesSecretMask, Nn as parseMappingFile, No as withUnsettledProperties, Nr as carriedExportAliasExposure, Ns as repairMalformedResourceEntriesForReadOnly, Nu as readBootstrapMarkerBody, O as serviceTokenBlockingReason, Oc as hasNoCloudControlHandlers, Od as derivePartitionAndUrlSuffix, Oi as stateSecretNameNeedles, Ol as physicalNameCopiesOf, On as rollbackOrphanIds, Oo as INTRINSIC_KEYS, Or as displayTextOrWithheld, Os as refuseMalformedResourceEntriesForDeploy, Ou as buildDenyExternalAccessPolicy, P as perType, Pa as isWaitAbandonedError, Pd as parseFailureDebugDetail, Pi as effectiveDeletionPolicy, Pl as provenPublicValue, Pn as proposeRenames, Po as withoutUnsettledProperties, Pr as exportNameNoEchoParameters, Ps as unreadableResourceEntries, Pt as withResourceDeadline, Pu as validateAssetBucketName, Qa as envCredentialsAreAssumedRole, Qc as liveMatchesUnresolvedTokenFrame, Ql as hasUnverifiableParameterRefusal, Qn as seedsDeleteFirstGuard, Qr as cyan, Qs as malformedOutputsRefusalMessage, Qt as resolvePendingCloudControlRequests, Qu as getDockerCmd, Ra as poisonRenderedSpellingsCollidingIn, Rc as canonicalCoordinates, Rd as hasPlainPrototype, Ri as createPreDeleteFinalSnapshot, Rl as recordNoEchoParameterFreshValue, Rn as settleUnsettledPrevious, Ro as isStatefulRecreateTargetForReplace, Rr as collectDeclaredOutputNames, Rs as refuseMalformedResourcePropertiesForDrift, Rt as recordRetainedForReadoption, Ru as resolveDockerContextDirectory, S as hasPendingMovesOut, Sa as deleteIndeterminateGuards, Sc as findActionableSdkUnwired, Sd as uploadCfnTemplate, Si as namingSecretsWithRecordedNoEcho, Sl as isUncertifiedBaselineMaskPosition, Sn as constructPathOf$1, So as isImpossibleEmptyStoredAttribute, Sr as inheritProducerRegions, Ss as malformedLocalResourceEntriesWarning, Su as buildAssetRedirectMap, T as refusePendingMovesOut, Tc as unwrittenCreateOnlyReplacement, Td as expectedOwnerParam, Ti as secretNamePrintingBags, Tl as identityKeyFor, Tn as findRefactorHints, To as carriesDynamicReference, Tr as reachableDivergentParameters, Ts as malformedScrubResourceEntriesRefusalMessage, Tu as rewriteTemplateAssetReferences, Ua as applyRoleArnIfSet, Uc as maskedLeafCoordinatesOf, Ud as displayAssemblyPath, Ui as withSecretPhysicalIdsMaskedInState, Ul as LockManager, Un as undeclaredEmptyObservedKeys, Ur as DEFAULT_RESOURCE_WARN_AFTER_MS, Us as hasReadableOrphans, Ut as refuseRefactorMarker, Uu as redactedDockerCause, Va as producerLookupOver, Vc as maskReadbackAtCoordinates, Vd as absoluteAssemblyPathEscape, Vl as WHOLE_DYNAMIC_REFERENCE_PATTERN, Vn as equalModuloMarkedMask, Vr as bindingSkippedOutputs, Vs as repairMalformedResourcePropertiesForReadOnly, Vt as refactorMarkerMovesOf, Vu as describeDockerFailure, Wa as assertFlagRoleArn, Wc as noEchoCoordinatesOf, Wd as renderAssemblyPathEscape, Wl as isLockInfoExpired, Wn as updatePartialMessage, Wr as maskingRetryLogger, Ws as malformedOrphansRefusalMessage, Wt as sameMove, Wu as redactDockerArgvValues, Xa as applyCallerIdentityCredentials, Xc as recordedNoEchoValuesOf, Xl as hasReadableExportSet, Xs as malformedExportSourceWarning, Xt as planOrphanAdoption, Xu as isMalformedEnvKey, Ya as AWS_CREDENTIAL_ENV_KEYS, Yc as readsNoEchoSource, Yd as resolveBucketRegion, Yl as exportNamesCarriedFrom, Yn as withCreateTokenLedger, Yr as withStackRecords, Ys as malformedExportNamesWarning, Yt as makeSiblingClaimReader, Yu as isDockerClientEnvKey, Za as callerEnvCredentials, Zc as valueAtCoordinate, Zl as hasReasonlessBaselineRefusal, Zn as planRollback, Zr as bold, Zs as malformedLocalOutputsWarning, Zt as pendingRequestCount, Zu as formatDockerLoginError, _ as findNestedTemplateTreeDefect, _c as STATE_RESOURCES_MALFORMED, _d as ssmResolvedValueType, _i as withAttemptedItemsMasked, _l as scrubResourceRecord, _n as collectNestedChildUnaddressed, _o as keepHeldTokenProvenance, _r as retiredAfterRollback, _s as refuseMalformedOrphansForOrphan, _u as withStackInstanceIdWithheld, aa as wouldReturnToSdkProvider, ac as refuseDivergentRecordRegionForDestroy, ad as getDefaultStateBucketName, ai as holdsSupersededResources, al as hasMaskableValues, an as sameJournaledOrphans, ar as replacementNeverSwapped, as as withRetry, au as stackInstanceIdCarriedFrom, b as renderNestedTemplateTreeDefect, ba as RollbackInlinePolicyWriters, bc as hasReadableOutputs, bd as MIGRATE_TMP_PREFIX, bi as journaledOrphanPrintingBag, bl as DYNAMIC_REFERENCE_TOKEN_SCAN, bn as DeploymentEventsReader, bo as recordedReferenceRegions, br as withNameGenerationReached, bs as unreadableOrphanRecords, bu as stringifyValue, c as mergeNoChangeOutputs, ca as customResourceResponseExpirationWarning, cc as malformedStateRefusalMessage, cd as resolveApp, ci as supersededAfterRollback, cl as printingCorpusOf, cn as displacedOpClause, co as coerceParameterTypedValue, cs as declaresNoEcho, cu as timePhase, d as makeCanonicalizePropertiesFn, da as isCustomResourceType$1, dc as refuseMalformedResourcesForExport, dd as resolveSkipPrefix, di as supersededResourcesOf, dl as shareLogOnlyValues, do as AWS_NO_VALUE, ds as malformedOrphanRecordsRefusalMessage, du as CrossPrefixScanCache, ed as runDockerStreaming, ei as green, el as redactForState, en as dropFailedCommands, eo as classifyReplaySecretRegion, er as isJournaledOrphan, eu as importableOutputs, f as conditionFingerprint, fc as refuseMalformedState, fd as resolveStateBucketWithDefault, fi as withoutSuperseded, fl as unionOfSecretBags, fn as nestedChildStackName$1, fo as cfnRefValueFromPhysicalId, fr as removeProtectionTypeList, fs as malformedOrphanRecordsWarning, fu as applyCrossPrefixScan, g as childTemplateLoader, gc as withheldAccountClause, gd as warnDeprecatedNoPrefixCliFlag, gi as noEchoParameterNamesOf, gl as maskSecretsInText, gn as withNestedRevertRun, gr as nameScopeOf, gs as refuseMalformedOrphanRecordsForDestroy, gu as stackInstanceIdOf, h as readRecordedConditionVerdicts, ha as CloudControlProvider, hc as accountArgs, hd as stateBucketExistenceConfirmed, hi as noEchoExactEchoLeavesOf, hl as maskSecretsInError, hn as revertedNestedRowIds, ho as refStateLookupFromResource, hr as nameGenerationHighWaterOf, hs as refuseMalformedOrphanRecords, hu as isNotImplemented, ia as isCustomResource, ic as STATE_REGION_DIVERGED, id as synthesisStatusMessage, ii as deleteSupersededEntry, il as createUnionSecretMasker, in as loadJournaledOrphans, ir as recordUnderIdIsNotOwn, is as describeTypeWithThrottleRetry, iu as shouldRetainResource, j as recordedProtectionNote, jd as StageLoadError, ji as ATOMIC_FINAL_SNAPSHOT_TYPES, jl as recordNestedStackParameterExpressions, jn as looselyEqual, jo as unsettledItemsOf, jr as secretBearingStateKeyWarning, js as refuseMalformedResourceEntriesForImportSave, ju as getBootstrapMarkerKey, k as diffSecurity, kd as refuseFailedLookups, ki as storedSecretNameNeedles, kn as withMovedTo, kr as exportAliasCollisionScrubWarning, ks as refuseMalformedResourceEntriesForDestroy, ku as assertAssetBucketRegion, l as crossStackOutputProvenanceSource, la as TemplateNoEchoReresolver, lc as refuseMalformedResourcesForDeploy, ld as resolveAutoAssetStorage, li as supersededHeldByOtherTypeWarning, ll as recordLogOnlyParameterValue, ln as displacedPhysicalIdShown, lo as isUnboundTemplateParameter, ls as deployRefusesOrphanRowsReason, lu as rebuildClientForBucketRegion, m as parentSuppliedValues, mc as JSON_LISTING_HOLE_VALUE, md as resolveUseCdkBootstrapAssets, mi as noEchoComparisonForTemplate, ml as errorCauseChain, mo as lacksRecordedTableArn, mr as nameGenerationCarriedFrom, ms as previewableOrphanRecords, mu as isAccessDenied, na as ProviderRegistry, nc as refuseMalformedOutputsForDestroy, nd as getDockerImageBySourceHash, ni as yellow, nn as isHandledOrphan, no as regionLessSecretName, nr as planFailedOps, ns as prefetchCreateOnlyPropertyPaths, nu as orphansAfterRollback, o as isSecretBearingReferenceString, oa as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, oc as malformedRenderedContainersWarning, od as getLegacyStateBucketName, oi as isSupersededResourceRecord, ol as literalSplitDelimitersOf, on as makeForeignHolderScan, or as resolveReplacementOldType, os as parameterInputsFor, ou as PhaseClock, p as conditionInputsFrom, pa as withPrintingSecrets, pc as repairMalformedResourcesForReadOnly, pd as resolveStateBucketWithDefaultAndSource, pi as noEchoAttributeNamesOf, pl as createSecretMasker, pn as recordDisplacedSkips, po as isStalePlaceholderArnAttribute, pr as orphanNeedsIdentity, ps as malformedOrphanRowsKeptWarning, pu as crossPrefixDeniedWarning, qa as isIamRoleArn, qd as injectedAwsRegionValue, ql as acceptedCreateOnlyDropsOf, qn as ledgerForStack, qr as destroyStackRecordsView, qs as refuseMalformedOrphansForDestroy, qu as partitionSensitiveEnv, ra as ccBrokenReason, rc as repairMalformedOutputsForReadOnly, rd as Synthesizer, ri as addSuperseded, rl as carryLogOnlyValues, rn as journaledOrphanLines, rr as recheckFailedPlan, rs as templateResourceTypes, ru as orphansCarriedFrom, s as keptWholeReasonText, sa as applyCustomResourceResponseExpiration, sc as malformedResourcesWarning, sd as loadCdkJson, si as removeSuperseded, sl as logOnlyValueCount, sn as NESTED_PENDING_PARENT_REASON, sr as findNestedStackTypeChanges, su as renderPhaseTimings, t as DeployEngine, ta as CC_BROKEN_REASON, tc as refuseMalformedOutputs, td as AssetManifestLoader, ti as red, tn as dropFailedHint, to as producerRegionsFromState, tr as isReplacementOrphan, tu as isReadableBag, u as inheritedProvenanceForChildDiff, ua as readsNoEchoDeleteValues, uc as refuseMalformedResourcesForDestroy, ud as resolveCaptureObservedState, ui as supersededHolderOf, ul as recordLogOnlyValue, un as dropSettledNestedJournals, uo as parameterTypeMayLoseSecretIdentity, us as isReadableOrphanRecord, uu as CrossPrefixReadError, v as isAbsoluteAssetPath, va as setResolvedResourceTimeouts, vc as UNREADABLE_RESOURCES_MAP_ROW, vd as CFN_TEMPLATE_BODY_LIMIT, vi as createReadOnlyAttributeHealerFactory, vl as withPhysicalNameCopies, vn as getCurrentNestedStackContext, vr as retiredNameGenerationsAfter, vs as repairMalformedOrphanRecordsForReadOnly, vu as AssetPublisher, w as pendingMovesRefusalMessage, wa as deleteSkipReason, wd as decodeListingKey, wi as secretNamePrintingBag, wl as pathCrossesDottedKey, wn as formatDestructiveChange, wo as isNamelessDynamicReferenceError, wr as namesAnyDeclaredParameter, ws as malformedResourceEntriesWarning, wu as loadPublishableAssetManifest, x as templateIdentity, xa as UNSPECIFIED_SKIP_REASON, xc as hasReadableResources, xd as findLargeInlineResources, xi as maskEventTextWithBoundBags, xl as dynamicReferenceTokens, xn as DeploymentEventsStore, xo as getAccountInfo, xs as isReadableResourceEntry, xu as WorkGraph, y as listNestedTemplateRows, ya as slowCcOperationTimeoutMs, yc as displayLogicalId, yd as CFN_TEMPLATE_URL_LIMIT, yi as completedReplayEntries, yn as withNestedStackContext, yo as recordedOutputReferenceRegions, yr as retiredNameGenerationsLeaving, ys as unpreviewableOrphanRecords, yu as isSensitiveAttributeName, zc as isMarkedCoordinate, zd as nullPrototypeRecord, zi as buildFinalSnapshotIdentifier, zl as recordProvenPublicExpression, zn as withUnprovenUnsettled, zo as isStatefulRecreateTargetSync, zr as collectPublishedOutputNames, zs as refuseMalformedResourcePropertiesForExport, zt as readRefactorMarker, zu as describeDockerCapturedOutput } from "./deploy-engine-BktCSZdi.js";
6
+ import { t as getCdkdVersion } from "./version-CO5muce9.js";
7
7
  import { t as cdkdCacheHome } from "./cli.js";
8
8
  import { randomBytes, randomUUID } from "node:crypto";
9
9
  import { CopyObjectCommand, CreateBucketCommand, DeleteBucketCommand, DeleteObjectsCommand, GetBucketLocationCommand, GetObjectCommand, HeadBucketCommand, ListObjectVersionsCommand, ListObjectsV2Command, NoSuchBucket, NotFound, PutBucketEncryptionCommand, PutBucketPolicyCommand, PutBucketVersioningCommand, PutObjectCommand, S3Client, S3ServiceException } from "@aws-sdk/client-s3";
@@ -1852,7 +1852,7 @@ function collectCrossStackRefs(node, onRef, unconditional) {
1852
1852
  // src/provisioning/register-providers.ts
1853
1853
  let providerClasses;
1854
1854
  function loadProviderClasses() {
1855
- providerClasses ??= import("./provider-classes-D0isRHVc.js");
1855
+ providerClasses ??= import("./provider-classes-BDPm7luc.js");
1856
1856
  return providerClasses;
1857
1857
  }
1858
1858
  function registerAllProviders(registry, classes) {
@@ -12251,6 +12251,85 @@ function createDriftCommand() {
12251
12251
  return cmd;
12252
12252
  }
12253
12253
 
12254
+ // src/cli/commands/destroy-runner/types.ts
12255
+ const NOECHO_PRINTING_BIND_CAP_MS = 1e4;
12256
+
12257
+ // src/cli/commands/destroy-runner/helpers.ts
12258
+ async function purgeStateHistoryIfOptedIn(ctx, stackName, region) {
12259
+ if (ctx.purgeStateHistory === true) await ctx.stateBackend.purgeDeletedStateHistory(stackName, region);
12260
+ }
12261
+ const NESTED_STACK_TYPE = "AWS::CloudFormation::Stack";
12262
+ function maskedSnapshotLogger(logger, mask) {
12263
+ return {
12264
+ info: (message) => logger.info(mask(message)),
12265
+ debug: (message) => logger.debug(mask(message))
12266
+ };
12267
+ }
12268
+ function recordDestroyEvent(recorder, event) {
12269
+ recorder?.record(maskEventTextWithBoundBags(event));
12270
+ }
12271
+ const SKIPPED_REMEDY = "Each 'skipped (...)' line above names its cause, and its warning says whether repairing the record in state.json helps. Where it does, repair it and re-run. Otherwise (for example a custom-resource Delete handler that reported FAILED), delete the resources by hand, then drop the records.";
12272
+ function countProtectedResources(state) {
12273
+ let count = 0;
12274
+ const records = [...Object.values(state.resources ?? {}), ...supersededResourcesOf(state).map((entry) => entry.state)];
12275
+ for (const resource of records) {
12276
+ const locator = perType(PROTECTION_PROPERTY_BY_TYPE, resource.resourceType);
12277
+ if (locator) {
12278
+ const isActive = (recorded) => isProtectionValueActive(resource.resourceType, recorded);
12279
+ if (isActive(readProtection(resource.properties, locator, state.region)) || isActive(readProtection(resource.observedProperties, locator, state.region))) count++;
12280
+ continue;
12281
+ }
12282
+ }
12283
+ return count;
12284
+ }
12285
+ function countProtectedJournaledOrphans(orphans, region) {
12286
+ let count = 0;
12287
+ for (const { ops } of orphans.segments) for (const op of ops) {
12288
+ if (op.physicalIdRecoveredFromError !== true || op.deletionPolicy === "Retain") continue;
12289
+ if (orphanNeedsIdentity(op) && !op.createdResourceIdentity) continue;
12290
+ const locator = perType(PROTECTION_PROPERTY_BY_TYPE, op.resourceType);
12291
+ if (locator && isProtectionValueActive(op.resourceType, readProtection(op.attemptedProperties, locator, region))) count++;
12292
+ }
12293
+ return count;
12294
+ }
12295
+ async function releaseRegistryMarkerAfterDestroy(ctx, stackName, region, logger) {
12296
+ if (ctx.crossPrefixCheck === void 0) return;
12297
+ try {
12298
+ const known = await ctx.crossPrefixCheck.cache.knownMarker?.(stackName, region);
12299
+ const released = await ctx.stateBackend.releaseRegistryMarker(stackName, region, known);
12300
+ logger.debug(safeMsg`Stack registry marker: ${released}`);
12301
+ } catch (error) {
12302
+ logger.warn(safeMsg`Could not delete the stack registry marker of ${displayStackName(stackName)} ` + safeMsg`(${describeAwsFailure(error).summary}). It names this state prefix, which no longer ` + `records the stack, so a deploy under another prefix treats it as stale.`);
12303
+ }
12304
+ }
12305
+ function holdsSameResourcesAs(snapshot, current) {
12306
+ return isDeepStrictEqual(snapshot.resources, current.resources) && isDeepStrictEqual(snapshot.supersededResources, current.supersededResources);
12307
+ }
12308
+ async function scanActiveConsumers(producerStack, producerRegion, ctx) {
12309
+ const refs = await ctx.stateBackend.listStacks();
12310
+ return (await Promise.all(refs.map(async (ref) => {
12311
+ const region = ref.region ?? ctx.baseRegion;
12312
+ if (ref.stackName === producerStack && region === producerRegion) return null;
12313
+ try {
12314
+ const imports = (await ctx.stateBackend.getState(ref.stackName, region))?.state.imports;
12315
+ if (!imports || imports.length === 0) return null;
12316
+ const matches = imports.filter((entry) => entry.sourceStack === producerStack && canonicalizeRegion(entry.sourceRegion) === canonicalizeRegion(producerRegion));
12317
+ if (matches.length === 0) return null;
12318
+ return matches.map((entry) => ({
12319
+ consumerStack: ref.stackName,
12320
+ consumerRegion: region,
12321
+ exportName: entry.exportName
12322
+ }));
12323
+ } catch {
12324
+ return null;
12325
+ }
12326
+ }))).filter((r) => r !== null).flat();
12327
+ }
12328
+ function refuseNewPendingRequests(read, stackName, region) {
12329
+ if ((read.pendingRequests ?? 0) === 0) return;
12330
+ throw new Error(`The rollback journal of stack ${displayStackName(stackName)} (${displaySafe(region, { asciiOnly: true })}) now records a Cloud Control CREATE a failed deploy stopped waiting for — another cdkd process wrote to it. Nothing was deleted; re-run the destroy, which checks how that CREATE ended first.`);
12331
+ }
12332
+
12254
12333
  // src/cli/commands/stack-lock-guard.ts
12255
12334
  async function acquireStackLock(opts) {
12256
12335
  const { lockManager, stackName, region, recovery } = opts;
@@ -12332,6 +12411,129 @@ async function acquireStackLock(opts) {
12332
12411
  };
12333
12412
  }
12334
12413
 
12414
+ // src/cli/commands/destroy-runner/preflight.ts
12415
+ async function refuseMalformedRecordAndLoadJournaledOrphans({ state, stackName, regionForState, refusalRecovery, ctx, logger, stackLockBase }) {
12416
+ refuseMalformedResourcesForDestroy(state, stackName, regionForState, refusalRecovery);
12417
+ refuseMalformedResourceEntriesForDestroy(state, stackName, regionForState, refusalRecovery);
12418
+ refuseMalformedResourcePropertiesForDestroy(state, stackName, regionForState, refusalRecovery);
12419
+ refuseMalformedOrphansForDestroy(state, stackName, regionForState, refusalRecovery);
12420
+ refuseMalformedOrphanRecordsForDestroy(state, stackName, regionForState, refusalRecovery);
12421
+ refusePendingMovesOut(state, stackName, regionForState, "cdkd destroy");
12422
+ let journalAtEntry;
12423
+ try {
12424
+ journalAtEntry = { journal: await ctx.stateBackend.loadRollbackJournal(stackName, regionForState) };
12425
+ } catch (error) {
12426
+ journalAtEntry = { error };
12427
+ }
12428
+ if (ctx.divergentBodyRegion !== void 0 && "journal" in journalAtEntry && pendingRequestCount(journalAtEntry.journal) > 0) {
12429
+ const ids = (journalAtEntry.journal?.segments ?? []).flatMap((segment) => segment.failedOperations ?? []).filter((op) => op.pendingCloudControlRequest !== void 0).map((op) => op.logicalId);
12430
+ const drop = dropFailedCommands(stackName, regionForState, ids);
12431
+ throw new CdkdError(`Stack ${displayStackName(stackName)}'s state record names another region than its key, and its rollback journal records a Cloud Control CREATE a failed deploy stopped waiting for. cdkd cannot tell which region to check it in. Nothing was deleted. Check the request in each region with aws cloudcontrol get-resource-request-status --request-token <token> --region <region> (the token is in the stack's rollback-journal.json), reconcile what it made by hand, then drop the entry and re-run:` + (drop === void 0 ? "" : drop.commands.map((c) => `\n ${c}`).join("")), "DESTROY_CC_PENDING_REQUEST_DIVERGENT_REGION");
12432
+ }
12433
+ const journalRewritten = await resolvePendingCloudControlRequests({
12434
+ journal: ctx.stateBackend,
12435
+ loaded: "journal" in journalAtEntry ? journalAtEntry.journal : null,
12436
+ reader: () => new CloudControlProvider(),
12437
+ stackName,
12438
+ region: regionForState,
12439
+ command: "destroy",
12440
+ logger,
12441
+ stateResources: state.resources,
12442
+ stackInstanceId: stackInstanceIdOf(state, displayStackName(stackName)),
12443
+ underLock: async (settle) => {
12444
+ const held = await acquireStackLock({
12445
+ ...stackLockBase,
12446
+ onFirstSignal: () => {
12447
+ process.stderr.write(`\nInterrupt received - finishing the Cloud Control request check for ${displayStackName(stackName)} (press Ctrl-C again to force-quit)\n`);
12448
+ }
12449
+ });
12450
+ try {
12451
+ return await settle();
12452
+ } finally {
12453
+ await held.release({ failureMessage: "Failed to release lock after settling an abandoned Cloud Control request" });
12454
+ }
12455
+ }
12456
+ });
12457
+ const entryRead = journalAtEntry;
12458
+ const journaledOrphans = await loadJournaledOrphans(journalRewritten ? ctx.stateBackend : { loadRollbackJournal: () => "journal" in entryRead ? Promise.resolve(entryRead.journal) : Promise.reject(entryRead.error) }, stackName, regionForState, state.orphans, logger);
12459
+ refuseDivergentRecordRegionForDestroy(state, stackName, regionForState, ctx.divergentBodyRegion, refusalRecovery, journaledOrphans.segments.flatMap((g) => g.ops).filter((op) => op.physicalIdRecoveredFromError === true).length);
12460
+ return journaledOrphans;
12461
+ }
12462
+ async function destroyEmptyStack({ stackName, ctx, logger, stackLockBase, regionForState, refusalRecovery, journaledOrphans, result }) {
12463
+ logger.info(`Stack ${displayStackName(stackName)} has no resources, cleaning up state...`);
12464
+ const emptyLock = await acquireStackLock({
12465
+ ...stackLockBase,
12466
+ onFirstSignal: () => {
12467
+ process.stderr.write(`\nInterrupt received - finishing the state cleanup for ${displayStackName(stackName)} (press Ctrl-C again to force-quit)\n`);
12468
+ }
12469
+ });
12470
+ try {
12471
+ const recheck = await ctx.stateBackend.getState(stackName, regionForState);
12472
+ if (recheck) {
12473
+ refuseMalformedResourcesForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12474
+ refuseMalformedResourceEntriesForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12475
+ refuseMalformedOrphansForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12476
+ refuseMalformedOrphanRecordsForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12477
+ refusePendingMovesOut(recheck.state, stackName, regionForState, "cdkd destroy");
12478
+ }
12479
+ refuseRefactorMarker(await readRefactorMarker(ctx.stateBackend), stackName, regionForState, "cdkd destroy");
12480
+ const recheckResources = recheck ? Object.keys(recheck.state.resources).length : 0;
12481
+ const recheckOrphans = recheck ? (recheck.state.orphans ?? []).length : 0;
12482
+ const recheckRead = await loadJournaledOrphans(ctx.stateBackend, stackName, regionForState, recheck?.state.orphans, journaledOrphans.unreadable === true ? { warn: () => void 0 } : logger);
12483
+ const recheckJournaled = recheckRead.count;
12484
+ refuseNewPendingRequests(recheckRead, stackName, regionForState);
12485
+ if (recheckJournaled > 0) throw new Error(`Stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) was empty when this run started but its rollback journal now records ${recheckJournaled} resource(s) a failed deploy created — another cdkd process wrote to it. Re-run the destroy to act on the current state.`);
12486
+ if (!(!recheck || recheckResources === 0 && recheckOrphans === 0 && !holdsSupersededResources(recheck.state))) throw new Error(`Stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) was empty when this run started but now has ${recheckResources} resource(s) and ${recheckOrphans} rollback-orphaned resource(s) — another cdkd process wrote to it. Re-run the destroy to act on the current state.`);
12487
+ await ctx.stateBackend.deleteState(stackName, regionForState);
12488
+ result.stateDeleted = true;
12489
+ logger.info(`${green("✓")} State deleted`);
12490
+ await Promise.all([recordRetainedForReadoption(ctx.stateBackend, stackName, regionForState, [], logger).then(() => purgeStateHistoryIfOptedIn(ctx, stackName, regionForState)), releaseRegistryMarkerAfterDestroy(ctx, stackName, regionForState, logger)]);
12491
+ } finally {
12492
+ await emptyLock.release({ failureMessage: "Failed to release lock after empty-state cleanup" });
12493
+ }
12494
+ result.skippedEmpty = true;
12495
+ return result;
12496
+ }
12497
+ async function announceOrphansAndConfirm({ state, logger, stackNoEchoValues, journaledOrphans, ctx, stackName, resourceCount, protectedCount, result }) {
12498
+ const orphansAtDestroy = state.orphans ?? [];
12499
+ if (orphansAtDestroy.length > 0) {
12500
+ logger.info(`\n${orphansAtDestroy.length} resource(s) are still in AWS from an earlier failed deploy. cdkd left them there because their DeletionPolicy is Retain (CDK's RemovalPolicy.RETAIN), and has been tracking them so a later deploy of this stack could adopt them back instead of colliding with their names.`);
12501
+ logger.info("Destroying this stack deletes that record. The resources stay in AWS, may continue to incur charges, and cdkd will no longer know about them:");
12502
+ const orphanListing = orphanRecordsPrintingBag(orphansAtDestroy, await stackNoEchoValues());
12503
+ for (const entry of orphansAtDestroy) withPrintingSecrets(orphanListing, () => logger.info(` - ${displaySafe(entry.logicalId)} (${displaySafe(entry.state.resourceType)}) ${displaySafe(entry.state.physicalId)}`));
12504
+ }
12505
+ if (journaledOrphans.count > 0) {
12506
+ logger.info(`\n${journaledOrphans.count} resource(s) were created by a failed deploy and are recorded only in the rollback journal. Each is deleted first as its DeletionPolicy directs (Retain keeps it in AWS, Snapshot takes the final snapshot), unless state or a later deploy may own it, which is warned about instead:`);
12507
+ const listing = journaledOrphanPrintingBag(journaledOrphans.segments.flatMap(({ ops }) => ops), state.resources, await stackNoEchoValues());
12508
+ withPrintingSecrets(listing, () => {
12509
+ for (const line of journaledOrphanLines(journaledOrphans, logger)) logger.info(line);
12510
+ });
12511
+ }
12512
+ if (!ctx.skipConfirmation) {
12513
+ if (process.stdin.isTTY !== true) throw new CdkdError(`The destroy confirmation prompt for stack ${displayStackName(stackName)} cannot run in a non-interactive environment. Pass --yes / -y to confirm the destroy (cdkd destroy also accepts -f / --force), or run the command from a real terminal.`, "NON_INTERACTIVE_CONFIRM");
12514
+ const rl = readline$1.createInterface({
12515
+ input: process.stdin,
12516
+ output: process.stdout
12517
+ });
12518
+ const journaledClause = journaledOrphans.count > 0 ? ` and ${journaledOrphans.count} recorded only in its rollback journal` : "";
12519
+ const prompt = ctx.removeProtection ? `\nAbout to destroy ${resourceCount} resources${journaledClause} from stack ${displayStackName(stackName)}, REMOVING DELETION PROTECTION on ${protectedCount} of them. Continue? (y/N): ` : `\nAre you sure you want to destroy stack ${displayStackName(stackName)} and delete all ${resourceCount} resources${journaledClause}? (Y/n): `;
12520
+ const answer = await rl.question(prompt);
12521
+ rl.close();
12522
+ const trimmed = answer.trim().toLowerCase();
12523
+ if (ctx.removeProtection) {
12524
+ if (trimmed !== "y" && trimmed !== "yes") {
12525
+ logger.info("Destroy cancelled");
12526
+ result.cancelled = true;
12527
+ return result;
12528
+ }
12529
+ } else if (trimmed === "n" || trimmed === "no") {
12530
+ logger.info("Destroy cancelled");
12531
+ result.cancelled = true;
12532
+ return result;
12533
+ }
12534
+ }
12535
+ }
12536
+
12335
12537
  // src/provisioning/secret-principal-resolution.ts
12336
12538
  const TRANSIENT_RESOLUTION_MESSAGE = "Resolving a secret-derived IAM principal list was throttled or hit a server error";
12337
12539
  function resolvableVerdict(verdict) {
@@ -12444,313 +12646,463 @@ function resolvablePrincipalLists(resource) {
12444
12646
  return keys.map((key) => props[key]).filter((value) => isResolvableSecretPrincipalList(value));
12445
12647
  }
12446
12648
 
12447
- // src/cli/commands/destroy-runner.ts
12448
- const NOECHO_PRINTING_BIND_CAP_MS = 1e4;
12449
- async function purgeStateHistoryIfOptedIn(ctx, stackName, region) {
12450
- if (ctx.purgeStateHistory === true) await ctx.stateBackend.purgeDeletedStateHistory(stackName, region);
12649
+ // src/cli/commands/destroy-runner/under-lock-steps.ts
12650
+ async function recheckUnderLock({ ctx, stackName, state, regionForState, refusalRecovery, lock, restoreBaseRegionAndClients, needsStrongRefCheck }) {
12651
+ try {
12652
+ const [current, marker] = await Promise.all([ctx.stateBackend.getState(stackName, regionForState), readRefactorMarker(ctx.stateBackend)]);
12653
+ if (current === null || !holdsSameResourcesAs(state, current.state)) throw new CdkdError(safeMsg`cdkd destroy refused stack ${stackName} (${regionForState}): its state ` + "changed after it was read (another command wrote it while this one waited for confirmation), so nothing was deleted. Re-run cdkd destroy.", "STATE_CHANGED");
12654
+ if (current.state.terminationProtection === true && ctx.removeProtection !== true) throw new StackTerminationProtectionError(stackName, void 0, {
12655
+ args: accountArgs(refusalRecovery),
12656
+ clause: withheldAccountClause(refusalRecovery, "the command below prints")
12657
+ }, {
12658
+ command: ctx.stateDestroy === true ? "cdkd state destroy" : "cdkd destroy",
12659
+ stackRegion: regionForState
12660
+ });
12661
+ refusePendingMovesOut(current.state, stackName, regionForState, "cdkd destroy");
12662
+ refuseRefactorMarker(marker, stackName, regionForState, "cdkd destroy");
12663
+ } catch (error) {
12664
+ await lock.release({ failureMessage: "Failed to release lock after a state re-check refusal" });
12665
+ restoreBaseRegionAndClients();
12666
+ throw error;
12667
+ }
12668
+ if (needsStrongRefCheck) {
12669
+ const releaseThenUnregister = async () => {
12670
+ await lock.release({ failureMessage: "Failed to release lock after strong-ref refusal/failure" });
12671
+ restoreBaseRegionAndClients();
12672
+ };
12673
+ let consumers;
12674
+ try {
12675
+ consumers = await scanActiveConsumers(stackName, regionForState, ctx);
12676
+ } catch (error) {
12677
+ await releaseThenUnregister();
12678
+ throw error;
12679
+ }
12680
+ if (consumers.length > 0) {
12681
+ await releaseThenUnregister();
12682
+ throw new StackHasActiveImportsError(stackName, regionForState, consumers);
12683
+ }
12684
+ }
12451
12685
  }
12452
- const NESTED_STACK_TYPE = "AWS::CloudFormation::Stack";
12453
- function maskedSnapshotLogger(logger, mask) {
12686
+ function makeSummaryHints(regionForState, refusalRecovery) {
12687
+ const hintCommand = (command, t) => pasteableCommand(command, [
12688
+ {
12689
+ value: t,
12690
+ hole: "stack",
12691
+ opts: { plainIdent: true }
12692
+ },
12693
+ {
12694
+ flag: "--stack-region",
12695
+ value: regionForState,
12696
+ hole: "region",
12697
+ opts: { plainIdent: true }
12698
+ },
12699
+ ...accountArgs(refusalRecovery)
12700
+ ]);
12701
+ const hintFor = (command, targets, label) => [...new Set(targets.map((t) => `\n${label}: ${hintCommand(command, t).command}`))].join("");
12702
+ const hintHolesClause = (targets) => (targets.every((t) => hintCommand("cdkd state show", t).withheld.every((w) => w.hole !== "stack" && w.hole !== "region")) ? "" : " A target that is not a plain identifier is printed as a quoted '<stack>' or '<region>' placeholder; list the records as stored with 'cdkd state list --long'.") + (targets.length === 0 ? "" : ((clause) => clause === "" ? "" : ` ${clause}`)(withheldAccountClause(refusalRecovery, "the command lines below print").trimEnd()));
12454
12703
  return {
12455
- info: (message) => logger.info(mask(message)),
12456
- debug: (message) => logger.debug(mask(message))
12704
+ hintFor,
12705
+ hintHolesClause
12457
12706
  };
12458
12707
  }
12459
- function recordDestroyEvent(recorder, event) {
12460
- recorder?.record(maskEventTextWithBoundBags(event));
12708
+ async function reReadJournaledOrphansUnderLock({ ctx, stackName, regionForState, state, journaledOrphans, logger }) {
12709
+ const journaledUnderLock = await loadJournaledOrphans(ctx.stateBackend, stackName, regionForState, state.orphans, journaledOrphans.unreadable === true ? { warn: () => void 0 } : logger);
12710
+ if (journaledUnderLock.unreadable === true && journaledOrphans.unreadable !== true) throw new Error(`The rollback journal of stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) was readable when this run started and cannot be read now (see the warning above). Nothing was deleted; re-run the destroy once it can be read.`);
12711
+ refuseNewPendingRequests(journaledUnderLock, stackName, regionForState);
12712
+ if (!sameJournaledOrphans(journaledUnderLock, journaledOrphans)) throw new Error(`The rollback journal of stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) recorded ${journaledOrphans.count} resource(s) a failed deploy created when this run started and ${journaledUnderLock.count} now, not the same ones — another cdkd process wrote to it. Nothing was deleted; re-run the destroy to act on the current journal.`);
12713
+ return journaledUnderLock;
12461
12714
  }
12462
- const SKIPPED_REMEDY = "Each 'skipped (...)' line above names its cause, and its warning says whether repairing the record in state.json helps. Where it does, repair it and re-run. Otherwise (for example a custom-resource Delete handler that reported FAILED), delete the resources by hand, then drop the records.";
12463
- function countProtectedResources(state) {
12464
- let count = 0;
12465
- const records = [...Object.values(state.resources ?? {}), ...supersededResourcesOf(state).map((entry) => entry.state)];
12466
- for (const resource of records) {
12467
- const locator = perType(PROTECTION_PROPERTY_BY_TYPE, resource.resourceType);
12468
- if (locator) {
12469
- const isActive = (recorded) => isProtectionValueActive(resource.resourceType, recorded);
12470
- if (isActive(readProtection(resource.properties, locator, state.region)) || isActive(readProtection(resource.observedProperties, locator, state.region))) count++;
12471
- continue;
12715
+ function buildDeleteGraph(state, logger) {
12716
+ logger.info("Building dependency graph...");
12717
+ const template = {
12718
+ AWSTemplateFormatVersion: "2010-09-09",
12719
+ Resources: {}
12720
+ };
12721
+ for (const [logicalId, resource] of Object.entries(state.resources)) template.Resources[logicalId] = {
12722
+ Type: resource.resourceType,
12723
+ Properties: resource.properties || {},
12724
+ ...resource.dependencies && resource.dependencies.length > 0 && { DependsOn: resource.dependencies }
12725
+ };
12726
+ const blockingResources = { ...template.Resources };
12727
+ const typeToLogicalIds = /* @__PURE__ */ new Map();
12728
+ for (const [logicalId, resource] of Object.entries(state.resources)) {
12729
+ const ids = typeToLogicalIds.get(resource.resourceType) ?? [];
12730
+ ids.push(logicalId);
12731
+ typeToLogicalIds.set(resource.resourceType, ids);
12732
+ }
12733
+ for (const [logicalId, resource] of Object.entries(state.resources)) {
12734
+ const mustDeleteAfter = IMPLICIT_DELETE_DEPENDENCIES[resource.resourceType];
12735
+ if (!mustDeleteAfter) continue;
12736
+ for (const depType of mustDeleteAfter) {
12737
+ const depIds = typeToLogicalIds.get(depType);
12738
+ if (!depIds) continue;
12739
+ for (const depId of depIds) {
12740
+ const existing = template.Resources[depId]?.DependsOn ?? [];
12741
+ const depsArray = Array.isArray(existing) ? existing : [existing];
12742
+ if (!depsArray.includes(logicalId)) {
12743
+ template.Resources[depId] = {
12744
+ ...template.Resources[depId],
12745
+ DependsOn: [...depsArray, logicalId]
12746
+ };
12747
+ logger.debug(`Implicit delete dependency: ${displaySafe(depId)} (${displaySafe(depType)}) must be deleted before ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)})`);
12748
+ }
12749
+ }
12472
12750
  }
12473
12751
  }
12474
- return count;
12475
- }
12476
- function countProtectedJournaledOrphans(orphans, region) {
12477
- let count = 0;
12478
- for (const { ops } of orphans.segments) for (const op of ops) {
12479
- if (op.physicalIdRecoveredFromError !== true || op.deletionPolicy === "Retain") continue;
12480
- if (orphanNeedsIdentity(op) && !op.createdResourceIdentity) continue;
12481
- const locator = perType(PROTECTION_PROPERTY_BY_TYPE, op.resourceType);
12482
- if (locator && isProtectionValueActive(op.resourceType, readProtection(op.attemptedProperties, locator, region))) count++;
12483
- }
12484
- return count;
12485
- }
12486
- async function releaseRegistryMarkerAfterDestroy(ctx, stackName, region, logger) {
12487
- if (ctx.crossPrefixCheck === void 0) return;
12488
- try {
12489
- const known = await ctx.crossPrefixCheck.cache.knownMarker?.(stackName, region);
12490
- const released = await ctx.stateBackend.releaseRegistryMarker(stackName, region, known);
12491
- logger.debug(safeMsg`Stack registry marker: ${released}`);
12492
- } catch (error) {
12493
- logger.warn(safeMsg`Could not delete the stack registry marker of ${displayStackName(stackName)} ` + safeMsg`(${describeAwsFailure(error).summary}). It names this state prefix, which no longer ` + `records the stack, so a deploy under another prefix treats it as stale.`);
12494
- }
12495
- }
12496
- function holdsSameResourcesAs(snapshot, current) {
12497
- return isDeepStrictEqual(snapshot.resources, current.resources) && isDeepStrictEqual(snapshot.supersededResources, current.supersededResources);
12498
- }
12499
- async function runDestroyForStack(stackName, state, ctx) {
12500
- const stackRegion = state.region;
12501
- if (!stackRegion || stackRegion === ctx.baseRegion) return destroyStackInRegion(stackName, state, ctx, void 0);
12502
- const scopeClients = new AwsClients({
12503
- region: stackRegion,
12504
- ...ctx.profile && { profile: ctx.profile }
12505
- });
12506
- try {
12507
- const awsScope = {
12508
- region: stackRegion,
12509
- clients: scopeClients
12752
+ for (const { before, after } of computeImplicitDeleteEdges(state.resources)) {
12753
+ const blocking = blockingResources[before]?.DependsOn ?? [];
12754
+ const blockingArray = Array.isArray(blocking) ? blocking : [blocking];
12755
+ if (!blockingArray.includes(after)) blockingResources[before] = {
12756
+ ...blockingResources[before],
12757
+ DependsOn: [...blockingArray, after]
12510
12758
  };
12511
- const nestedContext = getCurrentNestedStackContext();
12512
- return await runInStackAwsScope(awsScope, () => {
12513
- const registry = new ProviderRegistry();
12514
- const destroyInScope = () => destroyStackInRegion(stackName, state, ctx, {
12515
- clients: scopeClients,
12516
- registry
12517
- });
12518
- return nestedContext === void 0 ? destroyInScope() : withNestedStackContext({
12519
- ...nestedContext,
12520
- providerRegistry: registry,
12521
- awsClients: scopeClients
12522
- }, destroyInScope);
12523
- });
12524
- } finally {
12525
- try {
12526
- scopeClients.destroy();
12527
- } catch (destroyError) {
12528
- getLogger().debug(`Failed to destroy region-scoped AWS clients: ${describeAwsFailure(destroyError).detail}`);
12759
+ const existing = template.Resources[before]?.DependsOn ?? [];
12760
+ const depsArray = Array.isArray(existing) ? existing : [existing];
12761
+ if (!depsArray.includes(after)) {
12762
+ template.Resources[before] = {
12763
+ ...template.Resources[before],
12764
+ DependsOn: [...depsArray, after]
12765
+ };
12766
+ logger.debug(`Implicit delete dependency: ${displaySafe(before)} (${displaySafe(state.resources[before]?.resourceType)}) must be deleted before ${displaySafe(after)} (${displaySafe(state.resources[after]?.resourceType)})`);
12529
12767
  }
12530
12768
  }
12531
- }
12532
- async function destroyStackInRegion(stackName, state, ctx, stackScope) {
12533
- const providerClasses = await loadProviderClasses();
12534
- const logger = getLogger();
12535
- const result = {
12536
- stackName,
12537
- cancelled: false,
12538
- skippedEmpty: false,
12539
- deletedCount: 0,
12540
- retainedCount: 0,
12541
- skippedCount: 0,
12542
- guardIndeterminateCount: 0,
12543
- journaledOrphanSkips: 0,
12544
- stateDeleted: false,
12545
- blockedCount: 0,
12546
- errorCount: 0,
12547
- interrupted: false
12548
- };
12549
- const retainedForReadoption = [];
12550
- let retainedEarlier;
12551
- const guardIndeterminateTargets = /* @__PURE__ */ new Set();
12552
- const regionForState = state.region ?? ctx.baseRegion;
12553
- const crossPrefixScan = ctx.crossPrefixCheck?.cache.full(stackName, regionForState);
12554
- const refusalRecovery = {
12555
- profile: ctx.profile,
12556
- stateBucket: ctx.stateBucket,
12557
- statePrefix: ctx.statePrefix
12558
- };
12559
- const stackLockBase = {
12560
- lockManager: ctx.lockManager,
12561
- stackName,
12562
- region: regionForState,
12563
- operation: "destroy",
12564
- recovery: refusalRecovery
12769
+ const dagBuilder = new DagBuilder();
12770
+ const graph = dagBuilder.buildGraph(template);
12771
+ const blockingGraph = dagBuilder.buildGraph({
12772
+ ...template,
12773
+ Resources: blockingResources
12774
+ });
12775
+ const executionLevels = dagBuilder.getExecutionLevels(graph);
12776
+ logger.debug(`Dependency graph: ${executionLevels.length} level(s)`);
12777
+ return {
12778
+ dagBuilder,
12779
+ blockingGraph,
12780
+ executionLevels
12565
12781
  };
12566
- refuseMalformedResourcesForDestroy(state, stackName, regionForState, refusalRecovery);
12567
- refuseMalformedResourceEntriesForDestroy(state, stackName, regionForState, refusalRecovery);
12568
- refuseMalformedResourcePropertiesForDestroy(state, stackName, regionForState, refusalRecovery);
12569
- refuseMalformedOrphansForDestroy(state, stackName, regionForState, refusalRecovery);
12570
- refuseMalformedOrphanRecordsForDestroy(state, stackName, regionForState, refusalRecovery);
12571
- refusePendingMovesOut(state, stackName, regionForState, "cdkd destroy");
12572
- let journalAtEntry;
12573
- try {
12574
- journalAtEntry = { journal: await ctx.stateBackend.loadRollbackJournal(stackName, regionForState) };
12575
- } catch (error) {
12576
- journalAtEntry = { error };
12782
+ }
12783
+ function makePrintingBagOf({ ctx, state, noEchoValues, stackName, logger }) {
12784
+ const reresolver = ctx.noEchoReresolver;
12785
+ const judgedBagOf = secretNamePrintingBags(state.resources, reresolver === void 0 ? noEchoValues : namingSecretsWithRecordedNoEcho(noEchoValues, (logicalId) => {
12786
+ try {
12787
+ return reresolver.recordedNoEchoValuesFor(logicalId, Object.hasOwn(state.resources, logicalId) ? state.resources[logicalId] : void 0);
12788
+ } catch (error) {
12789
+ logger.debug(safeMsg`Could not read ${logicalId}'s stored NoEcho values for its printing bag (${error instanceof Error ? error.name : typeof error}).`);
12790
+ return;
12791
+ }
12792
+ }));
12793
+ const namingScope = nameScopeOf(stackName, stackInstanceIdOf(state, displayStackName(stackName)), state);
12794
+ const printingBagOf = (logicalId) => withStackScope(namingScope, () => judgedBagOf(logicalId));
12795
+ return printingBagOf;
12796
+ }
12797
+ function printDestroySummary({ result, ctx, stackName, logger, preserveState, guardIndeterminateTargets, skippedStateTargets, failedStateTargets, hintFor, hintHolesClause, journaledOrphanFailures }) {
12798
+ const retainedSuffix = result.retainedCount > 0 ? `, ${result.retainedCount} retained` : "";
12799
+ const skippedSuffix = (result.skippedCount > 0 ? `, ${yellow(result.skippedCount)} skipped` : "") + (result.blockedCount > 0 ? `, ${yellow(result.blockedCount)} blocked` : "");
12800
+ const guardSuffix = result.guardIndeterminateCount > 0 ? `, ${yellow(result.guardIndeterminateCount)} unverified` : "";
12801
+ if (result.guardIndeterminateCount > 0) {
12802
+ const eventsCommand = pasteableCommand("cdkd events", [{
12803
+ value: stackName,
12804
+ hole: "stack",
12805
+ opts: { plainIdent: true }
12806
+ }]);
12807
+ const durablePointer = ctx.eventRecorder === void 0 ? "This summary is the only record: this run wrote no deployment events, because it destroyed a nested-stack child, which threads no event recorder." : "The RESOURCE_GUARD_INDETERMINATE entries name the check and the reason and survive the run." + withheldTargetClause(eventsCommand, "stack", "cdkd events", "This stack's name") + `\nRead them with: ${eventsCommand.command}`;
12808
+ logger.warn(`\n${yellow("⚠")} ${result.guardIndeterminateCount} pre-flight safety check(s) could NOT be completed during this destroy and cdkd proceeded anyway: ${[...guardIndeterminateTargets].map((t) => plainOrDescribed(t, "logical id")).join(", ")}. A check can be suppressed by DENYING the permission it needs, so treat this as unconfirmed rather than benign. ${durablePointer}`);
12809
+ }
12810
+ if (result.journaledOrphanSkips > 0) logger.warn(safeMsg`${result.journaledOrphanSkips} resource(s) a failed deploy created were left in AWS (each named in a ` + "warning above, which says what to do with it). This stack no longer records them.");
12811
+ if (!preserveState) {
12812
+ const leftInAws = result.journaledOrphanSkips > 0;
12813
+ logger.info(`\n${leftInAws ? yellow("⚠") : green("✓")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} ${leftInAws ? "destroyed, with resources left in AWS" : "destroyed"}`)} (${green(result.deletedCount)} deleted${retainedSuffix}${leftInAws ? skippedSuffix : ""}${guardSuffix}, ${result.errorCount} errors)`);
12814
+ } else if (result.interrupted && result.errorCount === 0) logger.warn(`\n${yellow("⚠")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} destroy interrupted`)} (${green(result.deletedCount)} deleted${retainedSuffix}${skippedSuffix}${guardSuffix}, ${result.errorCount} errors). State preserved — re-run 'cdkd destroy' / 'cdkd state destroy' to finish.`);
12815
+ else if (result.errorCount === 0) {
12816
+ const targets = [...skippedStateTargets];
12817
+ const showHint = hintFor("cdkd state show", targets, "Inspect it with");
12818
+ const orphanHint = hintFor("cdkd state orphan", targets, "Drop the record with");
12819
+ logger.warn(`\n${yellow("⚠")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} partially destroyed`)} (${green(result.deletedCount)} deleted${retainedSuffix}${skippedSuffix}${guardSuffix}, ${result.errorCount} errors). cdkd did not confirm the skipped resource(s) were deleted, so they may still exist in AWS. ${SKIPPED_REMEDY}` + hintHolesClause(targets) + showHint + orphanHint);
12820
+ } else {
12821
+ const failedTargets = failedStateTargets.size > 0 ? [...failedStateTargets] : [stackName];
12822
+ const orphanHint = journaledOrphanFailures > 0 ? "" : hintFor("cdkd state orphan", failedTargets, "Drop the record with");
12823
+ const skippedTargets = [...skippedStateTargets];
12824
+ const skippedClause = skippedTargets.length > 0 ? ` Separately, ${result.skippedCount} resource(s) were SKIPPED — cdkd did not confirm they were deleted, so they may still exist in AWS. ${SKIPPED_REMEDY}` : "";
12825
+ const droppableSkipped = journaledOrphanFailures > 0 ? skippedTargets.filter((t) => t !== stackName) : skippedTargets;
12826
+ const skippedCommands = hintFor("cdkd state show", skippedTargets, "Inspect it with") + hintFor("cdkd state orphan", droppableSkipped, "Drop the record with");
12827
+ const dedupedCommands = (lines) => [...new Set(lines.split("\n").filter((l) => l !== ""))].map((l) => `\n${l}`).join("");
12828
+ logger.warn(`\n${yellow("⚠")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} partially destroyed`)} (${green(result.deletedCount)} deleted${retainedSuffix}${skippedSuffix}${guardSuffix}, ${red(result.errorCount)} errors). State preserved — re-run 'cdkd destroy' / 'cdkd state destroy' to clean up. ` + (journaledOrphanFailures > 0 ? `${journaledOrphanFailures} of the failures are resources a failed deploy created that only the rollback journal records: re-run the destroy to retry them. Do not drop this stack's state record — that also deletes the journal, their only record.` : "If the same resource keeps failing, dropping the state record is the last resort: it removes the record without deleting AWS resources.") + skippedClause + hintHolesClause([...orphanHint === "" ? [] : failedTargets, ...skippedTargets]) + dedupedCommands(orphanHint + skippedCommands));
12829
+ }
12830
+ }
12831
+
12832
+ // src/cli/commands/destroy-runner/delete-resource.ts
12833
+ async function deleteStackResource({ lock, state, ctx, stackName, logger, result, renderer, blockedBy, blockedIds, blockDependenciesOf, retainedForReadoption, startRetainedEarlierRead, skippedStateTargets, failedStateTargets, stateTargetFor, guardIndeterminateTargets, remainingResources, persistStateAfterDelete, printingBagOf, destroyProviderRegistry, destroyAwsClients, secretPrincipalRegions, secretPrincipalRegionsIncomplete }, logicalId, stackRegion) {
12834
+ if (lock.interrupted) return;
12835
+ const resource = state.resources[logicalId];
12836
+ if (!resource) {
12837
+ logger.warn(`Resource ${displaySafe(logicalId)} not found in state, skipping`);
12838
+ return;
12577
12839
  }
12578
- if (ctx.divergentBodyRegion !== void 0 && "journal" in journalAtEntry && pendingRequestCount(journalAtEntry.journal) > 0) {
12579
- const ids = (journalAtEntry.journal?.segments ?? []).flatMap((segment) => segment.failedOperations ?? []).filter((op) => op.pendingCloudControlRequest !== void 0).map((op) => op.logicalId);
12580
- const drop = dropFailedCommands(stackName, regionForState, ids);
12581
- throw new CdkdError(`Stack ${displayStackName(stackName)}'s state record names another region than its key, and its rollback journal records a Cloud Control CREATE a failed deploy stopped waiting for. cdkd cannot tell which region to check it in. Nothing was deleted. Check the request in each region with aws cloudcontrol get-resource-request-status --request-token <token> --region <region> (the token is in the stack's rollback-journal.json), reconcile what it made by hand, then drop the entry and re-run:` + (drop === void 0 ? "" : drop.commands.map((c) => `\n ${c}`).join("")), "DESTROY_CC_PENDING_REQUEST_DIVERGENT_REGION");
12840
+ const blocker = blockedBy.get(logicalId);
12841
+ if (blocker !== void 0) {
12842
+ const blockReason = `${blocker} depends on it and its delete failed`;
12843
+ logger.info(safeMsg` ${formatResourceLine("skipped", logicalId, resource.resourceType, `not deleted (${blockReason})`)}`);
12844
+ result.blockedCount++;
12845
+ blockedIds.push(logicalId);
12846
+ recordDestroyEvent(ctx.eventRecorder, {
12847
+ eventType: "RESOURCE_SKIPPED",
12848
+ stackName,
12849
+ operation: "DELETE",
12850
+ logicalId,
12851
+ resourceType: resource.resourceType,
12852
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
12853
+ ...resource.physicalId && { physicalId: resource.physicalId },
12854
+ reason: blockReason
12855
+ });
12856
+ return;
12582
12857
  }
12583
- const journalRewritten = await resolvePendingCloudControlRequests({
12584
- journal: ctx.stateBackend,
12585
- loaded: "journal" in journalAtEntry ? journalAtEntry.journal : null,
12586
- reader: () => new CloudControlProvider(),
12587
- stackName,
12588
- region: regionForState,
12589
- command: "destroy",
12590
- logger,
12591
- stateResources: state.resources,
12592
- stackInstanceId: stackInstanceIdOf(state, displayStackName(stackName)),
12593
- underLock: async (settle) => {
12594
- const held = await acquireStackLock({
12595
- ...stackLockBase,
12596
- onFirstSignal: () => {
12597
- process.stderr.write(`\nInterrupt received - finishing the Cloud Control request check for ${displayStackName(stackName)} (press Ctrl-C again to force-quit)\n`);
12598
- }
12858
+ if (shouldRetainResource(resource.deletionPolicy)) {
12859
+ logger.info(` ⊘ ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)}) retained — DeletionPolicy: ${displaySafe(resource.deletionPolicy)}`);
12860
+ result.retainedCount++;
12861
+ if (keptForRetainedRecord(resource)) {
12862
+ retainedForReadoption.push({
12863
+ logicalId,
12864
+ resourceType: resource.resourceType,
12865
+ physicalId: resource.physicalId
12599
12866
  });
12600
- try {
12601
- return await settle();
12602
- } finally {
12603
- await held.release({ failureMessage: "Failed to release lock after settling an abandoned Cloud Control request" });
12604
- }
12867
+ startRetainedEarlierRead();
12605
12868
  }
12606
- });
12607
- const entryRead = journalAtEntry;
12608
- const journaledOrphans = await loadJournaledOrphans(journalRewritten ? ctx.stateBackend : { loadRollbackJournal: () => "journal" in entryRead ? Promise.resolve(entryRead.journal) : Promise.reject(entryRead.error) }, stackName, regionForState, state.orphans, logger);
12609
- refuseDivergentRecordRegionForDestroy(state, stackName, regionForState, ctx.divergentBodyRegion, refusalRecovery, journaledOrphans.segments.flatMap((g) => g.ops).filter((op) => op.physicalIdRecoveredFromError === true).length);
12610
- const resourceCount = Object.keys(state.resources).length;
12611
- const orphanCount = (state.orphans ?? []).length;
12612
- const supersededCount = supersededResourcesOf(state).length;
12613
- refuseMalformedOutputsForDestroy(state, stackName, regionForState, refusalRecovery);
12614
- if (crossPrefixScan) applyCrossPrefixScan(await crossPrefixScan, {
12615
- stackName,
12616
- region: regionForState,
12617
- bucket: ctx.stateBucket,
12618
- recovery: {
12619
- profile: ctx.profile,
12620
- stateBucket: ctx.stateBucket
12621
- }
12622
- }, "destroy", (message) => logger.warn(message), (message) => logger.info(message));
12623
- if (resourceCount === 0 && orphanCount === 0 && !holdsSupersededResources(state) && journaledOrphans.count === 0) {
12624
- logger.info(`Stack ${displayStackName(stackName)} has no resources, cleaning up state...`);
12625
- const emptyLock = await acquireStackLock({
12626
- ...stackLockBase,
12627
- onFirstSignal: () => {
12628
- process.stderr.write(`\nInterrupt received - finishing the state cleanup for ${displayStackName(stackName)} (press Ctrl-C again to force-quit)\n`);
12629
- }
12869
+ recordDestroyEvent(ctx.eventRecorder, {
12870
+ eventType: "RESOURCE_RETAINED",
12871
+ stackName,
12872
+ operation: "DELETE",
12873
+ logicalId,
12874
+ resourceType: resource.resourceType,
12875
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy }
12630
12876
  });
12631
- try {
12632
- const recheck = await ctx.stateBackend.getState(stackName, regionForState);
12633
- if (recheck) {
12634
- refuseMalformedResourcesForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12635
- refuseMalformedResourceEntriesForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12636
- refuseMalformedOrphansForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12637
- refuseMalformedOrphanRecordsForDestroy(recheck.state, stackName, regionForState, refusalRecovery);
12638
- refusePendingMovesOut(recheck.state, stackName, regionForState, "cdkd destroy");
12639
- }
12640
- refuseRefactorMarker(await readRefactorMarker(ctx.stateBackend), stackName, regionForState, "cdkd destroy");
12641
- const recheckResources = recheck ? Object.keys(recheck.state.resources).length : 0;
12642
- const recheckOrphans = recheck ? (recheck.state.orphans ?? []).length : 0;
12643
- const recheckRead = await loadJournaledOrphans(ctx.stateBackend, stackName, regionForState, recheck?.state.orphans, journaledOrphans.unreadable === true ? { warn: () => void 0 } : logger);
12644
- const recheckJournaled = recheckRead.count;
12645
- refuseNewPendingRequests(recheckRead, stackName, regionForState);
12646
- if (recheckJournaled > 0) throw new Error(`Stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) was empty when this run started but its rollback journal now records ${recheckJournaled} resource(s) a failed deploy created — another cdkd process wrote to it. Re-run the destroy to act on the current state.`);
12647
- if (!(!recheck || recheckResources === 0 && recheckOrphans === 0 && !holdsSupersededResources(recheck.state))) throw new Error(`Stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) was empty when this run started but now has ${recheckResources} resource(s) and ${recheckOrphans} rollback-orphaned resource(s) — another cdkd process wrote to it. Re-run the destroy to act on the current state.`);
12648
- await ctx.stateBackend.deleteState(stackName, regionForState);
12649
- result.stateDeleted = true;
12650
- logger.info(`${green("✓")} State deleted`);
12651
- await Promise.all([recordRetainedForReadoption(ctx.stateBackend, stackName, regionForState, [], logger).then(() => purgeStateHistoryIfOptedIn(ctx, stackName, regionForState)), releaseRegistryMarkerAfterDestroy(ctx, stackName, regionForState, logger)]);
12652
- } finally {
12653
- await emptyLock.release({ failureMessage: "Failed to release lock after empty-state cleanup" });
12654
- }
12655
- result.skippedEmpty = true;
12656
- return result;
12657
- }
12658
- const needsStrongRefCheck = !!(state.outputs && Object.keys(state.outputs).length > 0);
12659
- if (needsStrongRefCheck) {
12660
- const consumers = await scanActiveConsumers(stackName, regionForState, ctx);
12661
- if (consumers.length > 0) throw new StackHasActiveImportsError(stackName, regionForState, consumers);
12877
+ return;
12662
12878
  }
12663
- logger.info(`\nResources to be deleted (${resourceCount}):`);
12664
- for (const [logicalId, resource] of Object.entries(state.resources)) logger.info(` - ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)})`);
12665
- if (supersededCount > 0) {
12666
- logger.info(safeMsg`\nOld resources a replacement left to delete (${supersededCount}):`);
12667
- for (const entry of supersededResourcesOf(state)) logger.info(safeMsg` - ${entry.logicalId} (${entry.state.resourceType}), superseded`);
12879
+ if (resource.resourceType !== "AWS::CloudFormation::Stack" && (typeof resource.physicalId !== "string" || resource.physicalId.trim() === "")) {
12880
+ const skipReason = "state record has no physical id";
12881
+ logger.warn(`Resource ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)}) has no non-empty string 'physicalId' in its state record, so cdkd cannot address it in AWS and did not try to delete it. Repairing the record in state.json and re-running helps; the record is kept.`);
12882
+ logger.info(` ${formatResourceLine("skipped", logicalId, resource.resourceType, `skipped (${skipReason})`)}`);
12883
+ result.skippedCount++;
12884
+ skippedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
12885
+ recordDestroyEvent(ctx.eventRecorder, {
12886
+ eventType: "RESOURCE_SKIPPED",
12887
+ stackName,
12888
+ operation: "DELETE",
12889
+ logicalId,
12890
+ resourceType: resource.resourceType,
12891
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
12892
+ reason: skipReason
12893
+ });
12894
+ return;
12668
12895
  }
12669
- const protectedCount = ctx.removeProtection ? countProtectedResources(state) + countProtectedJournaledOrphans(journaledOrphans, state.region) : 0;
12670
- let binding;
12671
- const stackNoEchoValues = () => {
12672
- if (binding === void 0) {
12673
- let timer;
12674
- const capped = new Promise((resolve) => {
12675
- timer = setTimeout(() => {
12676
- logger.warn(safeMsg`The stack's NoEcho values were not bound within ${NOECHO_PRINTING_BIND_CAP_MS / 1e3}s, ` + "so a resource name taken from one may print unmasked where state holds it in plaintext (state written before schema v11).");
12677
- resolve(void 0);
12678
- }, NOECHO_PRINTING_BIND_CAP_MS);
12679
- timer.unref?.();
12896
+ const baseLabel = `Deleting ${logicalId} (${resource.resourceType})`;
12897
+ renderer.addTask(logicalId, baseLabel);
12898
+ const resourceStartedAt = Date.now();
12899
+ recordDestroyEvent(ctx.eventRecorder, {
12900
+ eventType: "RESOURCE_STARTED",
12901
+ stackName,
12902
+ operation: "DELETE",
12903
+ logicalId,
12904
+ resourceType: resource.resourceType,
12905
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy }
12906
+ });
12907
+ try {
12908
+ let finalSnapshotIdentifier;
12909
+ const policy = effectiveDeletionPolicy(resource.resourceType, resource.deletionPolicy, resource.properties);
12910
+ if (policy === "Snapshot" && ctx.skipFinalSnapshot !== true) {
12911
+ if (ATOMIC_FINAL_SNAPSHOT_TYPES.has(resource.resourceType) && resource.provisionedBy !== "cc-api") finalSnapshotIdentifier = buildFinalSnapshotIdentifier(resource.physicalId, resource.resourceType);
12912
+ else if (ATOMIC_FINAL_SNAPSHOT_TYPES.has(resource.resourceType)) throw ccRoutedFinalSnapshotError(logicalId, resource.resourceType, "--skip-final-snapshot");
12913
+ else if (PRE_DELETE_SNAPSHOT_TYPES.has(resource.resourceType)) await createPreDeleteFinalSnapshot(resource.resourceType, resource.physicalId, logicalId, destroyAwsClients ?? ctx.baseAwsClients, maskedSnapshotLogger(logger, createUnionSecretMasker([printingBagOf(logicalId)])));
12914
+ else throw unsupportedFinalSnapshotError(logicalId, resource.resourceType, "--skip-final-snapshot");
12915
+ }
12916
+ const provider = destroyProviderRegistry.getProviderFor({
12917
+ resourceType: resource.resourceType,
12918
+ provisionedBy: resource.provisionedBy
12919
+ }).provider;
12920
+ const providerMinTimeoutMs = provider.getMinResourceTimeoutMs?.() ?? 0;
12921
+ const warnAfterMs = ctx.resourceWarnAfterByType?.[resource.resourceType] ?? ctx.resourceWarnAfterMs ?? 3e5;
12922
+ const globalTimeoutMs = ctx.resourceTimeoutMs ?? 18e5;
12923
+ const slowTypeMinTimeoutMs = slowCcOperationTimeoutMs(resource.resourceType, "DELETE");
12924
+ const timeoutMs = ctx.resourceTimeoutByType?.[resource.resourceType] ?? Math.max(providerMinTimeoutMs, slowTypeMinTimeoutMs, globalTimeoutMs);
12925
+ let deleteResult;
12926
+ let childLeftInAws = 0;
12927
+ const recordedRegions = secretPrincipalRegions !== void 0 ? recordedReferenceRegions(resource) : void 0;
12928
+ const secretPrincipalOptIn = secretPrincipalRegions !== void 0 ? {
12929
+ importedProducerRegions: secretPrincipalRegions,
12930
+ ...secretPrincipalRegionsIncomplete && { producerRegionsIncomplete: true },
12931
+ retryMemo: { detached: /* @__PURE__ */ new Set() },
12932
+ ...recordedRegions !== void 0 && { recordedRegions }
12933
+ } : void 0;
12934
+ await withResourceDeadline(async () => {
12935
+ const maxAttempts = provider.disableOuterRetry ? 0 : 3;
12936
+ const noEchoDeleteValues = readsNoEchoDeleteValues(resource.resourceType) ? await ctx.noEchoReresolver?.valuesFor(logicalId, resource) : void 0;
12937
+ let lastDeleteError;
12938
+ for (let attempt = 0; attempt <= maxAttempts; attempt++) try {
12939
+ const { value: outcome, unaddressed } = await runDeleteAttempt(attempt >= maxAttempts, () => collectNestedChildUnaddressed(() => withStackRecords(destroyStackRecordsView(state.resources), () => provider.delete(logicalId, resource.physicalId, resource.resourceType, resource.properties, {
12940
+ ...state.region !== void 0 && { expectedRegion: state.region },
12941
+ ...ctx.removeProtection === true && { removeProtection: true },
12942
+ ...finalSnapshotIdentifier !== void 0 && { finalSnapshotIdentifier },
12943
+ deletionPolicy: policy ?? "Delete",
12944
+ ...ctx.skipFinalSnapshot === true && { skipFinalSnapshot: true },
12945
+ ...secretPrincipalOptIn !== void 0 && { resolveSecretDerivedPrincipals: secretPrincipalOptIn },
12946
+ recordedAttributes: resource.attributes,
12947
+ recordedNoEchoLeaves: resource.noEchoLeaves,
12948
+ ...noEchoDeleteValues !== void 0 && { noEchoDeleteValues },
12949
+ ...ctx.noEchoReresolver !== void 0 && { noEchoReresolver: ctx.noEchoReresolver },
12950
+ ...ctx.stackDestroy === true && { stackDestroy: true },
12951
+ maskSecrets: createUnionSecretMasker([printingBagOf(logicalId)])
12952
+ }))));
12953
+ deleteResult = outcome ?? void 0;
12954
+ childLeftInAws = unaddressed?.deleteSkipped ?? 0;
12955
+ lastDeleteError = null;
12956
+ break;
12957
+ } catch (retryError) {
12958
+ lastDeleteError = retryError;
12959
+ const classify = retryClassificationText(retryError);
12960
+ if (!(!isMarkedNonRetryable(retryError) && (isRetryableTransientError(retryError, classify) || classify.includes("Too Many Requests"))) || attempt >= maxAttempts) break;
12961
+ const delay = 5e3 * Math.pow(2, attempt);
12962
+ logger.debug(` ⏳ Retrying delete ${displaySafe(logicalId)} in ${delay / 1e3}s (attempt ${attempt + 1}/${maxAttempts})`);
12963
+ await new Promise((resolve) => setTimeout(resolve, delay));
12964
+ }
12965
+ if (lastDeleteError) throw lastDeleteError;
12966
+ }, {
12967
+ warnAfterMs,
12968
+ timeoutMs,
12969
+ onWarn: (elapsedMs) => {
12970
+ const minutes = Math.max(1, Math.round(elapsedMs / 6e4));
12971
+ renderer.updateTaskLabel(logicalId, `${baseLabel} [taking longer than expected, ${minutes}m+]`);
12972
+ renderer.printAbove(() => {
12973
+ logger.warn(`${displaySafe(logicalId)} (${displaySafe(resource.resourceType)}) has been deleting for ${minutes}m — still waiting`);
12974
+ });
12975
+ },
12976
+ onTimeout: (elapsedMs) => new ResourceTimeoutError(logicalId, resource.resourceType, stackRegion, elapsedMs, "DELETE", timeoutMs)
12977
+ });
12978
+ renderer.removeTask(logicalId);
12979
+ for (const guard of deleteIndeterminateGuards(deleteResult)) {
12980
+ result.guardIndeterminateCount++;
12981
+ guardIndeterminateTargets.add(logicalId);
12982
+ recordDestroyEvent(ctx.eventRecorder, {
12983
+ eventType: "RESOURCE_GUARD_INDETERMINATE",
12984
+ stackName,
12985
+ operation: "DELETE",
12986
+ logicalId,
12987
+ resourceType: resource.resourceType,
12988
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
12989
+ ...resource.physicalId && { physicalId: resource.physicalId },
12990
+ guard: guard.guard,
12991
+ reason: guard.reason
12680
12992
  });
12681
- binding = {
12682
- bound: Promise.resolve().then(() => ctx.noEchoReresolver?.printingNoEchoValues()).catch(() => void 0).finally(() => clearTimeout(timer)),
12683
- capped
12684
- };
12685
12993
  }
12686
- return Promise.race([binding.bound, binding.capped]);
12687
- };
12688
- const orphansAtDestroy = state.orphans ?? [];
12689
- if (orphansAtDestroy.length > 0) {
12690
- logger.info(`\n${orphansAtDestroy.length} resource(s) are still in AWS from an earlier failed deploy. cdkd left them there because their DeletionPolicy is Retain (CDK's RemovalPolicy.RETAIN), and has been tracking them so a later deploy of this stack could adopt them back instead of colliding with their names.`);
12691
- logger.info("Destroying this stack deletes that record. The resources stay in AWS, may continue to incur charges, and cdkd will no longer know about them:");
12692
- const orphanListing = orphanRecordsPrintingBag(orphansAtDestroy, await stackNoEchoValues());
12693
- for (const entry of orphansAtDestroy) withPrintingSecrets(orphanListing, () => logger.info(` - ${displaySafe(entry.logicalId)} (${displaySafe(entry.state.resourceType)}) ${displaySafe(entry.state.physicalId)}`));
12694
- }
12695
- if (journaledOrphans.count > 0) {
12696
- logger.info(`\n${journaledOrphans.count} resource(s) were created by a failed deploy and are recorded only in the rollback journal. Each is deleted first as its DeletionPolicy directs (Retain keeps it in AWS, Snapshot takes the final snapshot), unless state or a later deploy may own it, which is warned about instead:`);
12697
- const listing = journaledOrphanPrintingBag(journaledOrphans.segments.flatMap(({ ops }) => ops), state.resources, await stackNoEchoValues());
12698
- withPrintingSecrets(listing, () => {
12699
- for (const line of journaledOrphanLines(journaledOrphans, logger)) logger.info(line);
12994
+ if (deleteResult?.outcome === "skipped") {
12995
+ const skipReason = deleteSkipReason(deleteResult) ?? "no reason reported by the provider";
12996
+ logger.info(` ${formatResourceLine("skipped", logicalId, resource.resourceType, `skipped (${skipReason})`)}`);
12997
+ result.skippedCount++;
12998
+ skippedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
12999
+ recordDestroyEvent(ctx.eventRecorder, {
13000
+ eventType: "RESOURCE_SKIPPED",
13001
+ stackName,
13002
+ operation: "DELETE",
13003
+ logicalId,
13004
+ resourceType: resource.resourceType,
13005
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13006
+ ...resource.physicalId && { physicalId: resource.physicalId },
13007
+ reason: skipReason,
13008
+ durationMs: Date.now() - resourceStartedAt
13009
+ });
13010
+ return;
13011
+ }
13012
+ const leftInAws = childLeftInAws > 0 ? deleteLeftInPlace(deleteResult) ?? `${childLeftInAws} resource(s) a failed deploy created were left in AWS` : void 0;
13013
+ const deletedLine = leftInAws !== void 0 ? formatResourceLine("skipped", logicalId, resource.resourceType, `deleted (${leftInAws})`) : formatResourceLine("deleted", logicalId, resource.resourceType);
13014
+ logger.info(` ${deletedLine}`);
13015
+ result.skippedCount += childLeftInAws;
13016
+ result.journaledOrphanSkips += childLeftInAws;
13017
+ result.deletedCount++;
13018
+ recordDestroyEvent(ctx.eventRecorder, {
13019
+ eventType: "RESOURCE_SUCCEEDED",
13020
+ stackName,
13021
+ operation: "DELETE",
13022
+ logicalId,
13023
+ resourceType: resource.resourceType,
13024
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13025
+ ...resource.physicalId && { physicalId: resource.physicalId },
13026
+ durationMs: Date.now() - resourceStartedAt
12700
13027
  });
12701
- }
12702
- if (!ctx.skipConfirmation) {
12703
- if (process.stdin.isTTY !== true) throw new CdkdError(`The destroy confirmation prompt for stack ${displayStackName(stackName)} cannot run in a non-interactive environment. Pass --yes / -y to confirm the destroy (cdkd destroy also accepts -f / --force), or run the command from a real terminal.`, "NON_INTERACTIVE_CONFIRM");
12704
- const rl = readline$1.createInterface({
12705
- input: process.stdin,
12706
- output: process.stdout
13028
+ if (leftInAws !== void 0) recordDestroyEvent(ctx.eventRecorder, {
13029
+ eventType: "RESOURCE_SKIPPED",
13030
+ stackName,
13031
+ operation: "DELETE",
13032
+ logicalId,
13033
+ resourceType: resource.resourceType,
13034
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13035
+ reason: leftInAws,
13036
+ durationMs: Date.now() - resourceStartedAt
12707
13037
  });
12708
- const journaledClause = journaledOrphans.count > 0 ? ` and ${journaledOrphans.count} recorded only in its rollback journal` : "";
12709
- const prompt = ctx.removeProtection ? `\nAbout to destroy ${resourceCount} resources${journaledClause} from stack ${displayStackName(stackName)}, REMOVING DELETION PROTECTION on ${protectedCount} of them. Continue? (y/N): ` : `\nAre you sure you want to destroy stack ${displayStackName(stackName)} and delete all ${resourceCount} resources${journaledClause}? (Y/n): `;
12710
- const answer = await rl.question(prompt);
12711
- rl.close();
12712
- const trimmed = answer.trim().toLowerCase();
12713
- if (ctx.removeProtection) {
12714
- if (trimmed !== "y" && trimmed !== "yes") {
12715
- logger.info("Destroy cancelled");
12716
- result.cancelled = true;
12717
- return result;
12718
- }
12719
- } else if (trimmed === "n" || trimmed === "no") {
12720
- logger.info("Destroy cancelled");
12721
- result.cancelled = true;
12722
- return result;
13038
+ delete remainingResources[logicalId];
13039
+ persistStateAfterDelete(logicalId);
13040
+ } catch (error) {
13041
+ renderer.removeTask(logicalId);
13042
+ const msg = describeAwsFailure(error).detail;
13043
+ if (!isInterruptedWaitError(error) && !isFinalSnapshotError(error) && !isMarkedNonRetryable(error) && !isWaitAbandonedError(error) && !isMarkedNotGone(error) && (msg.includes("does not exist") || msg.includes("not found") || msg.includes("No policy found") || msg.includes("NoSuchEntity") || msg.includes("NotFoundException"))) {
13044
+ logger.debug(` ${displaySafe(logicalId)} already deleted, removing from state`);
13045
+ result.deletedCount++;
13046
+ recordDestroyEvent(ctx.eventRecorder, {
13047
+ eventType: "RESOURCE_SUCCEEDED",
13048
+ stackName,
13049
+ operation: "DELETE",
13050
+ logicalId,
13051
+ resourceType: resource.resourceType,
13052
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13053
+ ...resource.physicalId && { physicalId: resource.physicalId },
13054
+ durationMs: Date.now() - resourceStartedAt
13055
+ });
13056
+ delete remainingResources[logicalId];
13057
+ persistStateAfterDelete(logicalId);
13058
+ } else if (error instanceof ResourceTimeoutError) {
13059
+ const wrapped = new ProvisioningError(error.message, resource.resourceType, logicalId, resource.physicalId, error);
13060
+ logger.error(` ✗ Failed to delete ${displaySafe(logicalId)}:`, wrapped.message);
13061
+ result.errorCount++;
13062
+ failedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
13063
+ blockDependenciesOf(logicalId);
13064
+ recordDestroyEvent(ctx.eventRecorder, {
13065
+ eventType: "RESOURCE_FAILED",
13066
+ stackName,
13067
+ operation: "DELETE",
13068
+ logicalId,
13069
+ resourceType: resource.resourceType,
13070
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13071
+ durationMs: Date.now() - resourceStartedAt,
13072
+ error: extractDeploymentEventError(wrapped)
13073
+ });
13074
+ } else {
13075
+ logger.error(` ✗ Failed to delete ${displaySafe(logicalId)}:`, safeStringify(error));
13076
+ result.errorCount++;
13077
+ failedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
13078
+ blockDependenciesOf(logicalId);
13079
+ recordDestroyEvent(ctx.eventRecorder, {
13080
+ eventType: "RESOURCE_FAILED",
13081
+ stackName,
13082
+ operation: "DELETE",
13083
+ logicalId,
13084
+ resourceType: resource.resourceType,
13085
+ ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13086
+ durationMs: Date.now() - resourceStartedAt,
13087
+ error: extractDeploymentEventError(error)
13088
+ });
12723
13089
  }
13090
+ } finally {
13091
+ renderer.removeTask(logicalId);
12724
13092
  }
12725
- const stackRegion = state.region;
12726
- let destroyProviderRegistry = ctx.providerRegistry;
12727
- let destroyAwsClients;
12728
- let regionSwitched = false;
12729
- const restoreBaseRegionAndClients = () => {
12730
- if (!regionSwitched) return;
12731
- regionSwitched = false;
12732
- destroyAwsClients = void 0;
12733
- process.env["AWS_REGION"] = ctx.baseRegion;
12734
- process.env["AWS_DEFAULT_REGION"] = ctx.baseRegion;
12735
- setAwsClients(ctx.baseAwsClients);
12736
- };
12737
- if (stackScope !== void 0 && stackRegion) {
12738
- logger.info(`Stack region: ${displaySafe(stackRegion, { asciiOnly: true })}`);
12739
- process.env["AWS_REGION"] = stackRegion;
12740
- process.env["AWS_DEFAULT_REGION"] = stackRegion;
12741
- regionSwitched = true;
12742
- try {
12743
- destroyAwsClients = stackScope.clients;
12744
- setAwsClients(destroyAwsClients);
12745
- destroyProviderRegistry = stackScope.registry;
12746
- registerAllProviders(destroyProviderRegistry, providerClasses);
12747
- destroyProviderRegistry.setCustomResourceResponseBucket(ctx.stateBucket);
12748
- if (ctx.allowUnsupportedTypes?.length) destroyProviderRegistry.allowUnsupportedTypes(ctx.allowUnsupportedTypes);
12749
- } catch (setupError) {
12750
- restoreBaseRegionAndClients();
12751
- throw setupError;
13093
+ }
13094
+
13095
+ // src/cli/commands/destroy-runner/under-lock.ts
13096
+ async function destroyStackUnderLock({ stackName, state, ctx, logger, result, regionForState, refusalRecovery, stackLockBase, journaledOrphans, needsStrongRefCheck, stackNoEchoValues, destroyProviderRegistry, destroyAwsClients, restoreBaseRegionAndClients }) {
13097
+ const retainedForReadoption = [];
13098
+ let retainedEarlier;
13099
+ const guardIndeterminateTargets = /* @__PURE__ */ new Set();
13100
+ const startRetainedEarlierRead = () => {
13101
+ if (retainedEarlier === void 0) {
13102
+ retainedEarlier = Promise.resolve().then(() => ctx.stateBackend.loadRetainedRecord(stackName, regionForState));
13103
+ retainedEarlier.catch(() => void 0);
12752
13104
  }
12753
- }
13105
+ };
12754
13106
  const renderer = getLiveRenderer();
12755
13107
  let statePreserved = false;
12756
13108
  let heldTail;
@@ -12769,61 +13121,22 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
12769
13121
  },
12770
13122
  onAcquireFailure: restoreBaseRegionAndClients
12771
13123
  });
12772
- try {
12773
- const [current, marker] = await Promise.all([ctx.stateBackend.getState(stackName, regionForState), readRefactorMarker(ctx.stateBackend)]);
12774
- if (current === null || !holdsSameResourcesAs(state, current.state)) throw new CdkdError(safeMsg`cdkd destroy refused stack ${stackName} (${regionForState}): its state ` + "changed after it was read (another command wrote it while this one waited for confirmation), so nothing was deleted. Re-run cdkd destroy.", "STATE_CHANGED");
12775
- if (current.state.terminationProtection === true && ctx.removeProtection !== true) throw new StackTerminationProtectionError(stackName, void 0, {
12776
- args: accountArgs(refusalRecovery),
12777
- clause: withheldAccountClause(refusalRecovery, "the command below prints")
12778
- }, {
12779
- command: ctx.stateDestroy === true ? "cdkd state destroy" : "cdkd destroy",
12780
- stackRegion: regionForState
12781
- });
12782
- refusePendingMovesOut(current.state, stackName, regionForState, "cdkd destroy");
12783
- refuseRefactorMarker(marker, stackName, regionForState, "cdkd destroy");
12784
- } catch (error) {
12785
- await lock.release({ failureMessage: "Failed to release lock after a state re-check refusal" });
12786
- restoreBaseRegionAndClients();
12787
- throw error;
12788
- }
12789
- if (needsStrongRefCheck) {
12790
- const releaseThenUnregister = async () => {
12791
- await lock.release({ failureMessage: "Failed to release lock after strong-ref refusal/failure" });
12792
- restoreBaseRegionAndClients();
12793
- };
12794
- let consumers;
12795
- try {
12796
- consumers = await scanActiveConsumers(stackName, regionForState, ctx);
12797
- } catch (error) {
12798
- await releaseThenUnregister();
12799
- throw error;
12800
- }
12801
- if (consumers.length > 0) {
12802
- await releaseThenUnregister();
12803
- throw new StackHasActiveImportsError(stackName, regionForState, consumers);
12804
- }
12805
- }
13124
+ await recheckUnderLock({
13125
+ ctx,
13126
+ stackName,
13127
+ state,
13128
+ regionForState,
13129
+ refusalRecovery,
13130
+ lock,
13131
+ restoreBaseRegionAndClients,
13132
+ needsStrongRefCheck
13133
+ });
12806
13134
  const remainingResources = { ...state.resources };
12807
13135
  let remainingSuperseded = state.supersededResources;
12808
- const stateTargetFor = (logicalId, resourceType) => resourceType === NESTED_STACK_TYPE ? `${stackName}~${logicalId}` : stackName;
13136
+ const stateTargetFor = (logicalId, resourceType) => resourceType === "AWS::CloudFormation::Stack" ? `${stackName}~${logicalId}` : stackName;
12809
13137
  const skippedStateTargets = /* @__PURE__ */ new Set();
12810
13138
  const failedStateTargets = /* @__PURE__ */ new Set();
12811
- const hintCommand = (command, t) => pasteableCommand(command, [
12812
- {
12813
- value: t,
12814
- hole: "stack",
12815
- opts: { plainIdent: true }
12816
- },
12817
- {
12818
- flag: "--stack-region",
12819
- value: regionForState,
12820
- hole: "region",
12821
- opts: { plainIdent: true }
12822
- },
12823
- ...accountArgs(refusalRecovery)
12824
- ]);
12825
- const hintFor = (command, targets, label) => [...new Set(targets.map((t) => `\n${label}: ${hintCommand(command, t).command}`))].join("");
12826
- const hintHolesClause = (targets) => (targets.every((t) => hintCommand("cdkd state show", t).withheld.every((w) => w.hole !== "stack" && w.hole !== "region")) ? "" : " A target that is not a plain identifier is printed as a quoted '<stack>' or '<region>' placeholder; list the records as stored with 'cdkd state list --long'.") + (targets.length === 0 ? "" : ((clause) => clause === "" ? "" : ` ${clause}`)(withheldAccountClause(refusalRecovery, "the command lines below print").trimEnd()));
13139
+ const { hintFor, hintHolesClause } = makeSummaryHints(regionForState, refusalRecovery);
12827
13140
  let secretPrincipalRegions;
12828
13141
  let secretPrincipalRegionsIncomplete = false;
12829
13142
  const buildDestroySnapshot = () => {
@@ -12860,10 +13173,14 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
12860
13173
  if (secretPrincipalRegionsIncomplete && Object.values(state.resources ?? {}).some((r) => holdsUnprovenSecretPrincipalRecord(r))) logger.warn(safeMsg`${stackName}: this nested child is destroyed without its parent stack, so the regions its parent reads from are unknown: a secret-derived principal record whose reference has no recorded region is skipped. To resolve it, destroy it through its parent stack (the top-level stack that holds it).`);
12861
13174
  renderer.start();
12862
13175
  stackNoEchoValues();
12863
- const journaledUnderLock = await loadJournaledOrphans(ctx.stateBackend, stackName, regionForState, state.orphans, journaledOrphans.unreadable === true ? { warn: () => void 0 } : logger);
12864
- if (journaledUnderLock.unreadable === true && journaledOrphans.unreadable !== true) throw new Error(`The rollback journal of stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) was readable when this run started and cannot be read now (see the warning above). Nothing was deleted; re-run the destroy once it can be read.`);
12865
- refuseNewPendingRequests(journaledUnderLock, stackName, regionForState);
12866
- if (!sameJournaledOrphans(journaledUnderLock, journaledOrphans)) throw new Error(`The rollback journal of stack ${displayStackName(stackName)} (${displaySafe(regionForState, { asciiOnly: true })}) recorded ${journaledOrphans.count} resource(s) a failed deploy created when this run started and ${journaledUnderLock.count} now, not the same ones — another cdkd process wrote to it. Nothing was deleted; re-run the destroy to act on the current journal.`);
13176
+ const journaledUnderLock = await reReadJournaledOrphansUnderLock({
13177
+ ctx,
13178
+ stackName,
13179
+ regionForState,
13180
+ state,
13181
+ journaledOrphans,
13182
+ logger
13183
+ });
12867
13184
  const noEchoValues = await stackNoEchoValues();
12868
13185
  if (journaledUnderLock.count > 0) {
12869
13186
  const orphanOutcome = await deleteJournaledOrphans(journaledUnderLock, { ...state.resources }, stackName, stackInstanceIdOf(state, displayStackName(stackName)), {
@@ -12895,83 +13212,44 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
12895
13212
  logger.warn(safeMsg`Failed to strip the deleted journal entries (a re-run repeats their deletes): ${describeAwsFailure(stripError).detail}`);
12896
13213
  }
12897
13214
  }
12898
- logger.info("Building dependency graph...");
12899
- const template = {
12900
- AWSTemplateFormatVersion: "2010-09-09",
12901
- Resources: {}
12902
- };
12903
- for (const [logicalId, resource] of Object.entries(state.resources)) template.Resources[logicalId] = {
12904
- Type: resource.resourceType,
12905
- Properties: resource.properties || {},
12906
- ...resource.dependencies && resource.dependencies.length > 0 && { DependsOn: resource.dependencies }
12907
- };
12908
- const blockingResources = { ...template.Resources };
12909
- const typeToLogicalIds = /* @__PURE__ */ new Map();
12910
- for (const [logicalId, resource] of Object.entries(state.resources)) {
12911
- const ids = typeToLogicalIds.get(resource.resourceType) ?? [];
12912
- ids.push(logicalId);
12913
- typeToLogicalIds.set(resource.resourceType, ids);
12914
- }
12915
- for (const [logicalId, resource] of Object.entries(state.resources)) {
12916
- const mustDeleteAfter = IMPLICIT_DELETE_DEPENDENCIES[resource.resourceType];
12917
- if (!mustDeleteAfter) continue;
12918
- for (const depType of mustDeleteAfter) {
12919
- const depIds = typeToLogicalIds.get(depType);
12920
- if (!depIds) continue;
12921
- for (const depId of depIds) {
12922
- const existing = template.Resources[depId]?.DependsOn ?? [];
12923
- const depsArray = Array.isArray(existing) ? existing : [existing];
12924
- if (!depsArray.includes(logicalId)) {
12925
- template.Resources[depId] = {
12926
- ...template.Resources[depId],
12927
- DependsOn: [...depsArray, logicalId]
12928
- };
12929
- logger.debug(`Implicit delete dependency: ${displaySafe(depId)} (${displaySafe(depType)}) must be deleted before ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)})`);
12930
- }
12931
- }
12932
- }
12933
- }
12934
- for (const { before, after } of computeImplicitDeleteEdges(state.resources)) {
12935
- const blocking = blockingResources[before]?.DependsOn ?? [];
12936
- const blockingArray = Array.isArray(blocking) ? blocking : [blocking];
12937
- if (!blockingArray.includes(after)) blockingResources[before] = {
12938
- ...blockingResources[before],
12939
- DependsOn: [...blockingArray, after]
12940
- };
12941
- const existing = template.Resources[before]?.DependsOn ?? [];
12942
- const depsArray = Array.isArray(existing) ? existing : [existing];
12943
- if (!depsArray.includes(after)) {
12944
- template.Resources[before] = {
12945
- ...template.Resources[before],
12946
- DependsOn: [...depsArray, after]
12947
- };
12948
- logger.debug(`Implicit delete dependency: ${displaySafe(before)} (${displaySafe(state.resources[before]?.resourceType)}) must be deleted before ${displaySafe(after)} (${displaySafe(state.resources[after]?.resourceType)})`);
12949
- }
12950
- }
12951
- const dagBuilder = new DagBuilder();
12952
- const graph = dagBuilder.buildGraph(template);
12953
- const blockingGraph = dagBuilder.buildGraph({
12954
- ...template,
12955
- Resources: blockingResources
12956
- });
12957
- const executionLevels = dagBuilder.getExecutionLevels(graph);
12958
- logger.debug(`Dependency graph: ${executionLevels.length} level(s)`);
13215
+ const { dagBuilder, blockingGraph, executionLevels } = buildDeleteGraph(state, logger);
12959
13216
  const blockedBy = /* @__PURE__ */ new Map();
12960
13217
  const blockedIds = [];
12961
13218
  const blockDependenciesOf = (logicalId) => {
12962
13219
  for (const dependency of dagBuilder.getAllDependencies(blockingGraph, logicalId)) if (!blockedBy.has(dependency)) blockedBy.set(dependency, logicalId);
12963
13220
  };
12964
- const reresolver = ctx.noEchoReresolver;
12965
- const judgedBagOf = secretNamePrintingBags(state.resources, reresolver === void 0 ? noEchoValues : namingSecretsWithRecordedNoEcho(noEchoValues, (logicalId) => {
12966
- try {
12967
- return reresolver.recordedNoEchoValuesFor(logicalId, Object.hasOwn(state.resources, logicalId) ? state.resources[logicalId] : void 0);
12968
- } catch (error) {
12969
- logger.debug(safeMsg`Could not read ${logicalId}'s stored NoEcho values for its printing bag (${error instanceof Error ? error.name : typeof error}).`);
12970
- return;
12971
- }
12972
- }));
12973
- const namingScope = nameScopeOf(stackName, stackInstanceIdOf(state, displayStackName(stackName)), state);
12974
- const printingBagOf = (logicalId) => withStackScope(namingScope, () => judgedBagOf(logicalId));
13221
+ const printingBagOf = makePrintingBagOf({
13222
+ ctx,
13223
+ state,
13224
+ noEchoValues,
13225
+ stackName,
13226
+ logger
13227
+ });
13228
+ const resourceFrame = {
13229
+ lock,
13230
+ state,
13231
+ ctx,
13232
+ stackName,
13233
+ logger,
13234
+ result,
13235
+ renderer,
13236
+ blockedBy,
13237
+ blockedIds,
13238
+ blockDependenciesOf,
13239
+ retainedForReadoption,
13240
+ startRetainedEarlierRead,
13241
+ skippedStateTargets,
13242
+ failedStateTargets,
13243
+ stateTargetFor,
13244
+ guardIndeterminateTargets,
13245
+ remainingResources,
13246
+ persistStateAfterDelete,
13247
+ printingBagOf,
13248
+ destroyProviderRegistry,
13249
+ destroyAwsClients,
13250
+ secretPrincipalRegions,
13251
+ secretPrincipalRegionsIncomplete
13252
+ };
12975
13253
  for (let levelIndex = executionLevels.length - 1; levelIndex >= 0; levelIndex--) {
12976
13254
  if (lock.interrupted) {
12977
13255
  logger.debug("Interrupted (draining) — not scheduling further deletion levels");
@@ -12981,270 +13259,7 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
12981
13259
  if (!level) continue;
12982
13260
  logger.debug(`Deletion level ${executionLevels.length - levelIndex}/${executionLevels.length} (${level.length} resources)`);
12983
13261
  const stackRegion = state.region ?? ctx.baseRegion;
12984
- const deletePromises = level.map((logicalId) => withPrintingSecrets(printingBagOf(logicalId), async () => {
12985
- if (lock.interrupted) return;
12986
- const resource = state.resources[logicalId];
12987
- if (!resource) {
12988
- logger.warn(`Resource ${displaySafe(logicalId)} not found in state, skipping`);
12989
- return;
12990
- }
12991
- const blocker = blockedBy.get(logicalId);
12992
- if (blocker !== void 0) {
12993
- const blockReason = `${blocker} depends on it and its delete failed`;
12994
- logger.info(safeMsg` ${formatResourceLine("skipped", logicalId, resource.resourceType, `not deleted (${blockReason})`)}`);
12995
- result.blockedCount++;
12996
- blockedIds.push(logicalId);
12997
- recordDestroyEvent(ctx.eventRecorder, {
12998
- eventType: "RESOURCE_SKIPPED",
12999
- stackName,
13000
- operation: "DELETE",
13001
- logicalId,
13002
- resourceType: resource.resourceType,
13003
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13004
- ...resource.physicalId && { physicalId: resource.physicalId },
13005
- reason: blockReason
13006
- });
13007
- return;
13008
- }
13009
- if (shouldRetainResource(resource.deletionPolicy)) {
13010
- logger.info(` ⊘ ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)}) retained — DeletionPolicy: ${displaySafe(resource.deletionPolicy)}`);
13011
- result.retainedCount++;
13012
- if (keptForRetainedRecord(resource)) {
13013
- retainedForReadoption.push({
13014
- logicalId,
13015
- resourceType: resource.resourceType,
13016
- physicalId: resource.physicalId
13017
- });
13018
- if (retainedEarlier === void 0) {
13019
- retainedEarlier = Promise.resolve().then(() => ctx.stateBackend.loadRetainedRecord(stackName, regionForState));
13020
- retainedEarlier.catch(() => void 0);
13021
- }
13022
- }
13023
- recordDestroyEvent(ctx.eventRecorder, {
13024
- eventType: "RESOURCE_RETAINED",
13025
- stackName,
13026
- operation: "DELETE",
13027
- logicalId,
13028
- resourceType: resource.resourceType,
13029
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy }
13030
- });
13031
- return;
13032
- }
13033
- if (resource.resourceType !== NESTED_STACK_TYPE && (typeof resource.physicalId !== "string" || resource.physicalId.trim() === "")) {
13034
- const skipReason = "state record has no physical id";
13035
- logger.warn(`Resource ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)}) has no non-empty string 'physicalId' in its state record, so cdkd cannot address it in AWS and did not try to delete it. Repairing the record in state.json and re-running helps; the record is kept.`);
13036
- logger.info(` ${formatResourceLine("skipped", logicalId, resource.resourceType, `skipped (${skipReason})`)}`);
13037
- result.skippedCount++;
13038
- skippedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
13039
- recordDestroyEvent(ctx.eventRecorder, {
13040
- eventType: "RESOURCE_SKIPPED",
13041
- stackName,
13042
- operation: "DELETE",
13043
- logicalId,
13044
- resourceType: resource.resourceType,
13045
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13046
- reason: skipReason
13047
- });
13048
- return;
13049
- }
13050
- const baseLabel = `Deleting ${logicalId} (${resource.resourceType})`;
13051
- renderer.addTask(logicalId, baseLabel);
13052
- const resourceStartedAt = Date.now();
13053
- recordDestroyEvent(ctx.eventRecorder, {
13054
- eventType: "RESOURCE_STARTED",
13055
- stackName,
13056
- operation: "DELETE",
13057
- logicalId,
13058
- resourceType: resource.resourceType,
13059
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy }
13060
- });
13061
- try {
13062
- let finalSnapshotIdentifier;
13063
- const policy = effectiveDeletionPolicy(resource.resourceType, resource.deletionPolicy, resource.properties);
13064
- if (policy === "Snapshot" && ctx.skipFinalSnapshot !== true) {
13065
- if (ATOMIC_FINAL_SNAPSHOT_TYPES.has(resource.resourceType) && resource.provisionedBy !== "cc-api") finalSnapshotIdentifier = buildFinalSnapshotIdentifier(resource.physicalId, resource.resourceType);
13066
- else if (ATOMIC_FINAL_SNAPSHOT_TYPES.has(resource.resourceType)) throw ccRoutedFinalSnapshotError(logicalId, resource.resourceType, "--skip-final-snapshot");
13067
- else if (PRE_DELETE_SNAPSHOT_TYPES.has(resource.resourceType)) await createPreDeleteFinalSnapshot(resource.resourceType, resource.physicalId, logicalId, destroyAwsClients ?? ctx.baseAwsClients, maskedSnapshotLogger(logger, createUnionSecretMasker([printingBagOf(logicalId)])));
13068
- else throw unsupportedFinalSnapshotError(logicalId, resource.resourceType, "--skip-final-snapshot");
13069
- }
13070
- const provider = destroyProviderRegistry.getProviderFor({
13071
- resourceType: resource.resourceType,
13072
- provisionedBy: resource.provisionedBy
13073
- }).provider;
13074
- const providerMinTimeoutMs = provider.getMinResourceTimeoutMs?.() ?? 0;
13075
- const warnAfterMs = ctx.resourceWarnAfterByType?.[resource.resourceType] ?? ctx.resourceWarnAfterMs ?? 3e5;
13076
- const globalTimeoutMs = ctx.resourceTimeoutMs ?? 18e5;
13077
- const slowTypeMinTimeoutMs = slowCcOperationTimeoutMs(resource.resourceType, "DELETE");
13078
- const timeoutMs = ctx.resourceTimeoutByType?.[resource.resourceType] ?? Math.max(providerMinTimeoutMs, slowTypeMinTimeoutMs, globalTimeoutMs);
13079
- let deleteResult;
13080
- let childLeftInAws = 0;
13081
- const recordedRegions = secretPrincipalRegions !== void 0 ? recordedReferenceRegions(resource) : void 0;
13082
- const secretPrincipalOptIn = secretPrincipalRegions !== void 0 ? {
13083
- importedProducerRegions: secretPrincipalRegions,
13084
- ...secretPrincipalRegionsIncomplete && { producerRegionsIncomplete: true },
13085
- retryMemo: { detached: /* @__PURE__ */ new Set() },
13086
- ...recordedRegions !== void 0 && { recordedRegions }
13087
- } : void 0;
13088
- await withResourceDeadline(async () => {
13089
- const maxAttempts = provider.disableOuterRetry ? 0 : 3;
13090
- const noEchoDeleteValues = readsNoEchoDeleteValues(resource.resourceType) ? await ctx.noEchoReresolver?.valuesFor(logicalId, resource) : void 0;
13091
- let lastDeleteError;
13092
- for (let attempt = 0; attempt <= maxAttempts; attempt++) try {
13093
- const { value: outcome, unaddressed } = await runDeleteAttempt(attempt >= maxAttempts, () => collectNestedChildUnaddressed(() => withStackRecords(destroyStackRecordsView(state.resources), () => provider.delete(logicalId, resource.physicalId, resource.resourceType, resource.properties, {
13094
- ...state.region !== void 0 && { expectedRegion: state.region },
13095
- ...ctx.removeProtection === true && { removeProtection: true },
13096
- ...finalSnapshotIdentifier !== void 0 && { finalSnapshotIdentifier },
13097
- deletionPolicy: policy ?? "Delete",
13098
- ...ctx.skipFinalSnapshot === true && { skipFinalSnapshot: true },
13099
- ...secretPrincipalOptIn !== void 0 && { resolveSecretDerivedPrincipals: secretPrincipalOptIn },
13100
- recordedAttributes: resource.attributes,
13101
- recordedNoEchoLeaves: resource.noEchoLeaves,
13102
- ...noEchoDeleteValues !== void 0 && { noEchoDeleteValues },
13103
- ...ctx.noEchoReresolver !== void 0 && { noEchoReresolver: ctx.noEchoReresolver },
13104
- ...ctx.stackDestroy === true && { stackDestroy: true },
13105
- maskSecrets: createUnionSecretMasker([printingBagOf(logicalId)])
13106
- }))));
13107
- deleteResult = outcome ?? void 0;
13108
- childLeftInAws = unaddressed?.deleteSkipped ?? 0;
13109
- lastDeleteError = null;
13110
- break;
13111
- } catch (retryError) {
13112
- lastDeleteError = retryError;
13113
- const classify = retryClassificationText(retryError);
13114
- if (!(!isMarkedNonRetryable(retryError) && (isRetryableTransientError(retryError, classify) || classify.includes("Too Many Requests"))) || attempt >= maxAttempts) break;
13115
- const delay = 5e3 * Math.pow(2, attempt);
13116
- logger.debug(` ⏳ Retrying delete ${displaySafe(logicalId)} in ${delay / 1e3}s (attempt ${attempt + 1}/${maxAttempts})`);
13117
- await new Promise((resolve) => setTimeout(resolve, delay));
13118
- }
13119
- if (lastDeleteError) throw lastDeleteError;
13120
- }, {
13121
- warnAfterMs,
13122
- timeoutMs,
13123
- onWarn: (elapsedMs) => {
13124
- const minutes = Math.max(1, Math.round(elapsedMs / 6e4));
13125
- renderer.updateTaskLabel(logicalId, `${baseLabel} [taking longer than expected, ${minutes}m+]`);
13126
- renderer.printAbove(() => {
13127
- logger.warn(`${displaySafe(logicalId)} (${displaySafe(resource.resourceType)}) has been deleting for ${minutes}m — still waiting`);
13128
- });
13129
- },
13130
- onTimeout: (elapsedMs) => new ResourceTimeoutError(logicalId, resource.resourceType, stackRegion, elapsedMs, "DELETE", timeoutMs)
13131
- });
13132
- renderer.removeTask(logicalId);
13133
- for (const guard of deleteIndeterminateGuards(deleteResult)) {
13134
- result.guardIndeterminateCount++;
13135
- guardIndeterminateTargets.add(logicalId);
13136
- recordDestroyEvent(ctx.eventRecorder, {
13137
- eventType: "RESOURCE_GUARD_INDETERMINATE",
13138
- stackName,
13139
- operation: "DELETE",
13140
- logicalId,
13141
- resourceType: resource.resourceType,
13142
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13143
- ...resource.physicalId && { physicalId: resource.physicalId },
13144
- guard: guard.guard,
13145
- reason: guard.reason
13146
- });
13147
- }
13148
- if (deleteResult?.outcome === "skipped") {
13149
- const skipReason = deleteSkipReason(deleteResult) ?? "no reason reported by the provider";
13150
- logger.info(` ${formatResourceLine("skipped", logicalId, resource.resourceType, `skipped (${skipReason})`)}`);
13151
- result.skippedCount++;
13152
- skippedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
13153
- recordDestroyEvent(ctx.eventRecorder, {
13154
- eventType: "RESOURCE_SKIPPED",
13155
- stackName,
13156
- operation: "DELETE",
13157
- logicalId,
13158
- resourceType: resource.resourceType,
13159
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13160
- ...resource.physicalId && { physicalId: resource.physicalId },
13161
- reason: skipReason,
13162
- durationMs: Date.now() - resourceStartedAt
13163
- });
13164
- return;
13165
- }
13166
- const leftInAws = childLeftInAws > 0 ? deleteLeftInPlace(deleteResult) ?? `${childLeftInAws} resource(s) a failed deploy created were left in AWS` : void 0;
13167
- const deletedLine = leftInAws !== void 0 ? formatResourceLine("skipped", logicalId, resource.resourceType, `deleted (${leftInAws})`) : formatResourceLine("deleted", logicalId, resource.resourceType);
13168
- logger.info(` ${deletedLine}`);
13169
- result.skippedCount += childLeftInAws;
13170
- result.journaledOrphanSkips += childLeftInAws;
13171
- result.deletedCount++;
13172
- recordDestroyEvent(ctx.eventRecorder, {
13173
- eventType: "RESOURCE_SUCCEEDED",
13174
- stackName,
13175
- operation: "DELETE",
13176
- logicalId,
13177
- resourceType: resource.resourceType,
13178
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13179
- ...resource.physicalId && { physicalId: resource.physicalId },
13180
- durationMs: Date.now() - resourceStartedAt
13181
- });
13182
- if (leftInAws !== void 0) recordDestroyEvent(ctx.eventRecorder, {
13183
- eventType: "RESOURCE_SKIPPED",
13184
- stackName,
13185
- operation: "DELETE",
13186
- logicalId,
13187
- resourceType: resource.resourceType,
13188
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13189
- reason: leftInAws,
13190
- durationMs: Date.now() - resourceStartedAt
13191
- });
13192
- delete remainingResources[logicalId];
13193
- persistStateAfterDelete(logicalId);
13194
- } catch (error) {
13195
- renderer.removeTask(logicalId);
13196
- const msg = describeAwsFailure(error).detail;
13197
- if (!isInterruptedWaitError(error) && !isFinalSnapshotError(error) && !isMarkedNonRetryable(error) && !isWaitAbandonedError(error) && !isMarkedNotGone(error) && (msg.includes("does not exist") || msg.includes("not found") || msg.includes("No policy found") || msg.includes("NoSuchEntity") || msg.includes("NotFoundException"))) {
13198
- logger.debug(` ${displaySafe(logicalId)} already deleted, removing from state`);
13199
- result.deletedCount++;
13200
- recordDestroyEvent(ctx.eventRecorder, {
13201
- eventType: "RESOURCE_SUCCEEDED",
13202
- stackName,
13203
- operation: "DELETE",
13204
- logicalId,
13205
- resourceType: resource.resourceType,
13206
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13207
- ...resource.physicalId && { physicalId: resource.physicalId },
13208
- durationMs: Date.now() - resourceStartedAt
13209
- });
13210
- delete remainingResources[logicalId];
13211
- persistStateAfterDelete(logicalId);
13212
- } else if (error instanceof ResourceTimeoutError) {
13213
- const wrapped = new ProvisioningError(error.message, resource.resourceType, logicalId, resource.physicalId, error);
13214
- logger.error(` ✗ Failed to delete ${displaySafe(logicalId)}:`, wrapped.message);
13215
- result.errorCount++;
13216
- failedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
13217
- blockDependenciesOf(logicalId);
13218
- recordDestroyEvent(ctx.eventRecorder, {
13219
- eventType: "RESOURCE_FAILED",
13220
- stackName,
13221
- operation: "DELETE",
13222
- logicalId,
13223
- resourceType: resource.resourceType,
13224
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13225
- durationMs: Date.now() - resourceStartedAt,
13226
- error: extractDeploymentEventError(wrapped)
13227
- });
13228
- } else {
13229
- logger.error(` ✗ Failed to delete ${displaySafe(logicalId)}:`, safeStringify(error));
13230
- result.errorCount++;
13231
- failedStateTargets.add(stateTargetFor(logicalId, resource.resourceType));
13232
- blockDependenciesOf(logicalId);
13233
- recordDestroyEvent(ctx.eventRecorder, {
13234
- eventType: "RESOURCE_FAILED",
13235
- stackName,
13236
- operation: "DELETE",
13237
- logicalId,
13238
- resourceType: resource.resourceType,
13239
- ...resource.provisionedBy && { provisionedBy: resource.provisionedBy },
13240
- durationMs: Date.now() - resourceStartedAt,
13241
- error: extractDeploymentEventError(error)
13242
- });
13243
- }
13244
- } finally {
13245
- renderer.removeTask(logicalId);
13246
- }
13247
- }));
13262
+ const deletePromises = level.map((logicalId) => withPrintingSecrets(printingBagOf(logicalId), () => deleteStackResource(resourceFrame, logicalId, stackRegion)));
13248
13263
  await Promise.all(deletePromises);
13249
13264
  }
13250
13265
  for (const entry of supersededResourcesOf(state)) {
@@ -13339,38 +13354,19 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
13339
13354
  else logger.warn(`${result.skippedCount - result.journaledOrphanSkips} resource(s) skipped — cdkd did not confirm they were deleted, so they may still exist in AWS. State preserved (the records are kept so the resources stay traceable).`);
13340
13355
  if (result.blockedCount > 0) logger.warn(safeMsg`${result.blockedCount} resource(s) not deleted because the delete of a resource that ` + "depends on them failed, as CloudFormation leaves them: " + safeMsg`${blockedIds.map((id) => plainOrDescribed(id, "logical id")).join(", ")}. ` + "Their records are kept: once the resource blocking them is deleted, a re-run of 'cdkd destroy' / 'cdkd state destroy' deletes them.");
13341
13356
  }
13342
- const retainedSuffix = result.retainedCount > 0 ? `, ${result.retainedCount} retained` : "";
13343
- const skippedSuffix = (result.skippedCount > 0 ? `, ${yellow(result.skippedCount)} skipped` : "") + (result.blockedCount > 0 ? `, ${yellow(result.blockedCount)} blocked` : "");
13344
- const guardSuffix = result.guardIndeterminateCount > 0 ? `, ${yellow(result.guardIndeterminateCount)} unverified` : "";
13345
- if (result.guardIndeterminateCount > 0) {
13346
- const eventsCommand = pasteableCommand("cdkd events", [{
13347
- value: stackName,
13348
- hole: "stack",
13349
- opts: { plainIdent: true }
13350
- }]);
13351
- const durablePointer = ctx.eventRecorder === void 0 ? "This summary is the only record: this run wrote no deployment events, because it destroyed a nested-stack child, which threads no event recorder." : "The RESOURCE_GUARD_INDETERMINATE entries name the check and the reason and survive the run." + withheldTargetClause(eventsCommand, "stack", "cdkd events", "This stack's name") + `\nRead them with: ${eventsCommand.command}`;
13352
- logger.warn(`\n${yellow("⚠")} ${result.guardIndeterminateCount} pre-flight safety check(s) could NOT be completed during this destroy and cdkd proceeded anyway: ${[...guardIndeterminateTargets].map((t) => plainOrDescribed(t, "logical id")).join(", ")}. A check can be suppressed by DENYING the permission it needs, so treat this as unconfirmed rather than benign. ${durablePointer}`);
13353
- }
13354
- if (result.journaledOrphanSkips > 0) logger.warn(safeMsg`${result.journaledOrphanSkips} resource(s) a failed deploy created were left in AWS (each named in a ` + "warning above, which says what to do with it). This stack no longer records them.");
13355
- if (!preserveState) {
13356
- const leftInAws = result.journaledOrphanSkips > 0;
13357
- logger.info(`\n${leftInAws ? yellow("⚠") : green("✓")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} ${leftInAws ? "destroyed, with resources left in AWS" : "destroyed"}`)} (${green(result.deletedCount)} deleted${retainedSuffix}${leftInAws ? skippedSuffix : ""}${guardSuffix}, ${result.errorCount} errors)`);
13358
- } else if (result.interrupted && result.errorCount === 0) logger.warn(`\n${yellow("⚠")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} destroy interrupted`)} (${green(result.deletedCount)} deleted${retainedSuffix}${skippedSuffix}${guardSuffix}, ${result.errorCount} errors). State preserved — re-run 'cdkd destroy' / 'cdkd state destroy' to finish.`);
13359
- else if (result.errorCount === 0) {
13360
- const targets = [...skippedStateTargets];
13361
- const showHint = hintFor("cdkd state show", targets, "Inspect it with");
13362
- const orphanHint = hintFor("cdkd state orphan", targets, "Drop the record with");
13363
- logger.warn(`\n${yellow("⚠")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} partially destroyed`)} (${green(result.deletedCount)} deleted${retainedSuffix}${skippedSuffix}${guardSuffix}, ${result.errorCount} errors). cdkd did not confirm the skipped resource(s) were deleted, so they may still exist in AWS. ${SKIPPED_REMEDY}` + hintHolesClause(targets) + showHint + orphanHint);
13364
- } else {
13365
- const failedTargets = failedStateTargets.size > 0 ? [...failedStateTargets] : [stackName];
13366
- const orphanHint = journaledOrphanFailures > 0 ? "" : hintFor("cdkd state orphan", failedTargets, "Drop the record with");
13367
- const skippedTargets = [...skippedStateTargets];
13368
- const skippedClause = skippedTargets.length > 0 ? ` Separately, ${result.skippedCount} resource(s) were SKIPPED — cdkd did not confirm they were deleted, so they may still exist in AWS. ${SKIPPED_REMEDY}` : "";
13369
- const droppableSkipped = journaledOrphanFailures > 0 ? skippedTargets.filter((t) => t !== stackName) : skippedTargets;
13370
- const skippedCommands = hintFor("cdkd state show", skippedTargets, "Inspect it with") + hintFor("cdkd state orphan", droppableSkipped, "Drop the record with");
13371
- const dedupedCommands = (lines) => [...new Set(lines.split("\n").filter((l) => l !== ""))].map((l) => `\n${l}`).join("");
13372
- logger.warn(`\n${yellow("⚠")} ${bold(`Stack ${plainOrDescribed(stackName, "stack name")} partially destroyed`)} (${green(result.deletedCount)} deleted${retainedSuffix}${skippedSuffix}${guardSuffix}, ${red(result.errorCount)} errors). State preserved — re-run 'cdkd destroy' / 'cdkd state destroy' to clean up. ` + (journaledOrphanFailures > 0 ? `${journaledOrphanFailures} of the failures are resources a failed deploy created that only the rollback journal records: re-run the destroy to retry them. Do not drop this stack's state record — that also deletes the journal, their only record.` : "If the same resource keeps failing, dropping the state record is the last resort: it removes the record without deleting AWS resources.") + skippedClause + hintHolesClause([...orphanHint === "" ? [] : failedTargets, ...skippedTargets]) + dedupedCommands(orphanHint + skippedCommands));
13373
- }
13357
+ printDestroySummary({
13358
+ result,
13359
+ ctx,
13360
+ stackName,
13361
+ logger,
13362
+ preserveState,
13363
+ guardIndeterminateTargets,
13364
+ skippedStateTargets,
13365
+ failedStateTargets,
13366
+ hintFor,
13367
+ hintHolesClause,
13368
+ journaledOrphanFailures
13369
+ });
13374
13370
  } finally {
13375
13371
  try {
13376
13372
  await lock.release({
@@ -13397,29 +13393,191 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
13397
13393
  }
13398
13394
  return result;
13399
13395
  }
13400
- async function scanActiveConsumers(producerStack, producerRegion, ctx) {
13401
- const refs = await ctx.stateBackend.listStacks();
13402
- return (await Promise.all(refs.map(async (ref) => {
13403
- const region = ref.region ?? ctx.baseRegion;
13404
- if (ref.stackName === producerStack && region === producerRegion) return null;
13396
+
13397
+ // src/cli/commands/destroy-runner/run.ts
13398
+ async function runDestroyForStack(stackName, state, ctx) {
13399
+ const stackRegion = state.region;
13400
+ if (!stackRegion || stackRegion === ctx.baseRegion) return destroyStackInRegion(stackName, state, ctx, void 0);
13401
+ const scopeClients = new AwsClients({
13402
+ region: stackRegion,
13403
+ ...ctx.profile && { profile: ctx.profile }
13404
+ });
13405
+ try {
13406
+ const awsScope = {
13407
+ region: stackRegion,
13408
+ clients: scopeClients
13409
+ };
13410
+ const nestedContext = getCurrentNestedStackContext();
13411
+ return await runInStackAwsScope(awsScope, () => {
13412
+ const registry = new ProviderRegistry();
13413
+ const destroyInScope = () => destroyStackInRegion(stackName, state, ctx, {
13414
+ clients: scopeClients,
13415
+ registry
13416
+ });
13417
+ return nestedContext === void 0 ? destroyInScope() : withNestedStackContext({
13418
+ ...nestedContext,
13419
+ providerRegistry: registry,
13420
+ awsClients: scopeClients
13421
+ }, destroyInScope);
13422
+ });
13423
+ } finally {
13405
13424
  try {
13406
- const imports = (await ctx.stateBackend.getState(ref.stackName, region))?.state.imports;
13407
- if (!imports || imports.length === 0) return null;
13408
- const matches = imports.filter((entry) => entry.sourceStack === producerStack && canonicalizeRegion(entry.sourceRegion) === canonicalizeRegion(producerRegion));
13409
- if (matches.length === 0) return null;
13410
- return matches.map((entry) => ({
13411
- consumerStack: ref.stackName,
13412
- consumerRegion: region,
13413
- exportName: entry.exportName
13414
- }));
13415
- } catch {
13416
- return null;
13425
+ scopeClients.destroy();
13426
+ } catch (destroyError) {
13427
+ getLogger().debug(`Failed to destroy region-scoped AWS clients: ${describeAwsFailure(destroyError).detail}`);
13417
13428
  }
13418
- }))).filter((r) => r !== null).flat();
13429
+ }
13419
13430
  }
13420
- function refuseNewPendingRequests(read, stackName, region) {
13421
- if ((read.pendingRequests ?? 0) === 0) return;
13422
- throw new Error(`The rollback journal of stack ${displayStackName(stackName)} (${displaySafe(region, { asciiOnly: true })}) now records a Cloud Control CREATE a failed deploy stopped waiting for — another cdkd process wrote to it. Nothing was deleted; re-run the destroy, which checks how that CREATE ended first.`);
13431
+ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
13432
+ const providerClasses = await loadProviderClasses();
13433
+ const logger = getLogger();
13434
+ const result = {
13435
+ stackName,
13436
+ cancelled: false,
13437
+ skippedEmpty: false,
13438
+ deletedCount: 0,
13439
+ retainedCount: 0,
13440
+ skippedCount: 0,
13441
+ guardIndeterminateCount: 0,
13442
+ journaledOrphanSkips: 0,
13443
+ stateDeleted: false,
13444
+ blockedCount: 0,
13445
+ errorCount: 0,
13446
+ interrupted: false
13447
+ };
13448
+ const regionForState = state.region ?? ctx.baseRegion;
13449
+ const crossPrefixScan = ctx.crossPrefixCheck?.cache.full(stackName, regionForState);
13450
+ const refusalRecovery = {
13451
+ profile: ctx.profile,
13452
+ stateBucket: ctx.stateBucket,
13453
+ statePrefix: ctx.statePrefix
13454
+ };
13455
+ const stackLockBase = {
13456
+ lockManager: ctx.lockManager,
13457
+ stackName,
13458
+ region: regionForState,
13459
+ operation: "destroy",
13460
+ recovery: refusalRecovery
13461
+ };
13462
+ const journaledOrphans = await refuseMalformedRecordAndLoadJournaledOrphans({
13463
+ state,
13464
+ stackName,
13465
+ regionForState,
13466
+ refusalRecovery,
13467
+ ctx,
13468
+ logger,
13469
+ stackLockBase
13470
+ });
13471
+ const resourceCount = Object.keys(state.resources).length;
13472
+ const orphanCount = (state.orphans ?? []).length;
13473
+ const supersededCount = supersededResourcesOf(state).length;
13474
+ refuseMalformedOutputsForDestroy(state, stackName, regionForState, refusalRecovery);
13475
+ if (crossPrefixScan) applyCrossPrefixScan(await crossPrefixScan, {
13476
+ stackName,
13477
+ region: regionForState,
13478
+ bucket: ctx.stateBucket,
13479
+ recovery: {
13480
+ profile: ctx.profile,
13481
+ stateBucket: ctx.stateBucket
13482
+ }
13483
+ }, "destroy", (message) => logger.warn(message), (message) => logger.info(message));
13484
+ if (resourceCount === 0 && orphanCount === 0 && !holdsSupersededResources(state) && journaledOrphans.count === 0) return destroyEmptyStack({
13485
+ stackName,
13486
+ ctx,
13487
+ logger,
13488
+ stackLockBase,
13489
+ regionForState,
13490
+ refusalRecovery,
13491
+ journaledOrphans,
13492
+ result
13493
+ });
13494
+ const needsStrongRefCheck = !!(state.outputs && Object.keys(state.outputs).length > 0);
13495
+ if (needsStrongRefCheck) {
13496
+ const consumers = await scanActiveConsumers(stackName, regionForState, ctx);
13497
+ if (consumers.length > 0) throw new StackHasActiveImportsError(stackName, regionForState, consumers);
13498
+ }
13499
+ logger.info(`\nResources to be deleted (${resourceCount}):`);
13500
+ for (const [logicalId, resource] of Object.entries(state.resources)) logger.info(` - ${displaySafe(logicalId)} (${displaySafe(resource.resourceType)})`);
13501
+ if (supersededCount > 0) {
13502
+ logger.info(safeMsg`\nOld resources a replacement left to delete (${supersededCount}):`);
13503
+ for (const entry of supersededResourcesOf(state)) logger.info(safeMsg` - ${entry.logicalId} (${entry.state.resourceType}), superseded`);
13504
+ }
13505
+ const protectedCount = ctx.removeProtection ? countProtectedResources(state) + countProtectedJournaledOrphans(journaledOrphans, state.region) : 0;
13506
+ let binding;
13507
+ const stackNoEchoValues = () => {
13508
+ if (binding === void 0) {
13509
+ let timer;
13510
+ const capped = new Promise((resolve) => {
13511
+ timer = setTimeout(() => {
13512
+ logger.warn(safeMsg`The stack's NoEcho values were not bound within ${NOECHO_PRINTING_BIND_CAP_MS / 1e3}s, ` + "so a resource name taken from one may print unmasked where state holds it in plaintext (state written before schema v11).");
13513
+ resolve(void 0);
13514
+ }, NOECHO_PRINTING_BIND_CAP_MS);
13515
+ timer.unref?.();
13516
+ });
13517
+ binding = {
13518
+ bound: Promise.resolve().then(() => ctx.noEchoReresolver?.printingNoEchoValues()).catch(() => void 0).finally(() => clearTimeout(timer)),
13519
+ capped
13520
+ };
13521
+ }
13522
+ return Promise.race([binding.bound, binding.capped]);
13523
+ };
13524
+ const cancelled = await announceOrphansAndConfirm({
13525
+ state,
13526
+ logger,
13527
+ stackNoEchoValues,
13528
+ journaledOrphans,
13529
+ ctx,
13530
+ stackName,
13531
+ resourceCount,
13532
+ protectedCount,
13533
+ result
13534
+ });
13535
+ if (cancelled !== void 0) return cancelled;
13536
+ const stackRegion = state.region;
13537
+ let destroyProviderRegistry = ctx.providerRegistry;
13538
+ let destroyAwsClients;
13539
+ let regionSwitched = false;
13540
+ const restoreBaseRegionAndClients = () => {
13541
+ if (!regionSwitched) return;
13542
+ regionSwitched = false;
13543
+ destroyAwsClients = void 0;
13544
+ process.env["AWS_REGION"] = ctx.baseRegion;
13545
+ process.env["AWS_DEFAULT_REGION"] = ctx.baseRegion;
13546
+ setAwsClients(ctx.baseAwsClients);
13547
+ };
13548
+ if (stackScope !== void 0 && stackRegion) {
13549
+ logger.info(`Stack region: ${displaySafe(stackRegion, { asciiOnly: true })}`);
13550
+ process.env["AWS_REGION"] = stackRegion;
13551
+ process.env["AWS_DEFAULT_REGION"] = stackRegion;
13552
+ regionSwitched = true;
13553
+ try {
13554
+ destroyAwsClients = stackScope.clients;
13555
+ setAwsClients(destroyAwsClients);
13556
+ destroyProviderRegistry = stackScope.registry;
13557
+ registerAllProviders(destroyProviderRegistry, providerClasses);
13558
+ destroyProviderRegistry.setCustomResourceResponseBucket(ctx.stateBucket);
13559
+ if (ctx.allowUnsupportedTypes?.length) destroyProviderRegistry.allowUnsupportedTypes(ctx.allowUnsupportedTypes);
13560
+ } catch (setupError) {
13561
+ restoreBaseRegionAndClients();
13562
+ throw setupError;
13563
+ }
13564
+ }
13565
+ return destroyStackUnderLock({
13566
+ stackName,
13567
+ state,
13568
+ ctx,
13569
+ logger,
13570
+ result,
13571
+ regionForState,
13572
+ refusalRecovery,
13573
+ stackLockBase,
13574
+ journaledOrphans,
13575
+ needsStrongRefCheck,
13576
+ stackNoEchoValues,
13577
+ destroyProviderRegistry,
13578
+ destroyAwsClients,
13579
+ restoreBaseRegionAndClients
13580
+ });
13423
13581
  }
13424
13582
 
13425
13583
  // src/cli/commands/destroy-skip-message.ts
@@ -32791,4 +32949,4 @@ function collectVerbFlags(program) {
32791
32949
  }
32792
32950
 
32793
32951
  export { resolveSecretDerivedPrincipals as a, buildProgram, isResolvableSecretPrincipalList as i, runDestroyForStack as n, canonicalizeIpProtocolValue as o, holdsUnprovenSecretPrincipalToken as r, canonicalizeIpv4Cidr as t };
32794
- //# sourceMappingURL=program-Be87SvBg.js.map
32952
+ //# sourceMappingURL=program-Dm0zFrcG.js.map