@cdkd/cli 0.350.0 → 0.350.2

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 (66) hide show
  1. package/dist/{ambient-client-defaults-7acjxfyN.js → ambient-client-defaults-nYbcw8Dc.js} +9 -166
  2. package/dist/ambient-client-defaults-nYbcw8Dc.js.map +1 -0
  3. package/dist/{asg-provider-Dvy_jqxt.js → asg-provider-C2lKCOu5.js} +9 -8
  4. package/dist/asg-provider-C2lKCOu5.js.map +1 -0
  5. package/dist/cli.js +3 -23
  6. package/dist/cli.js.map +1 -1
  7. package/dist/{custom-resource-runtime-BJmM5h_B.js → custom-resource-runtime-BcxDxd28.js} +96 -15
  8. package/dist/custom-resource-runtime-BcxDxd28.js.map +1 -0
  9. package/dist/{db-instance-modify-retry-pFWx2ED5.js → db-instance-modify-retry-EpoVdg4u.js} +4 -4
  10. package/dist/{db-instance-modify-retry-pFWx2ED5.js.map → db-instance-modify-retry-EpoVdg4u.js.map} +1 -1
  11. package/dist/{deploy-engine-C_cFqAUx.js → deploy-engine-DWLm19jg.js} +606 -403
  12. package/dist/deploy-engine-DWLm19jg.js.map +1 -0
  13. package/dist/{diff-calculator-CLik-y3v.js → diff-calculator-DNuEc3vO.js} +21 -29
  14. package/dist/diff-calculator-DNuEc3vO.js.map +1 -0
  15. package/dist/{ec2-termination-protection-BM1Zt3Fn.js → ec2-termination-protection-BrCiVso0.js} +26 -8
  16. package/dist/ec2-termination-protection-BrCiVso0.js.map +1 -0
  17. package/dist/{ecr-uri-C3_6QVgR.js → ecr-uri-JpCbWN50.js} +2 -2
  18. package/dist/{ecr-uri-C3_6QVgR.js.map → ecr-uri-JpCbWN50.js.map} +1 -1
  19. package/dist/{expected-bucket-owner-CGoY_YS8.js → expected-bucket-owner-IaiC3JwO.js} +2 -2
  20. package/dist/{expected-bucket-owner-CGoY_YS8.js.map → expected-bucket-owner-IaiC3JwO.js.map} +1 -1
  21. package/dist/{iam-role-provider-BaN9MMWs.js → iam-role-provider-fNKzA1U5.js} +6 -5
  22. package/dist/iam-role-provider-fNKzA1U5.js.map +1 -0
  23. package/dist/{image-plan-PsGpMjv7.js → image-plan-C87HDsmb.js} +93 -28
  24. package/dist/image-plan-C87HDsmb.js.map +1 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +5 -5
  27. package/dist/{logger-DmQRya0S.js → logger-CD1O0WGI.js} +3 -121
  28. package/dist/logger-CD1O0WGI.js.map +1 -0
  29. package/dist/{neptune-provider-BYgFNrtZ.js → neptune-provider-BYb2XZFH.js} +8 -7
  30. package/dist/neptune-provider-BYb2XZFH.js.map +1 -0
  31. package/dist/{program-C7rUgzkB.js → program-DJWAG98-.js} +485 -266
  32. package/dist/program-DJWAG98-.js.map +1 -0
  33. package/dist/{provider-classes-WNwnshId.js → provider-classes-B8WD5ucF.js} +204 -118
  34. package/dist/provider-classes-B8WD5ucF.js.map +1 -0
  35. package/dist/{rds-provider-DKZjtd50.js → rds-provider-B5Ox8FBm.js} +19 -18
  36. package/dist/rds-provider-B5Ox8FBm.js.map +1 -0
  37. package/dist/{read-replica-C5e4xpYi.js → read-replica-6SDKYiLa.js} +3 -3
  38. package/dist/{read-replica-C5e4xpYi.js.map → read-replica-6SDKYiLa.js.map} +1 -1
  39. package/dist/{replacement-rules-01_01yDU.js → replacement-rules-Dpkm5pWN.js} +3 -2
  40. package/dist/replacement-rules-Dpkm5pWN.js.map +1 -0
  41. package/dist/{resource-deadline-TfDpwRQ_.js → resource-deadline-P1IssiEh.js} +4 -4
  42. package/dist/{resource-deadline-TfDpwRQ_.js.map → resource-deadline-P1IssiEh.js.map} +1 -1
  43. package/dist/run-cli-CXI5umz9.js +34 -0
  44. package/dist/run-cli-CXI5umz9.js.map +1 -0
  45. package/dist/{update-removal-D-FspP88.js → update-removal-C8I2P2bf.js} +30 -8
  46. package/dist/update-removal-C8I2P2bf.js.map +1 -0
  47. package/dist/version-Cu2oblwQ.js +300 -0
  48. package/dist/version-Cu2oblwQ.js.map +1 -0
  49. package/package.json +2 -2
  50. package/dist/ambient-client-defaults-7acjxfyN.js.map +0 -1
  51. package/dist/asg-provider-Dvy_jqxt.js.map +0 -1
  52. package/dist/custom-resource-runtime-BJmM5h_B.js.map +0 -1
  53. package/dist/deploy-engine-C_cFqAUx.js.map +0 -1
  54. package/dist/diff-calculator-CLik-y3v.js.map +0 -1
  55. package/dist/ec2-termination-protection-BM1Zt3Fn.js.map +0 -1
  56. package/dist/iam-role-provider-BaN9MMWs.js.map +0 -1
  57. package/dist/image-plan-PsGpMjv7.js.map +0 -1
  58. package/dist/logger-DmQRya0S.js.map +0 -1
  59. package/dist/neptune-provider-BYgFNrtZ.js.map +0 -1
  60. package/dist/program-C7rUgzkB.js.map +0 -1
  61. package/dist/provider-classes-WNwnshId.js.map +0 -1
  62. package/dist/rds-provider-DKZjtd50.js.map +0 -1
  63. package/dist/replacement-rules-01_01yDU.js.map +0 -1
  64. package/dist/update-removal-D-FspP88.js.map +0 -1
  65. package/dist/version-DeKI8TvP.js +0 -11
  66. package/dist/version-DeKI8TvP.js.map +0 -1
@@ -1,19 +1,19 @@
1
- import { t as getCdkdVersion } from "./version-DeKI8TvP.js";
2
- import { $ as renderUnmatchedPatternsWarning, $t as parseContextOptions, A as followContainerLogs, At as rawCliRegion, B as resolveRuntimeCodeMountPath, Bt as writeProfileCredentialsFile, C as waitForRieReady, Ct as warnAwsEmulatorStateSourceHint, Dt as foldRegionOption, E as SENSITIVE_ENV_KEYS, Et as exportInferredRegionForSdk, F as removeContainer, Ft as resolveEffectiveRegion, G as partitionTopLevel, Gt as contextOptions, H as resolveRuntimeImage, Ht as appOptions, It as stackRegionResolver, J as renderAllNoTopLevelStacks, Jt as destroyOptions, K as refuseStackNameRegionCollisions, Kt as deployOptions, L as runDetached, Lt as stateWithRegion, M as killAndDrainContainerLogs, Mt as reconcileMarkerRegionWithLegacyDefault, N as pickFreePort, Nt as regionNeedsReconciliation, O as ensureDockerAvailable, Ot as legacyStateBucketFallbackRegion, P as pullImage, Pt as regionShown, Q as renderStacksNoLongerSelected, Qt as noLocalCustomResourcesOption, Rt as withOtherIndexRemoval, S as invokeRie, St as taskRoleAssumedInRealAws, T as DockerRunnerError, Tt as adoptDeprecatedRegionFlag, U as describeStack, Ut as applyWaitFlagEnv, V as resolveRuntimeFileExtension, Vt as annotationMessageOptions, W as matchStacks, Wt as commonOptions, X as renderNoStackMatch, Xt as guardStackRegionOptions, Y as renderAmbiguousTargetStack, Yt as exclusivelyOption, Z as renderNotInAppWarning, Zt as noCfnFallbackOption, _ as copyLayerTreeLastWins, _n as listAllLockKeys, _t as prepareLocalLoopbackForwarder, a as materializeLayerFromArn, an as warnIfDeprecatedRegion, at as buildCdkPathIndex, b as probeHostGatewaySupport, bt as resolveContainerRegion, cn as parseAssumeRoleToken, ct as stackForConstructPath, d as resolveAssetCodeDirectory, dn as resourceTimeoutOptions, dt as assertAwsEmulatorValue, en as parseStackRegion, et as selectTargetStack, f as derivePseudoParametersFromRegion$1, fn as validateResourceTimeouts, ft as attachLocalLoopbackForwarder, g as buildContainerImage$1, gn as describeStateKey, gt as mixedModeEmulatorOverride, h as architectureToPlatform, hn as STATE_KEY_MAX_CODE_POINTS, ht as mixedModeActive, i as resolveInlineCodeFilePath, in as useCdkBootstrapAssetsOption, it as unmatchedPatterns, jt as reconcileExportIndexRegion, k as flushStdio, kt as namedCliRegion, l as resolveLambdaLayers, ln as allowUnsupportedTypesOption, lt as stackForPathFormTarget, m as tryResolveImageFnJoin, mn as STATE_FILE_SUFFIX, mt as localAwsEmulatorCredentials, n as resolveTmpfsForLambda, nn as stackOptions, nt as stacksForDependency, o as resolveLambdaTarget, on as effectiveAssumeRoleArn, ot as readCdkPathOrUndefined, p as substituteImagePlaceholders, pn as LOCK_FILE_SUFFIX, pt as getActiveWorkloadAwsWiring$1, q as renderAllLeftOutStageStacks, qt as deprecatedRegionOption, r as resolveZipImagePlan, rn as stateOptions, rt as stacksNoLongerSelected, s as extractEphemeralStorageMb, sn as normalizeStartApiAssumeRole, st as resolveCdkPathToLogicalIds, t as resolveLocalBuildPlan$1, tn as skipFinalSnapshotOption, tt as stackMatchesPattern, u as assetPathDirs, un as parseDuration, ut as activateLocalAwsAndRoleArn, v as layerAssetDirectory, vn as listAllStateKeys, vt as profileCredentialsForWorkload, w as CONTAINER_LOG_DRAIN_TIMEOUT_MS, wt as workloadGetsEmulatorKeysOnly, x as resolveHostGatewayExtraHosts, xt as setContainerRegion, y as HOST_GATEWAY_MIN_VERSION, yn as parseStateKey, yt as realAwsException, z as streamLogs, zt as strandedProfileCredentialsNotice } from "./image-plan-PsGpMjv7.js";
3
- import { $t as forceQuitRecoveryClause, Dt as logicalIdShown, H as assertRegionMatch, M as VALUE_NOT_SHOWN, Qt as buildLockContentionMessage, U as isMarkedNotGone, V as RESOURCE_NOT_FOUND, Xt as UNREPRODUCIBLE_LOCK_CLAUSE, Zt as buildForceUnlockCommand, an as CUSTOM_RESOURCE_RESPONSE_PREFIX, bt as interruptWatchListenerCount, dn as setPasteableAwsCaBundle, en as formatLockExpiry, fn as setPasteableAwsProfile, kt as resourceTypeShown, ln as producerCoordinateKey, m as RESOLVED_PREVIOUS_PRINCIPAL_KEYS, mt as isAwsCliLiteral, nn as formatLockOwner, on as DEFAULT_STATE_PREFIX, p as IAM_PRINCIPAL_NAME, pn as withPasteableAwsProfile, sn as injectiveKey, st as runDeleteAttempt, tn as formatLockOperation, un as producerRecordKey, vt as beginCommandInterruptScope, xt as isInterruptedWaitError, y as readRecordedPrincipals, yt as endCommandInterruptScope, z as remedyLogicalId } from "./update-removal-D-FspP88.js";
4
- import { A as stripControlChars, B as retryClassificationText, Ct as withheldTargetClause, F as isAmbiguousOutcomeError, H as isMarkedNonRetryable, J as DynamicReferenceRegionAmbiguousError, Q as AccountIdUnavailableError, R as isRetryableTransientError, St as shellQuote, Tt as setPasteableVerbFlags, U as isThrottlingError, W as markNonRetryable, X as MalformedProducerRecordRefusalError, Y as IntrinsicResolutionRefusalError, _ as ResourceUpdateNotSupportedError, _t as pasteableCommand, a as normalizeAwsError, at as ProvisioningError, bt as quotedOrDescribed, ct as SynthesisError, et as CdkdError, ft as SHELL_ACTIVE_WHY, g as PartialFailureError, gt as isInertUnquoted, h as NestedStackChildDirectDestroyError, i as credentialFingerprint, j as stripForDisplay, k as escapeRegExp, l as withErrorHandling, mt as commandHole, n as ambientCredentialConfig, o as formatError, ot as ResourceTimeoutError, q as CrossAccountSecretRefusalError, r as clientDefaultsFor, rt as LocalInvokeBuildError$1, s as handleError, st as StateError, t as ambientClientDefaults, tt as DeployCancelledError, u as LocalStartServiceError, v as StackHasActiveImportsError, wt as setPasteableRunFlags, xt as shellBoundedDisplay, y as StackTerminationProtectionError, yt as plainOrDescribed, z as isTransientServerError } from "./ambient-client-defaults-7acjxfyN.js";
1
+ import { A as displayStackName, C as STACK_REF_MAX_CODE_POINTS, D as displayAwsMessage, E as cutMarker, F as stringifyJsonPayload, I as terminalSafe, L as truncateCodePoints, N as plainIdentOr, O as displayIdent, P as safeMsg, S as SECRET_REF_MAX_CODE_POINTS, T as asIsMessage, _ as shellQuote, b as setPasteableVerbFlags, c as deployReplaceCommand, d as pasteableCommand, g as shellBoundedDisplay, h as quotedOrDescribed, i as SHELL_ACTIVE_WHY, j as isPasteableIdent, k as displaySafe, m as proseQuoted, o as cdkdRemedy, p as plainOrDescribed, s as commandHole, t as getCdkdVersion, u as isInertUnquoted, v as withheldTargetClause, w as UNRENDERABLE, x as SAFE_MSG_ALTERED_CHAR, y as setPasteableRunFlags } from "./version-Cu2oblwQ.js";
2
+ import { $ as renderUnmatchedPatternsWarning, $t as guardStackRegionOptions, A as followContainerLogs, At as foldRegionOption, B as resolveRuntimeCodeMountPath, Bt as stateWithRegion, C as waitForRieReady, Cn as listAllStateKeys, Ct as setContainerRegion, Dt as workloadGetsEmulatorKeysOnly, E as SENSITIVE_ENV_KEYS, Et as warnAwsEmulatorStateSourceHint, F as removeContainer, Ft as reconcileMarkerRegionWithLegacyDefault, G as partitionTopLevel, Gt as appOptions, H as resolveRuntimeImage, Ht as strandedProfileCredentialsNotice, It as regionNeedsReconciliation, J as renderAllNoTopLevelStacks, Jt as contextOptions, K as refuseStackNameRegionCollisions, Kt as applyWaitFlagEnv, L as runDetached, Lt as regionShown, M as killAndDrainContainerLogs, Mt as namedCliRegion, N as pickFreePort, Nt as rawCliRegion, O as ensureDockerAvailable, Ot as adoptDeprecatedRegionFlag, P as pullImage, Pt as reconcileExportIndexRegion, Q as renderStacksNoLongerSelected, Qt as exclusivelyOption, Rt as resolveEffectiveRegion, S as invokeRie, Sn as listAllLockKeys, St as resolveContainerRegion, T as DockerRunnerError, Tt as taskRoleAssumedInRealAws, U as describeStack, Ut as writeProfileCredentialsFile, V as resolveRuntimeFileExtension, Vt as withOtherIndexRemoval, W as matchStacks, Wt as annotationMessageOptions, X as renderNoStackMatch, Xt as deprecatedRegionOption, Y as renderAmbiguousTargetStack, Yt as deployOptions, Z as renderNotInAppWarning, Zt as destroyOptions, _ as copyLayerTreeLastWins, _n as parsePositiveIntegerOption, _t as mixedModeActive, a as materializeLayerFromArn, an as stackOptions, at as buildCdkPathIndex, b as probeHostGatewaySupport, bn as STATE_KEY_MAX_CODE_POINTS, bt as profileCredentialsForWorkload, cn as warnIfDeprecatedRegion, ct as stackForConstructPath, d as resolveAssetCodeDirectory, dn as parseAssumeRoleToken, dt as assertAwsEmulatorValue, en as noCfnFallbackOption, et as selectTargetStack, f as derivePseudoParametersFromRegion$1, fn as allowUnsupportedTypesOption, ft as attachLocalLoopbackForwarder, g as buildContainerImage$1, gn as cliArgParser, gt as localAwsEmulatorCredentials, h as architectureToPlatform, hn as validateResourceTimeouts, ht as localAwsEmulatorActive, i as resolveInlineCodeFilePath, in as skipFinalSnapshotOption, it as unmatchedPatterns, jt as legacyStateBucketFallbackRegion, k as flushStdio, kt as exportInferredRegionForSdk, l as resolveLambdaLayers, ln as effectiveAssumeRoleArn, lt as stackForPathFormTarget, m as tryResolveImageFnJoin, mn as resourceTimeoutOptions, mt as keepEmulatorIssuedCredentials, n as resolveTmpfsForLambda, nn as parseContextOptions, nt as stacksForDependency, o as resolveLambdaTarget, on as stateOptions, ot as readCdkPathOrUndefined, p as substituteImagePlaceholders, pn as parseDuration, pt as getActiveWorkloadAwsWiring$1, q as renderAllLeftOutStageStacks, qt as commonOptions, r as resolveZipImagePlan, rn as parseStackRegion, rt as stacksNoLongerSelected, s as extractEphemeralStorageMb, sn as useCdkBootstrapAssetsOption, st as resolveCdkPathToLogicalIds, t as resolveLocalBuildPlan$1, tn as noLocalCustomResourcesOption, tt as stackMatchesPattern, u as assetPathDirs, un as normalizeStartApiAssumeRole, ut as activateLocalAwsAndRoleArn, v as layerAssetDirectory, vn as LOCK_FILE_SUFFIX, vt as mixedModeEmulatorOverride, w as CONTAINER_LOG_DRAIN_TIMEOUT_MS, wn as parseStateKey, wt as stateRoleRecordIsEmulatorSide, x as resolveHostGatewayExtraHosts, xn as describeStateKey, xt as realAwsException, y as HOST_GATEWAY_MIN_VERSION, yn as STATE_FILE_SUFFIX, yt as prepareLocalLoopbackForwarder, z as streamLogs, zt as stackRegionResolver } from "./image-plan-C87HDsmb.js";
3
+ import { $t as buildLockContentionMessage, At as resourceTypeShown, B as remedyLogicalId, H as RESOURCE_NOT_FOUND, M as VALUE_NOT_SHOWN, Ot as logicalIdShown, Qt as buildForceUnlockCommand, St as isInterruptedWaitError, U as assertRegionMatch, W as isMarkedNotGone, Zt as UNREPRODUCIBLE_LOCK_CLAUSE, bt as endCommandInterruptScope, cn as injectiveKey, ct as runDeleteAttempt, dn as producerRecordKey, en as forceQuitRecoveryClause, fn as setPasteableAwsCaBundle, ht as isAwsCliLiteral, m as RESOLVED_PREVIOUS_PRINCIPAL_KEYS, mn as withPasteableAwsProfile, nn as formatLockOperation, on as CUSTOM_RESOURCE_RESPONSE_PREFIX, p as IAM_PRINCIPAL_NAME, pn as setPasteableAwsProfile, rn as formatLockOwner, sn as DEFAULT_STATE_PREFIX, tn as formatLockExpiry, un as producerCoordinateKey, xt as interruptWatchListenerCount, y as readRecordedPrincipals, yt as beginCommandInterruptScope } from "./update-removal-C8I2P2bf.js";
5
4
  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-DOkPjjAW.js";
6
- import { $ as withStackScope, B as generateResourceName, E as coerceCfnBoolean, I as PATTERN_B_NAME_OPTIONS, L as PATTERN_B_NAME_PROPERTIES, Q as withSkipPrefix, R as PATTERN_B_RESOURCE_TYPES, S as explicitNamePropertyFor, X as isNameGeneration, _t as truncateCodePoints, a as reserveStdoutForPayload, at as asIsMessage, ct as displayIdent, dt as isPasteableIdent, gt as terminalSafe, ht as stringifyJsonPayload, i as releaseStdoutForPayload, it as UNRENDERABLE, lt as displaySafe, m as verboseAwareText, mt as safeMsg, n as getLogger, nt as SECRET_REF_MAX_CODE_POINTS, ot as cutMarker, p as safeStringify, pt as plainIdentOr, r as isStdoutReservedForPayload, rt as STACK_REF_MAX_CODE_POINTS, s as runStackBuffered, st as displayAwsMessage, tt as SAFE_MSG_ALTERED_CHAR, u as describeAwsFailure, ut as displayStackName, y as getLiveRenderer, z as derivesPatternBName } from "./logger-DmQRya0S.js";
5
+ import { $ as withStackScope, B as generateResourceName, E as coerceCfnBoolean, I as PATTERN_B_NAME_OPTIONS, L as PATTERN_B_NAME_PROPERTIES, Q as withSkipPrefix, R as PATTERN_B_RESOURCE_TYPES, S as explicitNamePropertyFor, X as isNameGeneration, a as reserveStdoutForPayload, i as releaseStdoutForPayload, m as verboseAwareText, n as getLogger, p as safeStringify, r as isStdoutReservedForPayload, s as runStackBuffered, u as describeAwsFailure, y as getLiveRenderer, z as derivesPatternBName } from "./logger-CD1O0WGI.js";
6
+ import { A as stripControlChars, B as retryClassificationText, F as isAmbiguousOutcomeError, H as isMarkedNonRetryable, J as DynamicReferenceRegionAmbiguousError, Q as AccountIdUnavailableError, R as isRetryableTransientError, U as isThrottlingError, W as markNonRetryable, X as MalformedProducerRecordRefusalError, Y as IntrinsicResolutionRefusalError, _ as ResourceUpdateNotSupportedError, a as normalizeAwsError, at as ProvisioningError, ct as SynthesisError, et as CdkdError, g as PartialFailureError, h as NestedStackChildDirectDestroyError, i as credentialFingerprint, j as stripForDisplay, k as escapeRegExp, l as withErrorHandling, n as ambientCredentialConfig, o as formatError, ot as ResourceTimeoutError, q as CrossAccountSecretRefusalError, r as clientDefaultsFor, rt as LocalInvokeBuildError$1, s as handleError, st as StateError, t as ambientClientDefaults, tt as DeployCancelledError, u as LocalStartServiceError, v as StackHasActiveImportsError, y as StackTerminationProtectionError, z as isTransientServerError } from "./ambient-client-defaults-nYbcw8Dc.js";
7
7
  import { a as getAssumedRoleCredentials, c as setAssumedRoleCredentials, h as formatAuthority, l as setAwsEndpointOverrideSource, m as runInStackAwsScope, n as awsClientDefaults, r as awsEndpointOverrideActive, s as runWithRealAws } from "./aws-client-defaults-DAebi99J.js";
8
- import { A as loadCdkJson, B as warnDeprecatedNoPrefixCliFlag, C as runDockerForeground, D as synthesisStatusMessage, E as Synthesizer, F as resolveStateBucketWithDefault, G as uploadCfnTemplate, H as CFN_TEMPLATE_URL_LIMIT, I as resolveStateBucketWithDefaultAndSource, J as AssemblyReader, K as refuseFailedLookups, L as resolveStateBucketWithSource, M as resolveAutoAssetStorage, N as resolveCaptureObservedState, O as getDefaultStateBucketName, P as resolveSkipPrefix, R as resolveUseCdkBootstrapAssets, S as getDockerCmd, T as abortInFlightMultipartUploads, U as MIGRATE_TMP_PREFIX, V as CFN_TEMPLATE_BODY_LIMIT, W as findLargeInlineResources, X as processStackMessages, Y as StageLoadError, Z as setChildProcessAwsEnv, _ as partitionSensitiveEnv, a as AssetPublisher, b as isMalformedEnvKey, c as resolveDockerContextDirectory, d as describeDockerFailure, f as redactedCause, g as finchSecretArgvRefusal, h as dockerSpawnEnvWithSensitive, i as isLockInfoExpired, j as resolveApp, k as getLegacyStateBucketName, m as redactDockerArgvValues, n as DagBuilder, o as WorkGraph, p as redactedDockerCause, r as LockManager, s as buildDockerImage, t as DiffCalculator, u as describeDockerExecFailure, v as warnFinchArgvExposure, w as runDockerStreaming, x as formatDockerLoginError, y as isDockerClientEnvKey, z as stateBucketExistenceConfirmed } from "./diff-calculator-CLik-y3v.js";
9
- import { $a as applyCallerIdentityCredentials, $i as isFinalSnapshotError, $n as withUnprovenUnsettled, $r as noEchoParameterValueSeed, $s as malformedOutputsRefusalMessage, $t as displacedOpClause, A as PROTECTION_PROPERTY_BY_TYPE, Aa as UNSPECIFIED_SKIP_REASON, Ac as NO_CC_HANDLERS_REASON, Ai as withAttemptedItemsMasked, Al as hasPlainPrototype, An as findDestructiveChanges, Ao as isImpossibleEmptyStoredAttribute, Ar as nameGenerationCarriedFrom, As as refuseMalformedResourceEntriesForImport, At as IMPLICIT_DELETE_DEPENDENCIES, Ba as stackIdTailOf, Bc as CrossPrefixScanCache, Bi as secretNamedRecordNeedles, Bn as differingRemedy, Br as namesAnyDeclaredParameter, Bs as refuseMalformedResourcePropertiesForExport, Bt as updateRefactorMarker, C as refusePendingMovesOut, Ca as withPrintingSecrets, Cc as findActionableSdkUnwired, Ci as green, Cn as NOECHO_MAC_KEY_ALIAS, Cs as malformedLocalResourcesWarning, D as diffSecurity, Di as noEchoComparisonForTemplate, Dl as decodeListingKey, Dn as noEchoMacVerdict, Dr as segmentCleanupOptions, Ds as refuseMalformedResourceEntries, E as serviceTokenBlockingReason, Ec as unwrittenCreateOnlyReplacement, Ei as noEchoAttributeNamesOf, En as noEchoMacParametersOf, Eo as recordedReferenceRegions, Es as refuseMalformedResourceAttributesForOrphan, Fa as isWaitAbandonedError, Fi as namingSecretsWithRecordedNoEcho, Fl as describeFileReadFailure, Fn as rollbackOrphanIds, Fo as withSharedDrainBudget, Fr as retiredNameGenerationsLeaving, Fs as malformedDriftResourcePropertiesWarning, Ft as readRefactorMarkerOnce, Ga as applyRoleArnIfSet, Gc as stackInstanceIdOf, Gn as propertiesChangedReason, Go as MULTI_REGION_RECREATE_BLOCKED_TYPES, Gr as exportAliasCollisionScrubWarning, Gs as malformedOrphansRefusalMessage, Gt as formatResourceLine, Ha as resolveDynamicReferences, Hc as crossPrefixDeniedWarning, Hi as storedSecretNameNeedles, Hn as looselyEqual, Ho as findReplacedReadersOfRecreateTargets, Hr as resourcesNamingDeclaredParameter, Hs as repairMalformedResourcePropertiesForReadOnly, Ht as readsOnlyNoEchoParameters, Ia as IntrinsicFunctionResolver, Ic as hasReasonlessBaselineRefusal, Ii as orphanRecordsPrintingBag, Il as displayAssemblyPath, In as withMovedTo, Ir as withNameGenerationReached, Is as malformedResourcePropertiesWarning, It as refactorMarkerMovesOf, Ja as explicitRoleArnOrThrow, Ji as ATOMIC_FINAL_SNAPSHOT_TYPES, Jn as replayFailedOperations, Jo as renderStatefulReason, Jr as secretSafeKeyDisplay, Js as refuseMalformedOrphansForDestroy, Ka as assertFlagRoleArn, Kc as withStackInstanceIdWithheld, Ki as secretSegmentsOfState, Kn as proposeRenames, Ko as isStatefulRecreateTargetForReplace, Kr as secretBearing, Ks as malformedOrphansWarning, La as isSelectOutOfBounds, Lc as hasUnverifiableParameterRefusal, Li as secretNamePrintingBag, Ln as changedReferenceInDiff, Lo as INTRINSIC_KEYS, Lt as refactorMarkerRefusalMessage, M as perType, Ma as deleteLeftInPlace, Mc as TemplateParser, Mi as completedReplayEntries, Ml as ownValue, Mn as findRefactorHints, Mo as isNamelessDynamicReferenceError, Mr as nameScopeOf, Ms as refuseMalformedResourceEntriesForOrphan, Mt as keptForRetainedRecord, N as readProtection, Na as deleteSkipReason, Nc as S3StateBackend, Ni as journaledOrphanPrintingBag, Nn as hintSidesOf, No as carriesDynamicReference, Nr as retiredAfterRollback, Ns as repairMalformedResourceEntriesForReadOnly, Nt as recordRetainedForReadoption, O as recordedProtectionEvidence, Oa as setResolvedResourceTimeouts, Oi as noEchoExactEchoLeavesOf, Ol as defineOwnKey, On as noEchoValueMacsOf, Or as removeProtectionTypeList, Os as refuseMalformedResourceEntriesForDeploy, Pc as splitImportedOps, Pi as maskEventTextWithBoundBags, Pn as movedToHint, Po as keepsSecretReferenceToken, Pr as retiredNameGenerationsAfter, Ps as unreadableResourceEntries, Pt as readRefactorMarker, Qa as AWS_CREDENTIAL_ENV_KEYS, Qi as effectiveDeletionPolicy, Qn as settleUnsettledPrevious, Qr as isWholeDynamicReferenceValue, Qs as malformedLocalOutputsWarning, Qt as NESTED_PENDING_PARENT_REASON, Ra as isAlwaysLiveAttribute, Rc as rebuildClientForBucketRegion, Ri as secretNamePrintingBags, Rl as renderAssemblyPathEscape, Rn as changedReferencePath, Rr as inheritProducerRegions, Rs as refuseMalformedResourcePropertiesForDestroy, Rt as refuseRefactorMarker, S as pendingMovesRefusalMessage, Sc as hasReadableResources, Si as gray, Sn as DeploymentEventsStore, So as keepHeldTokenProvenance, Sr as findNestedStackTypeChanges, Ss as malformedLocalResourceEntriesWarning, T as findServiceTokenRefusals, Ta as CloudControlProvider, Ti as yellow, Tl as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, Tn as noEchoMacBinding, Ts as malformedScrubResourceEntriesRefusalMessage, Ua as producerLookupOver, Uc as isAccessDenied, Ui as extractDeploymentEventError, Un as mappingPairs, Ur as WITHHELD_NAME_DISPLAY, Us as UNREADABLE_ORPHANS_CONTAINER_ROW, Vc as applyCrossPrefixScan, Vi as stateSecretNameNeedles, Vl as resolveBucketRegion, Vn as isPairableType, Vr as reachableDivergentParameters, Vs as refuseMalformedResourcePropertiesForOrphan, Vt as macWriteOnlyKeys, Wa as refuseUnreadableCdkCrossAccountRefs, Wc as isNotImplemented, Wn as parseMappingFile, Wo as shownType, Wr as displayTextOrWithheld, Ws as hasReadableOrphans, Xa as parseIamRoleArn, Xc as createAssetRedirectResolver, Xi as ccRoutedFinalSnapshotError, Xn as DELETED_RESOURCE_REMEDY, Xr as exportNameNoEchoParameters, Xs as malformedExportNamesWarning, Xt as pendingRequestCount, Ya as isIamRoleArn, Yc as buildAssetRedirectMap, Yi as PRE_DELETE_SNAPSHOT_TYPES, Yn as replayRollback, Yr as carriedExportAliasExposure, Ys as repairMalformedOrphansForReadOnly, Za as sendableAssumeRoleCommand, Zi as ccRoutedInstanceTakesNoSnapshot, Zn as recordAfterRollbackUpdate, Zr as exportNameSecretExposure, Zs as malformedExportSourceWarning, Zt as resolvePendingCloudControlRequests, _ as listNestedTemplateRows, _a as customResourceResponseExpirationWarning, _c as withheldAccountClause, _i as supersededHolderOf, _n as sameJournaledOrphans, _o as lacksRecordedTableArn, _r as recheckFailedPlan, _s as refuseMalformedOrphansForOrphan, a as scanActiveConsumers, aa as ProviderRegistry, ac as STATE_REGION_DIVERGED, ai as DEFAULT_RESOURCE_WARN_AFTER_MS, al as ensureAssetStorage, ao as regionLessSecretName, ar as updatePartialReason, as as maskedInputProof, b as hasPendingMovesOut, ba as readsNoEchoDeleteValues, bc as displayLogicalId, bi as bold, bn as planOrphanAdoption, br as resolveReplacementOldType, bs as unreadableOrphanRecords, c as inheritedProvenanceForChildDiff, ca as wouldReturnToSdkProvider, cc as malformedResourcesWarning, ci as destroyStackRecordsView, cl as isCrossRegionRedirect, cn as collectNestedChildUnaddressed, cs as maskedPropertyFingerprint, d as conditionInputsFrom, dc as refuseMalformedResourcesForDestroy, dl as readBootstrapMarkerBody, dn as deleteJournaledOrphans, do as coerceParameterTypedValue, dr as planRollback, ds as malformedOrphanRecordsRefusalMessage, ea as refusesFinalSnapshot, ec as malformedOutputsWarning, ei as collectDeclaredOutputNames, el as loadPublishableAssetManifest, en as displacedPhysicalIdShown, eo as callerEnvCredentials, er as calculateResourceDrift, f as parentSuppliedValues, fc as refuseMalformedResourcesForExport, fi as deleteSupersededEntry, fl as validateAssetBucketName, fn as dropFailedCommands, fo as isUnboundTemplateParameter, fr as seedsDeleteFirstGuard, fs as malformedOrphanRecordsWarning, g as isAbsoluteAssetPath, ga as applyCustomResourceResponseExpiration, gc as accountArgs, gi as supersededHeldByOtherTypeWarning, gl as getDockerImageBySourceHash, gn as loadJournaledOrphans, go as isStalePlaceholderArnAttribute, gr as planFailedOps, gs as refuseMalformedOrphanRecordsForDestroy, h as findNestedTemplateTreeDefect, ha as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, hc as JSON_LISTING_HOLE_VALUE, hi as supersededAfterRollback, hl as AssetManifestLoader, hn as journaledOrphanLines, ho as cfnRefValueFromPhysicalId, hr as isReplacementOrphan, hs as refuseMalformedOrphanRecords, i as mergeNoChangeOutputs, ia as CC_BROKEN_REASON, ic as repairMalformedOutputsForReadOnly, ii as DEFAULT_RESOURCE_TIMEOUT_MS, il as AssetModeResolver, in as recordDisplacedSkips, io as producerRegionsFromState, ir as updatePartialMessage, is as parameterInputsFor, j as isProtectionValueActive, ja as deleteIndeterminateGuards, jc as hasNoCloudControlHandlers, ji as createReadOnlyAttributeHealerFactory, jl as nullPrototypeRecord, jn as formatDestructiveChange, jo as carriesFetchableDynamicReference, jr as nameGenerationHighWaterOf, js as refuseMalformedResourceEntriesForImportSave, jt as computeImplicitDeleteEdges, k as recordedProtectionNote, ka as RollbackInlinePolicyWriters, ki as noEchoParameterNamesOf, kl as hasOwnKey, kn as constructPathOf$1, ko as getAccountInfo, kr as orphanNeedsIdentity, ks as refuseMalformedResourceEntriesForDestroy, l as makeCanonicalizePropertiesFn, lc as malformedStateRefusalMessage, ll as getBootstrapMarkerKey, ln as getCurrentNestedStackContext, lr as withCreateTokenLedger, ls as deployRefusesOrphanRowsReason, m as childTemplateLoader, ma as withCustomResourceStack, mc as repairMalformedResourcesForReadOnly, mi as isSupersededResourceRecord, ml as BOOTSTRAP_MARKER_PREFIX, mn as isHandledOrphan, mo as AWS_NO_VALUE, mr as isJournaledOrphan, ms as previewableOrphanRecords, n as isSecretBearingReferenceString, na as createPreDeleteFinalSnapshot, nc as refuseMalformedOutputs, ni as isExportAliasCollision, no as classifyRecordedSecretRegion, nr as equalModuloMask, ns as maskedPropertyFingerprintsOf, o as inRunStackKey, oa as ccBrokenReason, oc as refuseDivergentRecordRegionForDestroy, oi as maskingRetryLogger, ol as buildDenyExternalAccessPolicy, on as revertedNestedRowIds, p as readRecordedConditionVerdicts, pa as setLocalCustomResourceRuntimeEnabled, pc as refuseMalformedState, pi as holdsSupersededResources, pl as validateContainerRepoName, pn as dropFailedHint, po as parameterTypeMayLoseSecretIdentity, pr as demoteSupersededOrphans, ps as malformedOrphanRowsKeptWarning, qa as assertSendableRoleArn, qc as isSensitiveAttributeName, qi as withSecretPhysicalIdsMaskedInState, qn as referencedLogicalIds, qo as isStatefulRecreateTargetSync, qr as secretBearingStateKeyWarning, qs as refuseMalformedOrphans, r as keptWholeReasonText, ra as buildFinalSnapshotIdentifier, rc as refuseMalformedOutputsForDestroy, ri as bindingSkippedOutputs, rl as rewriteTemplateAssetReferences, rn as nestedChildStackName$1, ro as classifyReplaySecretRegion, rr as undeclaredEmptyObservedKeys, s as crossStackOutputProvenanceSource, sa as isCustomResource, sc as malformedRenderedContainersWarning, sl as assertAssetBucketRegion, sn as withNestedRevertRun, sr as ledgerForStack, ss as declaresNoEcho, t as DeployEngine, ta as unsupportedFinalSnapshotError, ti as collectPublishedOutputNames, tn as dropSettledNestedJournals, to as envCredentialsAreAssumedRole, tr as equalModuloMarkedMask, u as conditionFingerprint, uc as refuseMalformedResourcesForDeploy, ui as withStackRecords, ul as parseBootstrapMarker, un as withNestedStackContext, us as isReadableOrphanRecord, v as renderNestedTemplateTreeDefect, vc as STATE_RESOURCES_MALFORMED, vi as supersededResourcesOf, vn as makeForeignHolderScan, vo as refStateLookupFromResource, vr as recordUnderIdIsNotOwn, vs as repairMalformedOrphanRecordsForReadOnly, w as deferredServiceTokenWarning, wc as findHandledUnwrittenCreateOnly, wi as red, wl as ssmResolvedValueType, wn as createNoEchoValueMacs, wo as recordedOutputReferenceRegions, ws as malformedResourceEntriesWarning, x as pendingMovesOutOf, xa as isCustomResourceType$1, xc as hasReadableOutputs, xi as cyan, xn as DeploymentEventsReader, xr as withPreviousPolicies, xs as isReadableResourceEntry, y as templateIdentity, ya as TemplateNoEchoReresolver, yc as UNREADABLE_RESOURCES_MAP_ROW, yi as withoutSuperseded, yn as makeSiblingClaimReader, yr as replacementNeverSwapped, ys as unpreviewableOrphanRecords, za as poisonRenderedSpellingsCollidingIn, zc as CrossPrefixReadError, zl as resolveAssemblyPath, zn as changedReferenceReason, zr as computeParameterTaint, zs as refuseMalformedResourcePropertiesForDrift, zt as sameMove } from "./deploy-engine-C_cFqAUx.js";
8
+ import { A as loadCdkJson, B as warnDeprecatedNoPrefixCliFlag, C as runDockerForeground, D as synthesisStatusMessage, E as Synthesizer, F as resolveStateBucketWithDefault, G as uploadCfnTemplate, H as CFN_TEMPLATE_URL_LIMIT, I as resolveStateBucketWithDefaultAndSource, J as StageLoadError, K as refuseFailedLookups, L as resolveStateBucketWithSource, M as resolveAutoAssetStorage, N as resolveCaptureObservedState, O as getDefaultStateBucketName, P as resolveSkipPrefix, R as resolveUseCdkBootstrapAssets, S as getDockerCmd, T as abortInFlightMultipartUploads, U as MIGRATE_TMP_PREFIX, V as CFN_TEMPLATE_BODY_LIMIT, W as findLargeInlineResources, X as setChildProcessAwsEnv, Y as processStackMessages, _ as partitionSensitiveEnv, a as AssetPublisher, b as isMalformedEnvKey, c as resolveDockerContextDirectory, d as describeDockerFailure, f as redactedCause, g as finchSecretArgvRefusal, h as dockerSpawnEnvWithSensitive, i as isLockInfoExpired, j as resolveApp, k as getLegacyStateBucketName, m as redactDockerArgvValues, n as DagBuilder, o as WorkGraph, p as redactedDockerCause, q as AssemblyReader, r as LockManager, s as buildDockerImage, t as DiffCalculator, u as describeDockerExecFailure, v as warnFinchArgvExposure, w as runDockerStreaming, x as formatDockerLoginError, y as isDockerClientEnvKey, z as stateBucketExistenceConfirmed } from "./diff-calculator-DNuEc3vO.js";
9
+ import { $a as sendableAssumeRoleCommand, $i as isFinalSnapshotError, $n as equalModuloMarkedMask, $r as noEchoParameterValueSeed, $s as malformedExportSourceWarning, $t as dropSettledNestedJournals, A as PROTECTION_PROPERTY_BY_TYPE, Aa as setResolvedResourceTimeouts, Ai as withAttemptedItemsMasked, Al as decodeListingKey, An as findRefactorHints, Ar as nameGenerationCarriedFrom, As as refuseMalformedResourceEntriesForDeploy, At as keptForRetainedRecord, Ba as isAlwaysLiveAttribute, Bc as rebuildClientForBucketRegion, Bi as secretNamedRecordNeedles, Bl as describeFileReadFailure, Bn as looselyEqual, Br as namesAnyDeclaredParameter, Bs as refuseMalformedResourcePropertiesForDestroy, Bt as readsOnlyNoEchoParameters, C as refusePendingMovesOut, Cc as hasReadableOutputs, Ci as green, Cn as noEchoMacBinding, Cs as isReadableResourceEntry, D as diffSecurity, Da as CloudControlProvider, Di as noEchoComparisonForTemplate, Dl as ssmResolvedValueType, Dn as constructPathOf$1, Dr as segmentCleanupOptions, Ds as malformedScrubResourceEntriesRefusalMessage, E as serviceTokenBlockingReason, Ec as findHandledUnwrittenCreateOnly, Ei as noEchoAttributeNamesOf, En as noEchoValueMacsOf, Eo as recordedOutputReferenceRegions, Es as malformedResourceEntriesWarning, Fa as deleteSkipReason, Fc as S3StateBackend, Fi as namingSecretsWithRecordedNoEcho, Fl as hasPlainPrototype, Fn as changedReferenceInDiff, Fo as carriesDynamicReference, Fr as retiredNameGenerationsLeaving, Fs as repairMalformedResourceEntriesForReadOnly, Ft as refactorMarkerRefusalMessage, Ga as producerLookupOver, Gc as isAccessDenied, Gn as referencedLogicalIds, Gr as exportAliasCollisionScrubWarning, Gs as UNREADABLE_ORPHANS_CONTAINER_ROW, Ha as stackIdTailOf, Hc as CrossPrefixScanCache, Hi as storedSecretNameNeedles, Hn as parseMappingFile, Hr as resourcesNamingDeclaredParameter, Hs as refuseMalformedResourcePropertiesForExport, Ic as splitImportedOps, Ii as orphanRecordsPrintingBag, Il as nullPrototypeRecord, In as changedReferencePath, Io as keepsSecretReferenceToken, Ir as withNameGenerationReached, Is as unreadableResourceEntries, It as refuseRefactorMarker, Ja as assertFlagRoleArn, Jc as withStackInstanceIdWithheld, Ji as ATOMIC_FINAL_SNAPSHOT_TYPES, Jn as DELETED_RESOURCE_REMEDY, Jo as isStatefulRecreateTargetForReplace, Jr as secretSafeKeyDisplay, Js as malformedOrphansWarning, Jt as pendingRequestCount, Ka as refuseUnreadableCdkCrossAccountRefs, Kc as isNotImplemented, Ki as secretSegmentsOfState, Kl as resolveBucketRegion, Kn as replayFailedOperations, Ko as shownType, Kr as secretBearing, Ks as hasReadableOrphans, La as isWaitAbandonedError, Li as secretNamePrintingBag, Ll as ownValue, Ln as changedReferenceReason, Lo as withSharedDrainBudget, Ls as malformedDriftResourcePropertiesWarning, Lt as sameMove, M as perType, Ma as UNSPECIFIED_SKIP_REASON, Mc as NO_CC_HANDLERS_REASON, Mi as completedReplayEntries, Mn as movedToHint, Mo as isImpossibleEmptyStoredAttribute, Mr as nameScopeOf, Ms as refuseMalformedResourceEntriesForImport, Mt as readRefactorMarker, N as readProtection, Na as deleteIndeterminateGuards, Nc as hasNoCloudControlHandlers, Ni as journaledOrphanPrintingBag, Nl as defineOwnKey, Nn as rollbackOrphanIds, No as carriesFetchableDynamicReference, Nr as retiredAfterRollback, Ns as refuseMalformedResourceEntriesForImportSave, Nt as readRefactorMarkerOnce, O as recordedProtectionEvidence, Oc as unwrittenCreateOnlyReplacement, Oi as noEchoExactEchoLeavesOf, Ol as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, On as findDestructiveChanges, Oo as recordedReferenceRegions, Or as removeProtectionTypeList, Os as refuseMalformedResourceAttributesForOrphan, Pa as deleteLeftInPlace, Pc as TemplateParser, Pi as maskEventTextWithBoundBags, Pl as hasOwnKey, Pn as withMovedTo, Po as isNamelessDynamicReferenceError, Pr as retiredNameGenerationsAfter, Ps as refuseMalformedResourceEntriesForOrphan, Pt as refactorMarkerMovesOf, Qa as parseIamRoleArn, Qc as createAssetRedirectResolver, Qi as effectiveDeletionPolicy, Qn as calculateResourceDrift, Qr as isWholeDynamicReferenceValue, Qs as malformedExportNamesWarning, Qt as displacedPhysicalIdShown, Ra as IntrinsicFunctionResolver, Rc as hasReasonlessBaselineRefusal, Ri as secretNamePrintingBags, Rn as differingRemedy, Rr as inheritProducerRegions, Rs as malformedResourcePropertiesWarning, Rt as updateRefactorMarker, S as pendingMovesRefusalMessage, Sa as localCustomResourceCommand, Sc as displayLogicalId, Si as gray, Sn as createNoEchoValueMacs, Sr as findNestedStackTypeChanges, Ss as unreadableOrphanRecords, T as findServiceTokenRefusals, Ta as withCustomResourceStack, Tc as findActionableSdkUnwired, Ti as yellow, Tn as noEchoMacVerdict, Ts as malformedLocalResourcesWarning, Uc as applyCrossPrefixScan, Ui as extractDeploymentEventError, Ul as renderAssemblyPathEscape, Un as propertiesChangedReason, Ur as WITHHELD_NAME_DISPLAY, Us as refuseMalformedResourcePropertiesForOrphan, Ut as formatResourceLine, Va as poisonRenderedSpellingsCollidingIn, Vc as CrossPrefixReadError, Vi as stateSecretNameNeedles, Vl as displayAssemblyPath, Vn as mappingPairs, Vr as reachableDivergentParameters, Vs as refuseMalformedResourcePropertiesForDrift, Wa as resolveDynamicReferences, Wc as crossPrefixDeniedWarning, Wl as resolveAssemblyPath, Wn as proposeRenames, Wo as findReplacedReadersOfRecreateTargets, Wr as displayTextOrWithheld, Ws as repairMalformedResourcePropertiesForReadOnly, Xa as explicitRoleArnOrThrow, Xi as ccRoutedFinalSnapshotError, Xn as settleUnsettledPrevious, Xo as renderStatefulReason, Xr as exportNameNoEchoParameters, Xs as refuseMalformedOrphansForDestroy, Xt as NESTED_PENDING_PARENT_REASON, Ya as assertSendableRoleArn, Yc as isSensitiveAttributeName, Yi as PRE_DELETE_SNAPSHOT_TYPES, Yn as recordAfterRollbackUpdate, Yo as isStatefulRecreateTargetSync, Yr as carriedExportAliasExposure, Ys as refuseMalformedOrphans, Yt as resolvePendingCloudControlRequests, Za as isIamRoleArn, Zc as buildAssetRedirectMap, Zi as ccRoutedInstanceTakesNoSnapshot, Zn as withUnprovenUnsettled, Zr as exportNameSecretExposure, Zs as repairMalformedOrphansForReadOnly, Zt as displacedOpClause, _ as listNestedTemplateRows, _a as withPrintingSecrets, _c as JSON_LISTING_HOLE_VALUE, _i as supersededHolderOf, _l as AssetManifestLoader, _n as makeSiblingClaimReader, _o as cfnRefValueFromPhysicalId, _r as replacementNeverSwapped, _s as refuseMalformedOrphanRecords, a as scanActiveConsumers, aa as ProviderRegistry, ac as refuseMalformedOutputsForDestroy, ai as DEFAULT_RESOURCE_WARN_AFTER_MS, al as rewriteTemplateAssetReferences, an as withNestedRevertRun, ao as classifyReplaySecretRegion, ar as ledgerForStack, b as hasPendingMovesOut, ba as customResourcesFailedWithoutApp, bc as STATE_RESOURCES_MALFORMED, bi as bold, bn as DeploymentEventsStore, bo as refStateLookupFromResource, br as resolveReplacementOldType, bs as repairMalformedOrphanRecordsForReadOnly, c as inheritedProvenanceForChildDiff, ca as wouldReturnToSdkProvider, cc as refuseDivergentRecordRegionForDestroy, ci as destroyStackRecordsView, cl as buildDenyExternalAccessPolicy, cn as withNestedStackContext, d as conditionInputsFrom, da as customResourceResponseExpirationWarning, dc as malformedStateRefusalMessage, dl as getBootstrapMarkerKey, dn as dropFailedHint, dr as demoteSupersededOrphans, ds as deployRefusesOrphanRowsReason, ea as refusesFinalSnapshot, ec as malformedLocalOutputsWarning, ei as collectDeclaredOutputNames, eo as AWS_CREDENTIAL_ENV_KEYS, er as equalModuloMask, f as parentSuppliedValues, fc as refuseMalformedResourcesForDeploy, fi as deleteSupersededEntry, fl as parseBootstrapMarker, fn as isHandledOrphan, fr as isJournaledOrphan, fs as isReadableOrphanRecord, g as isAbsoluteAssetPath, gc as repairMalformedResourcesForReadOnly, gi as supersededHeldByOtherTypeWarning, gl as BOOTSTRAP_MARKER_PREFIX, gn as makeForeignHolderScan, go as AWS_NO_VALUE, gr as recordUnderIdIsNotOwn, gs as previewableOrphanRecords, h as findNestedTemplateTreeDefect, ha as isCustomResourceType$1, hc as refuseMalformedState, hi as supersededAfterRollback, hl as validateContainerRepoName, hn as sameJournaledOrphans, ho as parameterTypeMayLoseSecretIdentity, hr as recheckFailedPlan, hs as malformedOrphanRowsKeptWarning, i as mergeNoChangeOutputs, ia as CC_BROKEN_REASON, ic as refuseMalformedOutputs, ii as DEFAULT_RESOURCE_TIMEOUT_MS, in as revertedNestedRowIds, io as classifyRecordedSecretRegion, is as maskedPropertyFingerprintsOf, j as isProtectionValueActive, ja as RollbackInlinePolicyWriters, ji as createReadOnlyAttributeHealerFactory, jn as hintSidesOf, jo as getAccountInfo, jr as nameGenerationHighWaterOf, js as refuseMalformedResourceEntriesForDestroy, jt as recordRetainedForReadoption, k as recordedProtectionNote, ki as noEchoParameterNamesOf, kn as formatDestructiveChange, kr as orphanNeedsIdentity, ks as refuseMalformedResourceEntries, l as makeCanonicalizePropertiesFn, la as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, lc as malformedRenderedContainersWarning, ll as assertAssetBucketRegion, ln as deleteJournaledOrphans, lr as planRollback, ls as declaresNoEcho, m as childTemplateLoader, ma as readsNoEchoDeleteValues, mc as refuseMalformedResourcesForExport, mi as isSupersededResourceRecord, ml as validateAssetBucketName, mn as loadJournaledOrphans, mo as isUnboundTemplateParameter, mr as planFailedOps, ms as malformedOrphanRecordsWarning, n as isSecretBearingReferenceString, na as createPreDeleteFinalSnapshot, nc as malformedOutputsWarning, ni as isExportAliasCollision, nl as loadPublishableAssetManifest, nn as recordDisplacedSkips, no as callerEnvCredentials, nr as updatePartialMessage, o as inRunStackKey, oa as ccBrokenReason, oc as repairMalformedOutputsForReadOnly, oi as maskingRetryLogger, ol as AssetModeResolver, on as collectNestedChildUnaddressed, oo as producerRegionsFromState, os as parameterInputsFor, p as readRecordedConditionVerdicts, pa as TemplateNoEchoReresolver, pc as refuseMalformedResourcesForDestroy, pi as holdsSupersededResources, pl as readBootstrapMarkerBody, pn as journaledOrphanLines, po as coerceParameterTypedValue, pr as isReplacementOrphan, ps as malformedOrphanRecordsRefusalMessage, qa as applyRoleArnIfSet, qc as stackInstanceIdOf, qi as withSecretPhysicalIdsMaskedInState, qn as replayRollback, qo as MULTI_REGION_RECREATE_BLOCKED_TYPES, qr as secretBearingStateKeyWarning, qs as malformedOrphansRefusalMessage, r as keptWholeReasonText, ra as buildFinalSnapshotIdentifier, ri as bindingSkippedOutputs, ro as envCredentialsAreAssumedRole, rr as updatePartialReason, s as crossStackOutputProvenanceSource, sa as isCustomResource, sc as STATE_REGION_DIVERGED, sl as ensureAssetStorage, sn as getCurrentNestedStackContext, so as regionLessSecretName, sr as withCreateTokenLedger, ss as maskedInputProof, t as DeployEngine, ta as unsupportedFinalSnapshotError, tc as malformedOutputsRefusalMessage, ti as collectPublishedOutputNames, tn as nestedChildStackName$1, to as applyCallerIdentityCredentials, tr as undeclaredEmptyObservedKeys, u as conditionFingerprint, ua as applyCustomResourceResponseExpiration, uc as malformedResourcesWarning, ui as withStackRecords, ul as isCrossRegionRedirect, un as dropFailedCommands, ur as seedsDeleteFirstGuard, us as maskedPropertyFingerprint, v as renderNestedTemplateTreeDefect, va as NO_LOCAL_CUSTOM_RESOURCES_FLAG, vc as accountArgs, vi as supersededResourcesOf, vl as getDockerImageBySourceHash, vn as planOrphanAdoption, vo as isStalePlaceholderArnAttribute, vr as IMPLICIT_DELETE_DEPENDENCIES, vs as refuseMalformedOrphanRecordsForDestroy, w as deferredServiceTokenWarning, wa as setLocalCustomResourceRuntimeEnabled, wc as hasReadableResources, wi as red, wn as noEchoMacParametersOf, wo as keepHeldTokenProvenance, ws as malformedLocalResourceEntriesWarning, x as pendingMovesOutOf, xa as customResourcesRunWithoutApp, xc as UNREADABLE_RESOURCES_MAP_ROW, xi as cyan, xn as NOECHO_MAC_KEY_ALIAS, xr as withPreviousPolicies, xs as unpreviewableOrphanRecords, y as templateIdentity, yc as withheldAccountClause, yi as withoutSuperseded, yn as DeploymentEventsReader, yo as lacksRecordedTableArn, yr as computeImplicitDeleteEdges, ys as refuseMalformedOrphansForOrphan, za as isSelectOutOfBounds, zc as hasUnverifiableParameterRefusal, zn as isPairableType, zo as INTRINSIC_KEYS, zr as computeParameterTaint, zt as macWriteOnlyKeys } from "./deploy-engine-DWLm19jg.js";
10
10
  import { n as canonicalizeRegion, r as derivePartitionAndUrlSuffix, t as PARTITION_TABLE } from "./aws-partition-DA0r2sr-.js";
11
- import { A as parseFailureDebugDetail, E as timePhase, M as utf8ByteLength, O as describeJsonParseFailure, T as renderPhaseTimings, d as getCreateOnlyPropertyPaths, g as describeTypeWithThrottleRetry, m as templateResourceTypes, p as prefetchCreateOnlyPropertyPaths, x as PhaseClock, y as withRetry } from "./ec2-termination-protection-BM1Zt3Fn.js";
12
- import { t as expectedOwnerParam } from "./expected-bucket-owner-CGoY_YS8.js";
11
+ import { A as describeJsonParseFailure, C as PhaseClock, D as renderPhaseTimings, M as parseFailureDebugDetail, O as timePhase, P as utf8ByteLength, d as getCreateOnlyPropertyPaths, g as describeTypeWithThrottleRetry, m as templateResourceTypes, p as prefetchCreateOnlyPropertyPaths, x as withRetry } from "./ec2-termination-protection-BrCiVso0.js";
12
+ import { t as expectedOwnerParam } from "./expected-bucket-owner-IaiC3JwO.js";
13
13
  import { a as acceptedCreateOnlyDropsOf, c as hasReadableExportSet, d as isReadableBag, f as orphansAfterRollback, g as stackInstanceIdCarriedFrom, i as slowCcOperationTimeoutMs, l as importableOutputKeys, m as shouldRetainResource, o as describeRegionValueKind, p as orphansCarriedFrom, s as exportNamesCarriedFrom, u as importableOutputs } from "./delete-started-Co5Gt1jH.js";
14
- import { An as recordProvenPublicExpression, Cn as provenPublicValue, D as recordedNoEchoValuesOf, Dn as recordMaskOnlyValuesIn, En as recordMaskOnlyValue, Fn as isSingleDynamicReferenceToken, Ft as spelledKeysOf, It as pathCrossesDottedKey, Mt as DYNAMIC_REFERENCE_TOKEN_SCAN, Nn as WHOLE_DYNAMIC_REFERENCE_PATTERN, Nt as dynamicReferenceTokens, On as recordNoEchoAttributeValues, Ot as scrubResourceRecord, Pt as isUncertifiedBaselineMaskPosition, Rt as identityKeyFor, T as readsNoEchoSource, W as redactForState, _t as maskSecretsInText, an as physicalNameCopiesOf, at as literalSplitDelimitersOf, b as noEchoOutputsComparison, cn as recordNestedStackParameterExpressions, ct as recordLogOnlyParameterValue, dn as splitGetAttStringForm, dt as shareLogOnlyValues, et as carryLogOnlyValues, f as isMarkedCoordinate, fn as carriesSecretMask, ft as unionOfSecretBags, g as maskedLeafCoordinatesOf, gt as maskSecretsInError, h as maskWholeValue, it as hasMaskableValues, j as liveMatchesUnresolvedTokenFrame, jn as wholeStringLeavesOf, k as valueAtCoordinate, kn as recordNoEchoParameterFreshValue, kt as withPhysicalNameCopies, m as maskReadbackAtCoordinates, mt as errorCauseChain, nt as createUnionSecretMasker, ot as logOnlyValueCount, p as maskAtCoordinates, pt as createSecretMasker, qt as inheritNestedStackParameterAssociations, sn as recordPhysicalNameCopy, st as printingCorpusOf, u as canonicalCoordinates, ut as recordLogOnlyValue, v as noEchoCoordinatesOf, y as noEchoLeavesOf } from "./replacement-rules-01_01yDU.js";
15
- import { D as withoutUnsettledProperties, E as withUnsettledProperties, S as unsettledItemsOf, i as withResourceDeadline, w as unsettledPropertiesOf, x as unsettledItemsField } from "./resource-deadline-TfDpwRQ_.js";
16
- import { a as parseEcrRegistryHost, i as looksLikeEcrHostWithForeignSuffix, n as hasEcrRegistryHostLabels, t as ecrRegistryHostPattern } from "./ecr-uri-C3_6QVgR.js";
14
+ import { An as recordProvenPublicExpression, Cn as provenPublicValue, D as recordedNoEchoValuesOf, Dn as recordMaskOnlyValuesIn, En as recordMaskOnlyValue, Fn as isSingleDynamicReferenceToken, Ft as spelledKeysOf, It as pathCrossesDottedKey, Mt as DYNAMIC_REFERENCE_TOKEN_SCAN, Nn as WHOLE_DYNAMIC_REFERENCE_PATTERN, Nt as dynamicReferenceTokens, On as recordNoEchoAttributeValues, Ot as scrubResourceRecord, Pt as isUncertifiedBaselineMaskPosition, Rt as identityKeyFor, T as readsNoEchoSource, W as redactForState, _t as maskSecretsInText, an as physicalNameCopiesOf, at as literalSplitDelimitersOf, b as noEchoOutputsComparison, cn as recordNestedStackParameterExpressions, ct as recordLogOnlyParameterValue, dn as splitGetAttStringForm, dt as shareLogOnlyValues, et as carryLogOnlyValues, f as isMarkedCoordinate, fn as carriesSecretMask, ft as unionOfSecretBags, g as maskedLeafCoordinatesOf, gt as maskSecretsInError, h as maskWholeValue, it as hasMaskableValues, j as liveMatchesUnresolvedTokenFrame, jn as wholeStringLeavesOf, k as valueAtCoordinate, kn as recordNoEchoParameterFreshValue, kt as withPhysicalNameCopies, m as maskReadbackAtCoordinates, mt as errorCauseChain, nt as createUnionSecretMasker, ot as logOnlyValueCount, p as maskAtCoordinates, pt as createSecretMasker, qt as inheritNestedStackParameterAssociations, sn as recordPhysicalNameCopy, st as printingCorpusOf, u as canonicalCoordinates, ut as recordLogOnlyValue, v as noEchoCoordinatesOf, y as noEchoLeavesOf } from "./replacement-rules-Dpkm5pWN.js";
15
+ import { D as withoutUnsettledProperties, E as withUnsettledProperties, S as unsettledItemsOf, i as withResourceDeadline, w as unsettledPropertiesOf, x as unsettledItemsField } from "./resource-deadline-P1IssiEh.js";
16
+ import { a as parseEcrRegistryHost, i as looksLikeEcrHostWithForeignSuffix, n as hasEcrRegistryHostLabels, t as ecrRegistryHostPattern } from "./ecr-uri-JpCbWN50.js";
17
17
  import { t as cdkdCacheHome } from "./cli.js";
18
18
  import { randomBytes, randomUUID } from "node:crypto";
19
19
  import { CopyObjectCommand, CreateBucketCommand, DeleteBucketCommand, DeleteObjectsCommand, GetBucketLocationCommand, GetObjectCommand, HeadBucketCommand, ListObjectVersionsCommand, ListObjectsV2Command, NoSuchBucket, NotFound, PutBucketEncryptionCommand, PutBucketPolicyCommand, PutBucketVersioningCommand, PutObjectCommand, S3Client, S3ServiceException } from "@aws-sdk/client-s3";
@@ -32,7 +32,7 @@ import { execFile } from "node:child_process";
32
32
  import { devNull, tmpdir } from "node:os";
33
33
  import { CreateAliasCommand, CreateKeyCommand, DescribeKeyCommand, KMSClient, ScheduleKeyDeletionCommand } from "@aws-sdk/client-kms";
34
34
  import { BatchDeleteImageCommand, DeleteRepositoryCommand, DescribeImagesCommand as DescribeImagesCommand$1, ECRClient, GetAuthorizationTokenCommand } from "@aws-sdk/client-ecr";
35
- import { A2A_CONTAINER_PORT, A2A_PATH, AGENTCORE_A2A_PROTOCOL, AGENTCORE_AGUI_PROTOCOL, AGENTCORE_MCP_PROTOCOL, ConnectionRegistry, DEFAULT_AWS_EMULATOR_URL, DynamicReferenceResolver, EMULATOR_SCRUBBED_ENV_KEYS, EcsTaskResolutionError, MCP_CONTAINER_PORT, MCP_PATH, UNNAMED_WORKLOAD, a2aInvokeOnce, addAlbSpecificOptions, addAwsEndpointOptions, addCommonEcsServiceOptions, addImageOverrideOptions, addStartServiceSpecificOptions, albStrategy, applyWorkloadAwsWiringToEnv, attachAuthorizers, attachStageContext, availableApiIdentifiers, awaitLoopbackForwarderStatus, awsEmulatorEnvName, awsEmulatorRealServices, bufferToBody, buildAgentCoreCodeImage, buildCognitoJwksUrl, buildConnectEvent, buildCorsConfigByApiId, buildCorsConfigFromCloudFrontChain, buildDisconnectEvent, buildJwksUrlFromIssuer, buildMessageEvent, buildMgmtEndpointEnvUrl, buildNamespaceOwnerForwarderDockerArgs, buildStageMap, canonicalizeImageOverrideKeys, classifySourceChange, containsDynamicReference, createAuthorizerCache, createFileWatcher, createFileWatcher as createFileWatcher$1, createJwksCache, createMixedModeStateProvider, createWatchPredicates, defaultCredentialsLoader, describeAwsFailureForWarn, describeForwarderFailure, discoverRoutes, discoverWebSocketApis, dockerRegistryEnv, downloadAndExtractS3Bundle, effectiveLoopbackPorts, enforceImageOverrideOrphans, filterRoutesByApiIdentifier, firstUsableRegion, getActiveWorkloadAwsWiring, getAwsEndpointOverride, groupRoutesByServer, groupWorkloadsRoutedApart, handleConnectionsRequest, invokeAgentCore, invokeAgentCoreWs, isAwsServiceRoutedToEmulator, keysNotFromTemplate, keysOverriddenBy, loopbackForwarderPlan, mcpInvokeOnce, noImplicitEcrPullArgs, parseAwsEndpoint, parseConnectionsPath, parseImageOverrideFlags, parseSelectionExpressionPath, pickAgentCoreCandidateStack, pickAgentCoreCandidateStack as pickAgentCoreCandidateStack$1, readAwsEmulatorEnvVarsFile, readEmulatorRunFiles, readEnvVarsFileText, readMtlsMaterialsFromDisk, realAwsServicesOf, resolveAgentCoreTarget, resolveAwsEmulatorOption, resolveDynamicReferencesInEnv, resolveEnvVars, resolveHostDefaultCredentials, resolveImageOverrides, resolveSingleTarget, resolveWatchConfig, resolveWorkloadAwsWiring, runEcsServiceEmulator, runImageOverrideBuilds, setActiveWorkloadAwsWiring, setAwsEndpointOverride, signAgentCoreInvocation, startApiServer, verifyJwtViaDiscovery, waitForAgentCorePing, withoutKeys } from "cdk-local/internal";
35
+ import { A2A_CONTAINER_PORT, A2A_PATH, AGENTCORE_A2A_PROTOCOL, AGENTCORE_AGUI_PROTOCOL, AGENTCORE_MCP_PROTOCOL, ConnectionRegistry, DEFAULT_AWS_EMULATOR_URL, DynamicReferenceResolver, EMULATOR_SCRUBBED_ENV_KEYS, EcsTaskResolutionError, MCP_CONTAINER_PORT, MCP_PATH, UNNAMED_WORKLOAD, a2aInvokeOnce, addAlbSpecificOptions, addAwsEndpointOptions, addCommonEcsServiceOptions, addImageOverrideOptions, addStartServiceSpecificOptions, albStrategy, applyWorkloadAwsWiringToEnv, attachAuthorizers, attachStageContext, availableApiIdentifiers, awaitLoopbackForwarderStatus, awsEmulatorEnvName, awsEmulatorRealServices, awsEmulatorSqsHostBlocks, bufferToBody, buildAgentCoreCodeImage, buildCognitoJwksUrl, buildConnectEvent, buildCorsConfigByApiId, buildCorsConfigFromCloudFrontChain, buildDisconnectEvent, buildJwksUrlFromIssuer, buildMessageEvent, buildMgmtEndpointEnvUrl, buildNamespaceOwnerForwarderDockerArgs, buildStageMap, canonicalizeImageOverrideKeys, classifySourceChange, containsDynamicReference, createAuthorizerCache, createFileWatcher, createFileWatcher as createFileWatcher$1, createJwksCache, createMixedModeStateProvider, createWatchPredicates, defaultCredentialsLoader, describeAwsFailureForWarn, describeForwarderFailure, discoverRoutes, discoverWebSocketApis, dockerRegistryEnv, downloadAndExtractS3Bundle, effectiveLoopbackPorts, enforceImageOverrideOrphans, filterRoutesByApiIdentifier, firstUsableRegion, getActiveWorkloadAwsWiring, getAwsEndpointOverride, groupRoutesByServer, groupWorkloadsRoutedApart, handleConnectionsRequest, invokeAgentCore, invokeAgentCoreWs, isAwsServiceRoutedToEmulator, keysNotFromTemplate, keysOverriddenBy, logMixedModeForWorkload, loopbackForwarderPlan, mcpInvokeOnce, noImplicitEcrPullArgs, parseAwsEndpoint, parseConnectionsPath, parseImageOverrideFlags, parseSelectionExpressionPath, pickAgentCoreCandidateStack, pickAgentCoreCandidateStack as pickAgentCoreCandidateStack$1, readAwsEmulatorEnvVarsFile, readEmulatorRunFiles, readEnvVarsFileText, readMtlsMaterialsFromDisk, realAwsServicesOf, resolveAgentCoreTarget, resolveAwsEmulatorOption, resolveDynamicReferencesInEnv, resolveEnvVars, resolveHostDefaultCredentials, resolveImageOverrides, resolveSingleTarget, resolveWatchConfig, resolveWorkloadAwsWiring, runEcsServiceEmulator, runImageOverrideBuilds, setActiveWorkloadAwsWiring, setAwsEndpointOverride, signAgentCoreInvocation, startApiServer, verifyJwtViaDiscovery, waitForAgentCorePing, withoutKeys } from "cdk-local/internal";
36
36
  import { isDeepStrictEqual, promisify } from "node:util";
37
37
  import graphlib from "graphlib";
38
38
  import { Command, InvalidArgumentError, Option } from "commander";
@@ -61,9 +61,16 @@ async function activateAwsEmulatorForCommand(flag) {
61
61
  const url = endpoint.url;
62
62
  getLogger().info(safeMsg`Using AWS Emulator at ${url} for every AWS call.`);
63
63
  } catch (err) {
64
- throw new CdkdError(err instanceof Error ? err.message : String(err), "AWS_EMULATOR_UNAVAILABLE", err instanceof Error ? err : void 0);
64
+ const message = err instanceof Error ? err.message : String(err);
65
+ throw new CdkdError(message + plainHttpHint(message), "AWS_EMULATOR_UNAVAILABLE", err instanceof Error ? err : void 0);
65
66
  }
66
67
  }
68
+ function plainHttpHint(message) {
69
+ const m = /^--aws-emulator http:\/\/(\S+?): no AWS Emulator answers its health check at \S+ \((HPE_[A-Z_]+)\)/.exec(message);
70
+ if (m === null) return "";
71
+ const httpsUrl = `https://${m[1]}`;
72
+ return safeMsg` The port answered, but not in plain HTTP (${m[2]}): if this port is AWS Emulator, it serves HTTPS, so use --aws-emulator ${httpsUrl}.`;
73
+ }
67
74
 
68
75
  // src/cli/options/aws-emulator.ts
69
76
  function awsEmulatorOption() {
@@ -471,9 +478,12 @@ async function bootstrapDestroyCommand(options) {
471
478
  const stateKeys = await listAllStateKeys(stateBackend);
472
479
  if (stateKeys.length > 0) {
473
480
  const listing = stateKeys.map((k) => ` - ${describeStateKey(k, STATE_FILE_SUFFIX, DEFAULT_STATE_PREFIX)} [${displayIdent(k, { maxCodePoints: STATE_KEY_MAX_CODE_POINTS })}]`).join("\n");
474
- throw new CdkdError(`Refusing to delete state bucket '${bucketName}': ${stateKeys.length} stack(s) still have state in it:\n${listing}\nDestroy every stack ('cdkd destroy' / 'cdkd state destroy') before deleting the state bucket.`, "STATE_BUCKET_NOT_EMPTY");
481
+ throw new CdkdError(`Refusing to delete state bucket '${bucketName}': ${stateKeys.length} stack(s) still have state in it:\n${listing}\nDestroy every stack (${proseQuoted(cdkdRemedy("cdkd destroy"))} / ${proseQuoted(cdkdRemedy("cdkd state destroy"))}) before deleting the state bucket.`, "STATE_BUCKET_NOT_EMPTY");
475
482
  }
476
- if (markerSiblings.otherRegions.length > 0) throw new CdkdError(`Refusing to delete state bucket '${bucketName}': region(s) ${markerSiblings.otherRegions.map((r) => displayIdent(r)).join(", ")} are still opted in to cdkd asset storage (their bootstrap markers live in this bucket). Run 'cdkd bootstrap --destroy --region <r>' for each first.`, "STATE_BUCKET_HOLDS_MARKERS");
483
+ if (markerSiblings.otherRegions.length > 0) throw new CdkdError(`Refusing to delete state bucket '${bucketName}': region(s) ${markerSiblings.otherRegions.map((r) => displayIdent(r)).join(", ")} are still opted in to cdkd asset storage (their bootstrap markers live in this bucket). Run ${pasteableCommand("cdkd bootstrap", [{ literal: "--destroy" }, {
484
+ flag: "--region",
485
+ hole: "r"
486
+ }]).command} for each first.`, "STATE_BUCKET_HOLDS_MARKERS");
477
487
  if (markerSiblings.sameRegionKeys.length > 0) {
478
488
  const canonicalStillPresent = markerBody !== null && resolvedMarkerKey === markerKey;
479
489
  const listing = markerSiblings.sameRegionKeys.map((k, i) => ` ${i + 1}. ${k}`).join("\n");
@@ -629,7 +639,7 @@ async function ensureNoEchoMacKey(args) {
629
639
  return "skipped";
630
640
  }
631
641
  const failed = (step, error) => {
632
- warn(`Could not set up the NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS} in ${region} (${errorName(error)} from ${step}). Deploys keep working: a write-only property a NoEcho parameter feeds is re-sent on every deploy. Re-run 'cdkd bootstrap' with kms:CreateKey, kms:PutKeyPolicy, kms:CreateAlias and kms:DescribeKey to create it.`);
642
+ warn(`Could not set up the NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS} in ${region} (${errorName(error)} from ${step}). Deploys keep working: a write-only property a NoEcho parameter feeds is re-sent on every deploy. Re-run ${proseQuoted(cdkdRemedy("cdkd bootstrap"))} with kms:CreateKey, kms:PutKeyPolicy, kms:CreateAlias and kms:DescribeKey to create it.`);
633
643
  return "failed";
634
644
  };
635
645
  try {
@@ -638,7 +648,7 @@ async function ensureNoEchoMacKey(args) {
638
648
  report(`NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS} already exists`);
639
649
  return "exists";
640
650
  }
641
- warn(`${NOECHO_MAC_KEY_ALIAS} in ${region} does not name an enabled HMAC_256 key (${meta?.KeySpec ?? "unknown spec"}, ${meta?.KeyState ?? "unknown state"}), so deploys make no NoEcho value MACs. Point the alias at an enabled HMAC_256 key, or delete it and re-run 'cdkd bootstrap'.`);
651
+ warn(`${NOECHO_MAC_KEY_ALIAS} in ${region} does not name an enabled HMAC_256 key (${meta?.KeySpec ?? "unknown spec"}, ${meta?.KeyState ?? "unknown state"}), so deploys make no NoEcho value MACs. Point the alias at an enabled HMAC_256 key, or delete it and re-run ${proseQuoted(cdkdRemedy("cdkd bootstrap"))}.`);
642
652
  return "failed";
643
653
  } catch (error) {
644
654
  if (errorName(error) !== "NotFoundException") return failed("kms:DescribeKey", error);
@@ -680,7 +690,7 @@ async function ensureNoEchoMacKey(args) {
680
690
  } catch (describeError) {
681
691
  return failed("kms:DescribeKey", describeError);
682
692
  }
683
- warn(`${NOECHO_MAC_KEY_ALIAS} in ${region} does not name an enabled HMAC_256 key, so deploys make no NoEcho value MACs. Point the alias at an enabled HMAC_256 key, or delete it and re-run 'cdkd bootstrap'.`);
693
+ warn(`${NOECHO_MAC_KEY_ALIAS} in ${region} does not name an enabled HMAC_256 key, so deploys make no NoEcho value MACs. Point the alias at an enabled HMAC_256 key, or delete it and re-run ${proseQuoted(cdkdRemedy("cdkd bootstrap"))}.`);
684
694
  return "failed";
685
695
  }
686
696
  report(`Created the NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS}`);
@@ -1200,7 +1210,7 @@ function createApprovalPrompter(options) {
1200
1210
  return serializePrompt(() => getLiveRenderer().suspendWhile(async () => {
1201
1211
  process.stdout.write(renderApprovalRequest(request));
1202
1212
  return confirmOrRefuse("Do you wish to deploy these changes?", {
1203
- refusal: `Deployment of stack ${displayIdent(request.stackName)} requires approval (--require-approval=${request.level}), but stdin is not interactive. Re-run with --yes to deploy without asking, or review the changes with 'cdkd diff'.`,
1213
+ refusal: `Deployment of stack ${displayIdent(request.stackName)} requires approval (--require-approval=${request.level}), but stdin is not interactive. Re-run with --yes to deploy without asking, or review the changes with ${proseQuoted(cdkdRemedy("cdkd diff"))}.`,
1204
1214
  suffix: " (y/n) "
1205
1215
  });
1206
1216
  }));
@@ -1298,12 +1308,14 @@ function watchCommandInterrupt(opts) {
1298
1308
  return;
1299
1309
  }
1300
1310
  if (interrupted) {
1301
- process.stderr.write("\nForce-quit.\nIf the next run reports a stack lock, release it with: cdkd force-unlock <stack-name>\n");
1311
+ process.stderr.write(`
1312
+ Force-quit.
1313
+ If the next run reports a stack lock, release it with: ${pasteableCommand("cdkd force-unlock", [{ hole: "stack-name" }]).command}\n`);
1302
1314
  process.exit(130);
1303
1315
  }
1304
1316
  markInterrupted();
1305
1317
  if (stacksInFlight > 0) {
1306
- process.stderr.write(`\nInterrupted before ${opts.command} armed its per-stack teardown — quitting now. No delete was issued for this stack; on a multi-stack run, stacks processed earlier are already destroyed.\nIf the next run reports a stack lock, release it with: cdkd force-unlock <stack-name>\n`);
1318
+ process.stderr.write(`\nInterrupted before ${opts.command} armed its per-stack teardown — quitting now. No delete was issued for this stack; on a multi-stack run, stacks processed earlier are already destroyed.\nIf the next run reports a stack lock, release it with: ${pasteableCommand("cdkd force-unlock", [{ hole: "stack-name" }]).command}\n`);
1307
1319
  process.exit(130);
1308
1320
  }
1309
1321
  process.stderr.write(`\nInterrupted — ${opts.command} will stop before starting another stack (press Ctrl-C again to force-quit)...\n`);
@@ -1436,7 +1448,7 @@ function collectCrossStackRefs(node, onRef, unconditional) {
1436
1448
  // src/provisioning/register-providers.ts
1437
1449
  let providerClasses;
1438
1450
  function loadProviderClasses() {
1439
- providerClasses ??= import("./provider-classes-WNwnshId.js");
1451
+ providerClasses ??= import("./provider-classes-B8WD5ucF.js");
1440
1452
  return providerClasses;
1441
1453
  }
1442
1454
  function registerAllProviders(registry, classes) {
@@ -2243,7 +2255,7 @@ async function ensureAwsEmulatorStateBucket(args) {
2243
2255
  await configureStateBucket(setup);
2244
2256
  } catch (error) {
2245
2257
  const msg = error instanceof Error ? error.message : String(error);
2246
- throw new CdkdError(safeMsg`AWS Emulator auto-bootstrap of state bucket ${bucketName} failed: ${msg}. ` + "Run `cdkd bootstrap --aws-emulator --force` to retry.", "AWS_EMULATOR_BOOTSTRAP_FAILED", error instanceof Error ? error : void 0);
2258
+ throw new CdkdError(safeMsg`AWS Emulator auto-bootstrap of state bucket ${bucketName} failed: ${msg}. ` + `Retry with: ${cdkdRemedy("cdkd bootstrap", "--force")}`, "AWS_EMULATOR_BOOTSTRAP_FAILED", error instanceof Error ? error : void 0);
2247
2259
  }
2248
2260
  logger.info(safeMsg`AWS Emulator had no cdkd bootstrap; bootstrapped it (state bucket ${bucketName}).`);
2249
2261
  return bucketName;
@@ -2629,7 +2641,7 @@ async function probeStatefulRecreateTargetsAsync(targets, clients, logger = getL
2629
2641
  let regionVerified = true;
2630
2642
  if (clients.expectedRegionDiverged) {
2631
2643
  regionVerified = false;
2632
- logger.warn(`--recreate-via-cc-api / --recreate-via-sdk-provider: CloudWatch Logs reported ${target.logicalId} (log group ${target.physicalId}) missing, but this stack's state record names a region that is not the one its S3 key holds, so cdkd cannot attribute that not-found to any region — run 'cdkd state show' with --verbose to see what the record claims, and repair it. Re-run with --force-stateful-recreation if the log group really is disposable (that flag clears the data guard for every target in the run). Until then it is treated as NOT provably empty.`);
2644
+ logger.warn(`--recreate-via-cc-api / --recreate-via-sdk-provider: CloudWatch Logs reported ${target.logicalId} (log group ${target.physicalId}) missing, but this stack's state record names a region that is not the one its S3 key holds, so cdkd cannot attribute that not-found to any region — run ${proseQuoted(cdkdRemedy("cdkd state show"))} with --verbose to see what the record claims, and repair it. Re-run with --force-stateful-recreation if the log group really is disposable (that flag clears the data guard for every target in the run). Until then it is treated as NOT provably empty.`);
2633
2645
  }
2634
2646
  const recordedRegion = clients.expectedRegionDiverged ? void 0 : foldRegion(clients.expectedRegion);
2635
2647
  if (recordedRegion) {
@@ -3942,7 +3954,7 @@ async function injectRetainPoliciesRecursiveInternal(templateBody, cfnStackName,
3942
3954
  const r = resource;
3943
3955
  if (r["Type"] !== "AWS::CloudFormation::Stack") continue;
3944
3956
  const childNode = tree.nested.get(logicalId);
3945
- if (!childNode) throw new Error(`Template for '${cfnStackName}' has nested-stack '${logicalId}' (Type: ${NESTED_STACK_RESOURCE_TYPE}) but the CloudFormation resource tree has no matching child entry. AWS may have removed the child since DescribeStackResources ran, or the template was hand-edited mid-flight — re-run \`cdkd import --migrate-from-cloudformation\` to refresh.`);
3957
+ if (!childNode) throw new Error(`Template for '${cfnStackName}' has nested-stack '${logicalId}' (Type: ${NESTED_STACK_RESOURCE_TYPE}) but the CloudFormation resource tree has no matching child entry. AWS may have removed the child since DescribeStackResources ran, or the template was hand-edited mid-flight — re-run ${proseQuoted(cdkdRemedy("cdkd import", "--migrate-from-cloudformation"), "`")} to refresh.`);
3946
3958
  const childTpl = await deps.cfnClient.send(new GetTemplateCommand({
3947
3959
  StackName: childNode.physicalId,
3948
3960
  TemplateStage: "Original"
@@ -4177,7 +4189,7 @@ async function prepareCloudFormationStackRetirement(options) {
4177
4189
  };
4178
4190
  }
4179
4191
  async function confirmPrompt$6(prompt) {
4180
- return confirmOrRefuse(prompt, { refusal: "The CloudFormation stack retirement confirmation prompt cannot run in a non-interactive environment. Pass -y / --yes on cdkd import --migrate-from-cloudformation. Alternatively, run it from a real terminal. Nothing has been written yet: cdkd state and the CloudFormation stack are unchanged, so re-running with -y / --yes is the whole recovery." });
4192
+ return confirmOrRefuse(prompt, { refusal: `The CloudFormation stack retirement confirmation prompt cannot run in a non-interactive environment. Pass -y / --yes on ${cdkdRemedy("cdkd import", "--migrate-from-cloudformation")}. Alternatively, run it from a real terminal. Nothing has been written yet: cdkd state and the CloudFormation stack are unchanged, so re-running with -y / --yes is the whole recovery.` });
4181
4193
  }
4182
4194
 
4183
4195
  // src/cli/commands/retire-cfn-stack/delete-stack.ts
@@ -6201,7 +6213,7 @@ function renderChangeLines(changes, logFn, ccApiRoutes, adoptedOrphans, refactor
6201
6213
  delete: deleteCount
6202
6214
  };
6203
6215
  }
6204
- const REDACTED_LEGACY_PLAINTEXT = "<redacted: may be legacy plaintext in state — run `cdkd scrub`>";
6216
+ const redactedLegacyPlaintext = () => `<redacted: may be legacy plaintext in state — run ${proseQuoted(cdkdRemedy("cdkd scrub"), "`")}>`;
6205
6217
  function stripDisplayOnlyChars(value) {
6206
6218
  return value.replace(/[\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "").replace(/[\u2028\u2029]/g, " ");
6207
6219
  }
@@ -6215,7 +6227,7 @@ function renderOutputChangeLines(outputChanges, logFn) {
6215
6227
  logFn("\n Outputs:");
6216
6228
  const indent = " ";
6217
6229
  const render = (value) => stripDisplayOnlyChars((JSON.stringify(value, null, 2) ?? "undefined").replace(/\n/g, `\n${indent}`));
6218
- const renderOld = (change) => change.oldValueRedacted ? REDACTED_LEGACY_PLAINTEXT : render(change.oldValue);
6230
+ const renderOld = (change) => change.oldValueRedacted ? redactedLegacyPlaintext() : render(change.oldValue);
6219
6231
  for (const change of outputChanges) {
6220
6232
  const exported = change.isExport ? " [export]" : "";
6221
6233
  const name = outputNameRow(change);
@@ -6704,7 +6716,7 @@ async function saveScrubbedState(stateBackend, stackName, region, state, loaded)
6704
6716
  const SCRUB_CLEAN_SCOPE_NOTE = " (scrub checks only values the template names through a {{resolve:...}} reference)";
6705
6717
 
6706
6718
  // src/cli/commands/scrub/nested.ts
6707
- const NESTED_STACK_TYPE$1 = "AWS::CloudFormation::Stack";
6719
+ const NESTED_STACK_TYPE$2 = "AWS::CloudFormation::Stack";
6708
6720
  function readNestedChildTemplate$1(templatePath) {
6709
6721
  let template;
6710
6722
  try {
@@ -6739,7 +6751,7 @@ function nestedChildWorkItem(parent, region, child) {
6739
6751
  const nestedChild = child.refusal !== void 0 ? child : {
6740
6752
  logicalId: child.logicalId,
6741
6753
  stackName: child.stackName,
6742
- refusal: nestedChildRefusal(child.stackName, "the synth output names no template file for its row (Metadata['aws:asset:path']), so scrub has no template to learn its secrets from", "Re-synthesize with a CDK version that emits it, then re-run cdkd scrub.")
6754
+ refusal: nestedChildRefusal(child.stackName, "the synth output names no template file for its row (Metadata['aws:asset:path']), so scrub has no template to learn its secrets from", `Re-synthesize with a CDK version that emits it, then re-run ${cdkdRemedy("cdkd scrub")}.`)
6743
6755
  };
6744
6756
  return {
6745
6757
  stack: {
@@ -7265,7 +7277,7 @@ var ScrubResolvers = class {
7265
7277
  }
7266
7278
  };
7267
7279
  function regionAmbiguousScrubSecretError(origin, stackName, secretName, foreignProducerRegions, stackRegion, secrets) {
7268
- return new ScrubRefusalError(`Scrub of ${displayStackName(stackName)} cannot re-resolve the secret reference ${maskedIdent(secretName, secrets)} in ${origin}: the reference carries no region of its own, and this stack read across a region boundary (producer region(s) on record: ${foreignProducerRegions.map((r) => displayIdent(r)).join(", ")}), so it may have been resolved in one of those rather than in ${displayIdent(stackRegion)}. A secret of the same name in two regions is two independent values, so scrub would look for the WRONG plaintext — leaving the real one in state while reporting the stack clean, and using the foreign value as a needle that can rewrite an unrelated literal. Refusing instead. Spell the reference as a full ARN, which names its region and is resolved there, then re-run 'cdkd scrub'.`, "SCRUB_SECRET_REGION_AMBIGUOUS");
7280
+ return new ScrubRefusalError(`Scrub of ${displayStackName(stackName)} cannot re-resolve the secret reference ${maskedIdent(secretName, secrets)} in ${origin}: the reference carries no region of its own, and this stack read across a region boundary (producer region(s) on record: ${foreignProducerRegions.map((r) => displayIdent(r)).join(", ")}), so it may have been resolved in one of those rather than in ${displayIdent(stackRegion)}. A secret of the same name in two regions is two independent values, so scrub would look for the WRONG plaintext — leaving the real one in state while reporting the stack clean, and using the foreign value as a needle that can rewrite an unrelated literal. Refusing instead. Spell the reference as a full ARN, which names its region and is resolved there, then re-run ${proseQuoted(cdkdRemedy("cdkd scrub"))}.`, "SCRUB_SECRET_REGION_AMBIGUOUS");
7269
7281
  }
7270
7282
  function unresolvableForeignScrubSecretError(origin, stackName, secretName, region, cause, secrets, recorded = false) {
7271
7283
  return new ScrubRefusalError(`Scrub of ${displayStackName(stackName)} could not resolve the secret reference ${maskedIdent(secretName, secrets)} in ${origin} in ${recorded ? "the region its state record names" : "the region its ARN names"} (${displayIdent(region)}): ${maskSecretsInText(describeAwsFailure(cause).detail, secrets)}. Refusing rather than resolving it in the stack's own region, which would look for a different secret's value and report the stack clean over state that still holds the plaintext.`, "SCRUB_CROSS_REGION_SECRET_UNRESOLVED");
@@ -7436,7 +7448,7 @@ function effectiveIntrinsicKey(node) {
7436
7448
  return RESOLVER_INTRINSIC_PRECEDENCE.find((key) => key in node);
7437
7449
  }
7438
7450
  function unresolvableCrossStackReadError(origin, stackName, intrinsic, path, cause, secrets) {
7439
- return new ScrubRefusalError(`Scrub of ${displayStackName(stackName)} could not resolve the ${intrinsic} in ${origin}${path ? ` at ${maskedIdent(path, secrets)}` : ""}: ${maskSecretsInText(describeAwsFailure(cause).detail, secrets)}. Refusing rather than continuing: the value that reference carries may be a secret, and scrub would then have no plaintext to look for — reporting the stack clean over state that still holds it. Deploy the producer stack (or correct the reference) and re-run 'cdkd scrub'.`, "SCRUB_CROSS_STACK_READ_UNRESOLVED");
7451
+ return new ScrubRefusalError(`Scrub of ${displayStackName(stackName)} could not resolve the ${intrinsic} in ${origin}${path ? ` at ${maskedIdent(path, secrets)}` : ""}: ${maskSecretsInText(describeAwsFailure(cause).detail, secrets)}. Refusing rather than continuing: the value that reference carries may be a secret, and scrub would then have no plaintext to look for — reporting the stack clean over state that still holds it. Deploy the producer stack (or correct the reference) and re-run ${proseQuoted(cdkdRemedy("cdkd scrub"))}.`, "SCRUB_CROSS_STACK_READ_UNRESOLVED");
7440
7452
  }
7441
7453
  function scrubRefusalWording(verdict, loggedExportKey, loggedProducerStack, loggedVia, maskedNames = /* @__PURE__ */ new Set()) {
7442
7454
  const chain = dedupePreservingOrder(loggedVia, "first");
@@ -7449,7 +7461,7 @@ function scrubRefusalWording(verdict, loggedExportKey, loggedProducerStack, logg
7449
7461
  const built = scrubOrder.map((name) => scrubCommandFor(name));
7450
7462
  const remedyCommands = built.map((b) => `Scrub with: ${b.command}`);
7451
7463
  const subject = scrubOrder.length > 1 ? "A producer stack name" : "The producer stack name";
7452
- const withheldClause = [...new Set(built.map((b, i) => b.withheld.length > 0 && maskedNames.has(scrubOrder[i]) ? ` ${subject} holds a value recorded as a secret, so it is ` + (proseWithholds(scrubOrder[i]) ? "not shown above and" : "shown masked and") + " is not named in the command below; list the records as stored with 'cdkd state list --long' and act on the record whose stack name matches." : withheldTargetClause(b, "stack", "cdkd scrub", subject)))].join("");
7464
+ const withheldClause = [...new Set(built.map((b, i) => b.withheld.length > 0 && maskedNames.has(scrubOrder[i]) ? ` ${subject} holds a value recorded as a secret, so it is ` + (proseWithholds(scrubOrder[i]) ? "not shown above and" : "shown masked and") + ` is not named in the command below; list the records as stored with ${proseQuoted(cdkdRemedy("cdkd state list", "--long"))} and act on the record whose stack name matches.` : withheldTargetClause(b, "stack", "cdkd scrub", subject)))].join("");
7453
7465
  return {
7454
7466
  templateClaim,
7455
7467
  remedy: scrubOrder.length > 1 ? `Scrub the producers first, from the head of the chain, in the order below` : `Scrub the producer first`,
@@ -7907,7 +7919,7 @@ async function scrubStackResolvePass({ stack, region, logger, newBag, perResourc
7907
7919
  const bagKeys = resolveInput !== null && typeof resolveInput === "object" && !Array.isArray(resolveInput) ? Object.keys(resolveInput) : void 0;
7908
7920
  const intrinsicShapedBag = bagKeys?.some((k) => RESOLVER_DISPATCH_KEYS.has(k)) ?? false;
7909
7921
  const resolveUnits = bagKeys && !intrinsicShapedBag ? Object.entries(resolveInput) : [["", resolveInput]];
7910
- const isNestedRow = templateResource.Type === NESTED_STACK_TYPE$1;
7922
+ const isNestedRow = templateResource.Type === NESTED_STACK_TYPE$2;
7911
7923
  const resolvedRowProps = nullPrototypeRecord();
7912
7924
  if (isNestedRow) nestedRowParameters.set(logicalId, {
7913
7925
  value: void 0,
@@ -7943,7 +7955,7 @@ async function scrubStackResolvePass({ stack, region, logger, newBag, perResourc
7943
7955
  }
7944
7956
  perResourceTemplateProps.set(logicalId, templateResource.Properties);
7945
7957
  const nestedParameters = nestedRowParameters.get(logicalId);
7946
- if (isNestedRow && nestedParameters?.complete === true) recordNestedStackParameterExpressions(recordedSecretValues, NESTED_STACK_TYPE$1, resolvedRowProps, templateResource.Properties);
7958
+ if (isNestedRow && nestedParameters?.complete === true) recordNestedStackParameterExpressions(recordedSecretValues, NESTED_STACK_TYPE$2, resolvedRowProps, templateResource.Properties);
7947
7959
  }
7948
7960
  for (const [orphanIndex, record] of (state.orphans ?? []).entries()) {
7949
7961
  const recordedSecretValues = newBag();
@@ -8372,13 +8384,13 @@ async function scrubStackRewritePass({ stack, region, stateBackend, opts, logger
8372
8384
  continue;
8373
8385
  }
8374
8386
  if (!Object.hasOwn(state.resources ?? {}, logicalId)) {
8375
- refuse(`${shownStack}'s state has no record of the nested-stack row that deploys it, so the parameters it was deployed with are unknown`, `Deploy ${shownStack} so it records the row, then re-run cdkd scrub; if its Condition keeps the row out of the deploy, the child record is left over — remove it with cdkd state destroy.`);
8387
+ refuse(`${shownStack}'s state has no record of the nested-stack row that deploys it, so the parameters it was deployed with are unknown`, `Deploy ${shownStack} so it records the row, then re-run ${cdkdRemedy("cdkd scrub")}; if its Condition keeps the row out of the deploy, the child record is left over — remove it with ${cdkdRemedy("cdkd state destroy")}.`);
8376
8388
  continue;
8377
8389
  }
8378
8390
  const resolved = nestedRowParameters.get(logicalId);
8379
8391
  const parameters = resolved?.complete === true ? nestedChildParameters(resolved.value) : void 0;
8380
8392
  if (parameters === void 0) {
8381
- refuse(`the Parameters ${shownStack} passes it could not be resolved to the values a deploy would hand it, so what it inherited is unknown`, verboseAwareText("Re-run cdkd scrub with --verbose to see which value failed to resolve, and fix that.", "The debug output above shows which value failed to resolve; fix that."));
8393
+ refuse(`the Parameters ${shownStack} passes it could not be resolved to the values a deploy would hand it, so what it inherited is unknown`, verboseAwareText(`Re-run ${cdkdRemedy("cdkd scrub")} with --verbose to see which value failed to resolve, and fix that.`, "The debug output above shows which value failed to resolve; fix that."));
8382
8394
  continue;
8383
8395
  }
8384
8396
  nestedChildren.push({
@@ -8592,14 +8604,14 @@ async function scrubStackRewritePass({ stack, region, stateBackend, opts, logger
8592
8604
  readers = findDroppedOutputReaders(stack.stackName, region, dropping, await (opts.readConsumerRecords ?? (() => readConsumerRecords(stateBackend, region)))());
8593
8605
  } catch (err) {
8594
8606
  droppedOutputReadersUnverified = true;
8595
- logger.warn(safeMsg`${shownStack}'s template no longer declares output key(s) ${shownKeys(dropping)}, ` + `but the other stacks' state could not be read to confirm none of them still ` + safeMsg`reads one (${maskSecretsInText(describeAwsFailure(err).detail, corpus)}), ` + "so NONE was dropped and this stack is not reported clean. Fix the read and re-run cdkd scrub.");
8607
+ logger.warn(safeMsg`${shownStack}'s template no longer declares output key(s) ${shownKeys(dropping)}, ` + `but the other stacks' state could not be read to confirm none of them still ` + safeMsg`reads one (${maskSecretsInText(describeAwsFailure(err).detail, corpus)}), ` + `so NONE was dropped and this stack is not reported clean. Fix the read and ` + safeMsg`re-run ${cdkdRemedy("cdkd scrub")}.`);
8596
8608
  dropping = /* @__PURE__ */ new Set();
8597
8609
  }
8598
8610
  if (readers !== void 0 && readers.length > 0) {
8599
8611
  const read = readers.some((r) => r.key === void 0) ? new Set(dropping) : new Set(readers.map((r) => r.key));
8600
8612
  keptReadOutputKeys = read.size;
8601
8613
  const lines = readers.map((r) => safeMsg`${displayStackName(maskSecretsInText(r.consumerStack, corpus))} (${displayIdent(r.consumerRegion)}) ` + (r.key === void 0 ? r.legacy ? `records no ${r.intrinsic} reads (written before cdkd recorded them), so it may read one` : r.damaged ? `reads an entry whose name is not a string (a damaged record), which cannot be compared, via ${r.intrinsic}` : `reads a name stored redacted, which cannot be compared, via ${r.intrinsic}` : safeMsg`reads ${shownKeys([r.key])} via ${r.intrinsic}`));
8602
- logger.warn(safeMsg`${shownStack}'s template no longer declares output key(s) ${shownKeys(read)}, ` + safeMsg`but another stack still reads them: ${lines.join("; ")}. They were NOT ` + "dropped, since that read would break, and this stack is not reported clean: a value left beside the references scrub writes can be printed by cdkd diff. Stop the consumer reading it (or declare the output again), or redeploy a consumer whose record predates the reads, then re-run cdkd scrub.");
8614
+ logger.warn(safeMsg`${shownStack}'s template no longer declares output key(s) ${shownKeys(read)}, ` + safeMsg`but another stack still reads them: ${lines.join("; ")}. They were NOT ` + "dropped, since that read would break, and this stack is not reported clean: a value left beside the references scrub writes can be printed by cdkd diff. Stop the consumer reading it (or declare the output again), or redeploy a " + safeMsg`consumer whose record predates the reads, then re-run ${cdkdRemedy("cdkd scrub")}.`);
8603
8615
  dropping = new Set([...dropping].filter((key) => !read.has(key)));
8604
8616
  }
8605
8617
  }
@@ -9013,7 +9025,7 @@ async function runScrubTargets({ options, logger, effectiveRegion, region, state
9013
9025
  logger.error(`Scrub of ${shownStack} failed: ${describeFailure(err)}`);
9014
9026
  if (err instanceof Error && err.stack) logger.debug("Stack trace:", err.stack);
9015
9027
  try {
9016
- work.splice(workIndex + 1, 0, ...unreachedNestedRecords((await listStateRefs()).filter((ref) => !appStackNames.has(ref.stackName)), stackName, stackRegion, [], `the scrub of ${shownStack}, which deploys it, failed, so its inputs are unknown`, `Fix the failure reported for ${shownStack} and re-run cdkd scrub.`).map((child) => nestedChildWorkItem({
9028
+ work.splice(workIndex + 1, 0, ...unreachedNestedRecords((await listStateRefs()).filter((ref) => !appStackNames.has(ref.stackName)), stackName, stackRegion, [], `the scrub of ${shownStack}, which deploys it, failed, so its inputs are unknown`, `Fix the failure reported for ${shownStack} and re-run ${cdkdRemedy("cdkd scrub")}.`).map((child) => nestedChildWorkItem({
9017
9029
  stackName,
9018
9030
  displayName: stackName,
9019
9031
  artifactId: stackName,
@@ -9025,7 +9037,7 @@ async function runScrubTargets({ options, logger, effectiveRegion, region, state
9025
9037
  }
9026
9038
  let unreached;
9027
9039
  try {
9028
- unreached = unreachedNestedRecords((await listStateRefs()).filter((ref) => !appStackNames.has(ref.stackName)), stackName, stackRegion, scrubbed.nestedChildren, scrubbed.noRecord ? `${shownStack} has no state record, so no row records the parameters it was deployed with` : `no nested-stack row in ${shownStack}'s template or state record reaches it, so scrub has no template to learn its secrets from`, "Inspect it with cdkd state show; if it is left over, remove it with cdkd state destroy (resources) or cdkd state orphan (record only).");
9040
+ unreached = unreachedNestedRecords((await listStateRefs()).filter((ref) => !appStackNames.has(ref.stackName)), stackName, stackRegion, scrubbed.nestedChildren, scrubbed.noRecord ? `${shownStack} has no state record, so no row records the parameters it was deployed with` : `no nested-stack row in ${shownStack}'s template or state record reaches it, so scrub has no template to learn its secrets from`, `Inspect it with ${cdkdRemedy("cdkd state show")}; if it is left over, remove it with ${cdkdRemedy("cdkd state destroy")} (resources) or ${cdkdRemedy("cdkd state orphan")} (record only).`);
9029
9041
  } catch (err) {
9030
9042
  failures.push({ stackName: `${stackName}~*` });
9031
9043
  logger.error(safeMsg`Scrub of the nested stacks under ${shownStack} failed: their state records could not be listed, so any record no template row reaches was not examined: ${describeFailure(err)}`);
@@ -9511,7 +9523,7 @@ function incompleteRemediationMessage(reports, mode) {
9511
9523
  return [
9512
9524
  `Comparison INCOMPLETE — nothing to ${mode}, and that is NOT a clean bill of health: ${uncompared} of ${total} resource(s) could not be compared.`,
9513
9525
  ...groups,
9514
- `Re-run 'cdkd drift' without --${mode} to see which resources and why — a detection-only run exits 2 while a comparison is incomplete.`
9526
+ `Re-run ${proseQuoted(cdkdRemedy("cdkd drift"))} without --${mode} to see which resources and why — a detection-only run exits 2 while a comparison is incomplete.`
9515
9527
  ];
9516
9528
  }
9517
9529
 
@@ -9640,7 +9652,7 @@ function isDriftSecretRefusal(err) {
9640
9652
  }
9641
9653
  function regionAmbiguousDriftSecretError(logicalId, propertyPath, secretName, foreignProducerRegions, consumerRegion) {
9642
9654
  const where = propertyPath === "" ? "" : ` property '${propertyPath}'`;
9643
- return new DriftSecretRefusalError(`${logicalId}${where}: the secret reference '${secretName}' carries no region of its own, and this stack read across a region boundary (producer region(s) on record: ${foreignProducerRegions.join(", ")}), so it may have been resolved in one of those rather than in '${consumerRegion}'. A secret of the same name in two regions is two independent values, so cdkd would compare against — and with --revert WRITE — the WRONG secret. Refusing instead. Spell the reference as a full ARN, which names its region and is resolved there, then re-run 'cdkd drift'.`, "DRIFT_SECRET_REGION_AMBIGUOUS");
9655
+ return new DriftSecretRefusalError(`${logicalId}${where}: the secret reference '${secretName}' carries no region of its own, and this stack read across a region boundary (producer region(s) on record: ${foreignProducerRegions.join(", ")}), so it may have been resolved in one of those rather than in '${consumerRegion}'. A secret of the same name in two regions is two independent values, so cdkd would compare against — and with --revert WRITE — the WRONG secret. Refusing instead. Spell the reference as a full ARN, which names its region and is resolved there, then re-run ${proseQuoted(cdkdRemedy("cdkd drift"))}.`, "DRIFT_SECRET_REGION_AMBIGUOUS");
9644
9656
  }
9645
9657
  function refuseUnprovenDriftSecret(leaf, propertyPath, logicalId, consumerRegion, evidence, recordedRegions) {
9646
9658
  if (evidence.complete) return;
@@ -9649,7 +9661,7 @@ function refuseUnprovenDriftSecret(leaf, propertyPath, logicalId, consumerRegion
9649
9661
  const name = classifyReplaySecretRegion(token, consumerRegion, evidence.regions).kind === "local" ? regionLessSecretName(token) : void 0;
9650
9662
  if (name === void 0) continue;
9651
9663
  const where = propertyPath === "" ? "" : ` property '${propertyPath}'`;
9652
- throw new DriftSecretRefusalError(`${logicalId}${where}: the secret reference '${name}' carries no region of its own, and this is a nested stack whose parent stacks' cross-region reads could not be established, so a parent may have resolved it in another region than '${consumerRegion}'. A secret of the same name in two regions is two independent values, so cdkd would compare against — and with --revert WRITE — the WRONG secret. Refusing instead. Make the parent stacks' state readable (or repair a record whose parent link disagrees with its key), or spell the reference as a full ARN, then re-run 'cdkd drift'.`, "DRIFT_SECRET_REGION_UNKNOWN");
9664
+ throw new DriftSecretRefusalError(`${logicalId}${where}: the secret reference '${name}' carries no region of its own, and this is a nested stack whose parent stacks' cross-region reads could not be established, so a parent may have resolved it in another region than '${consumerRegion}'. A secret of the same name in two regions is two independent values, so cdkd would compare against — and with --revert WRITE — the WRONG secret. Refusing instead. Make the parent stacks' state readable (or repair a record whose parent link disagrees with its key), or spell the reference as a full ARN, then re-run ${proseQuoted(cdkdRemedy("cdkd drift"))}.`, "DRIFT_SECRET_REGION_UNKNOWN");
9653
9665
  }
9654
9666
  }
9655
9667
  function noteUnreadableAncestor(stackName, region, why) {
@@ -9750,10 +9762,22 @@ async function resolveStateSecretExpressions(props, resolvers, secrets, options)
9750
9762
  }
9751
9763
 
9752
9764
  // src/cli/commands/refused-baseline-remedy.ts
9753
- const ACCEPT_REFUSED_REMEDY = "Once the deployed template no longer reads a parameter at this resource, cdkd state refresh-observed '<stack>' --accept-refused '<logicalId>' --template '<file>' records a baseline on your assertion that AWS holds no secret the template does not spell as a dynamic reference.";
9765
+ function acceptRefusedRemedy() {
9766
+ return `Once the deployed template no longer reads a parameter at this resource, ${pasteableCommand("cdkd state refresh-observed", [
9767
+ { hole: "stack" },
9768
+ {
9769
+ flag: "--accept-refused",
9770
+ hole: "logicalId"
9771
+ },
9772
+ {
9773
+ flag: "--template",
9774
+ hole: "file"
9775
+ }
9776
+ ]).command} records a baseline on your assertion that AWS holds no secret the template does not spell as a dynamic reference.`;
9777
+ }
9754
9778
  function refusedBaselineRemedy(record) {
9755
- if (hasUnverifiableParameterRefusal(record)) return "Deploying a change does NOT clear this refusal: the resource reads a template parameter whose deployed value cdkd could not prove, so only a deploy that replaces the resource, or a re-import while a CloudFormation stack can prove that value, restores a baseline. " + ACCEPT_REFUSED_REMEDY;
9756
- if (hasReasonlessBaselineRefusal(record)) return "This refusal was recorded without a reason this cdkd recognizes: a deploy that actually CHANGES this resource restores a baseline unless the resource reads a template parameter, and then only a deploy that replaces the resource, or a re-import while a CloudFormation stack can prove the parameter's deployed value, does. " + ACCEPT_REFUSED_REMEDY;
9779
+ if (hasUnverifiableParameterRefusal(record)) return "Deploying a change does NOT clear this refusal: the resource reads a template parameter whose deployed value cdkd could not prove, so only a deploy that replaces the resource, or a re-import while a CloudFormation stack can prove that value, restores a baseline. " + acceptRefusedRemedy();
9780
+ if (hasReasonlessBaselineRefusal(record)) return "This refusal was recorded without a reason this cdkd recognizes: a deploy that actually CHANGES this resource restores a baseline unless the resource reads a template parameter, and then only a deploy that replaces the resource, or a re-import while a CloudFormation stack can prove the parameter's deployed value, does. " + acceptRefusedRemedy();
9757
9781
  }
9758
9782
 
9759
9783
  // src/cli/commands/drift/redaction.ts
@@ -10535,7 +10559,7 @@ async function runAccept(reports, regionScope, stateBackend, stateConfig, awsCli
10535
10559
  const refusal = acceptRefusalReason(change, outcome.maskedPaths);
10536
10560
  if (refusal !== void 0) {
10537
10561
  const revert = revertCommandLine(report.stackName, report.region);
10538
- logger.warn(` ! ${report.stackName}/${outcome.logicalId} (${outcome.resourceType}): not accepting '${displayDriftPath(outcome, change.path)}' — ${refusal}, so cdkd will not write it to ` + (revert === void 0 ? "state. Run 'cdkd drift --revert' for this stack to push the referenced value back to AWS, or re-deploy if the reference changed." : `state. Push the referenced value back to AWS with the command below, or re-deploy if the reference changed.\nRevert with: ${revert}`));
10562
+ logger.warn(` ! ${report.stackName}/${outcome.logicalId} (${outcome.resourceType}): not accepting '${displayDriftPath(outcome, change.path)}' — ${refusal}, so cdkd will not write it to ` + (revert === void 0 ? `state. Run ${proseQuoted(cdkdRemedy("cdkd drift", "--revert"))} for this stack to push the referenced value back to AWS, or re-deploy if the reference changed.` : `state. Push the referenced value back to AWS with the command below, or re-deploy if the reference changed.\nRevert with: ${revert}`));
10539
10563
  continue;
10540
10564
  }
10541
10565
  setAtPath(newBaseline, change.path, change.awsValue);
@@ -11132,7 +11156,7 @@ function warnIfPreV10BaselineGap(state, outcomes, logger) {
11132
11156
  if (affected.length === 0) return [];
11133
11157
  const shown = affected.slice(0, 10).join(", ");
11134
11158
  const rest = affected.length > 10 ? `, and ${affected.length - 10} more` : "";
11135
- const finding = `${state.stackName} (${state.region ?? "unknown region"}): this stack's state predates cdkd's refused-baseline marker (schema v${state.version ?? 1}; the marker arrived in v${10}), and ${affected.length} of its compared resource(s) have no drift baseline: ${shown}${rest}. If any were adopted by 'cdkd import' and that import REFUSED to capture a baseline, cdkd cannot tell — so it compares them against their recorded properties, which can hold a placeholder the deployed stack never used and can surface a live secret in this report. Re-run 'cdkd import' for this stack to put the record right.`;
11159
+ const finding = `${state.stackName} (${state.region ?? "unknown region"}): this stack's state predates cdkd's refused-baseline marker (schema v${state.version ?? 1}; the marker arrived in v${10}), and ${affected.length} of its compared resource(s) have no drift baseline: ${shown}${rest}. If any were adopted by 'cdkd import' and that import REFUSED to capture a baseline, cdkd cannot tell — so it compares them against their recorded properties, which can hold a placeholder the deployed stack never used and can surface a live secret in this report. Re-run ${proseQuoted(cdkdRemedy("cdkd import"))} for this stack to put the record right.`;
11136
11160
  const note = " Note: ANY write to this stack's state — including this run's --accept / --revert, or a deploy that changes nothing about the resources above — re-stamps it at the current schema version and SILENCES this warning without fixing those records. Only a re-import, or a deploy that actually CHANGES a listed resource, repairs one — and the deploy only when that resource reads no template parameter, since a deploy binds the same parameter Default the import did.";
11137
11161
  logger.warn(finding);
11138
11162
  logger.warn(note);
@@ -11173,7 +11197,7 @@ function canonicalizeDerivedPatternBName(resourceType, baseline, aws) {
11173
11197
  // src/cli/commands/drift/detect.ts
11174
11198
  async function runDriftForStack(stackName, region, stateBackend, providerRegistry, ccApiFallback, resolvePrincipalUniqueId, malformedRecordMode, nestedChildRecord, refusalRecovery) {
11175
11199
  const result = await stateBackend.getState(stackName, region);
11176
- if (!result) throw new Error(`No state found for stack '${stackName}' (${region}). Run 'cdkd state list' to see available stacks.`);
11200
+ if (!result) throw new Error(`No state found for stack '${stackName}' (${region}). Run ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
11177
11201
  const namingScope = nameScopeOf(stackName, stackInstanceIdOf(result.state, displayStackName(stackName)), result.state);
11178
11202
  return await withStackScope(namingScope, async () => {
11179
11203
  const outcomes = [];
@@ -11549,7 +11573,7 @@ async function revertDriftedOutcome(args) {
11549
11573
  const intrinsicObjectPaths = collectUnresolvedIntrinsicObjectPaths(desiredProperties, driftedTopLevelKeys);
11550
11574
  if (intrinsicObjectPaths.length > 0) {
11551
11575
  tally.totalUnresolvable++;
11552
- logger.error(` ✗ ${report.stackName}/${outcome.logicalId} (${outcome.resourceType}): refused to revert ${maskSecretsInText(intrinsicObjectPaths.join(", "), secrets)} — the recorded baseline holds an unresolved CloudFormation intrinsic there (e.g. Fn::Join, Ref), which cdkd cannot resolve outside a deploy; writing it would set the live property to the raw intrinsic object instead of its value. Run 'cdkd deploy' for this stack — the deploy resolves the template and records a resolvable baseline — then re-run the revert if drift remains.`);
11576
+ logger.error(` ✗ ${report.stackName}/${outcome.logicalId} (${outcome.resourceType}): refused to revert ${maskSecretsInText(intrinsicObjectPaths.join(", "), secrets)} — the recorded baseline holds an unresolved CloudFormation intrinsic there (e.g. Fn::Join, Ref), which cdkd cannot resolve outside a deploy; writing it would set the live property to the raw intrinsic object instead of its value. Run ${proseQuoted(cdkdRemedy("cdkd deploy"))} for this stack — the deploy resolves the template and records a resolvable baseline — then re-run the revert if drift remains.`);
11553
11577
  return;
11554
11578
  }
11555
11579
  }
@@ -11745,7 +11769,7 @@ async function runRevert(reports, regionScope, stateBackend, stateConfig, awsCli
11745
11769
  ...reRecordedCount > 0 ? ["the identity the revert returned"] : [],
11746
11770
  ...settledCount > 0 ? ["that a failed deploy's unsettled properties are settled"] : []
11747
11771
  ].join(" and ");
11748
- logger.warn(`Reverted ${report.stackName} (${report.region}), but could not record ${unrecorded}: ${describeAwsFailure(err).detail}.` + (reRecordedCount > 0 ? " The state record still holds the physical id and attributes from before the revert, which a later 'Fn::GetAtt' and 'cdkd export' read. Re-running the revert does not repair it, since the revert landed; a later deploy that updates this resource records the identity its update returns." : "") + (recordedCount > 0 ? ` The next 'cdkd drift' will report the same difference — ` + (revertAgain === void 0 ? `re-run 'cdkd drift --revert' for this stack once the state write can succeed.` : `re-run the command below once the state write can succeed.\nRevert with: ${revertAgain}`) : ""));
11772
+ logger.warn(`Reverted ${report.stackName} (${report.region}), but could not record ${unrecorded}: ${describeAwsFailure(err).detail}.` + (reRecordedCount > 0 ? " The state record still holds the physical id and attributes from before the revert, which a later 'Fn::GetAtt' and 'cdkd export' read. Re-running the revert does not repair it, since the revert landed; a later deploy that updates this resource records the identity its update returns." : "") + (recordedCount > 0 ? ` The next 'cdkd drift' will report the same difference — ` + (revertAgain === void 0 ? `re-run ${proseQuoted(cdkdRemedy("cdkd drift", "--revert"))} for this stack once the state write can succeed.` : `re-run the command below once the state write can succeed.\nRevert with: ${revertAgain}`) : ""));
11749
11773
  }
11750
11774
  }
11751
11775
  } finally {
@@ -11761,8 +11785,8 @@ async function runRevert(reports, regionScope, stateBackend, stateConfig, awsCli
11761
11785
  if (totalUnresolvable > 0) summaryParts.push(`${totalUnresolvable} reference-unresolvable`);
11762
11786
  if (totalFailed > 0) summaryParts.push(`${totalFailed} failed`);
11763
11787
  logger.info(`\nRevert summary: ${summaryParts.join(", ")}.`);
11764
- if (totalUnsupported > 0) logger.warn(`${totalUnsupported} resource(s) cannot be reverted in place — re-deploy the stack with cdkd deploy --replace, or destroy + redeploy to push the cdkd-state values back into AWS.`);
11765
- if (totalFailed > 0 || totalUnsupported > 0 || totalUnresolvable > 0) throw new PartialFailureError(`Revert completed with ${totalFailed + totalUnsupported + totalUnresolvable} resource error(s) (${totalFailed} AWS update failure(s), ${totalUnsupported} update-not-supported, ${totalUnresolvable} refused or unresolvable — those never reached provider.update; each per-resource message above names its cause and remedy, e.g. missing secretsmanager:GetSecretValue / ssm:GetParameter grants for an unresolvable reference). Re-run cdkd drift ${commandHole("stacks...")} to see the remaining drift, then cdkd drift ${commandHole("stacks...")} --revert to retry.`);
11788
+ if (totalUnsupported > 0) logger.warn(`${totalUnsupported} resource(s) cannot be reverted in place — re-deploy the stack with ${deployReplaceCommand()}, or destroy + redeploy to push the cdkd-state values back into AWS.`);
11789
+ if (totalFailed > 0 || totalUnsupported > 0 || totalUnresolvable > 0) throw new PartialFailureError(`Revert completed with ${totalFailed + totalUnsupported + totalUnresolvable} resource error(s) (${totalFailed} AWS update failure(s), ${totalUnsupported} update-not-supported, ${totalUnresolvable} refused or unresolvable — those never reached provider.update; each per-resource message above names its cause and remedy, e.g. missing secretsmanager:GetSecretValue / ssm:GetParameter grants for an unresolvable reference). Re-run ${pasteableCommand("cdkd drift", [{ hole: "stacks..." }]).command} to see the remaining drift, then ${pasteableCommand("cdkd drift", [{ hole: "stacks..." }, { literal: "--revert" }]).command} to retry.`);
11766
11790
  }
11767
11791
 
11768
11792
  // src/cli/commands/drift/command.ts
@@ -11882,7 +11906,7 @@ async function driftCommand(stacks, options) {
11882
11906
  if (anyRefusedDeleted) {
11883
11907
  if (anyIncomplete) {
11884
11908
  for (const line of incompleteRemediationMessage(reports, mode).slice(0, -1)) logger.info(line);
11885
- logger.info(safeMsg`Re-run 'cdkd drift' without --${mode} to see which resources and why — ` + `with a deleted resource in the stack, that run exits 1.`);
11909
+ logger.info(safeMsg`Re-run ${proseQuoted(cdkdRemedy("cdkd drift"))} without --${mode} to see which resources and why — ` + `with a deleted resource in the stack, that run exits 1.`);
11886
11910
  }
11887
11911
  if (!options.dryRun) throw deletedRefusalError(refusedDeleted, mode);
11888
11912
  return;
@@ -11917,7 +11941,7 @@ function refuseDeletedForRemediation(reports, mode, logger) {
11917
11941
  if (outcome.kind !== "deleted") continue;
11918
11942
  if (outcome.nestedStackRecordMissing === true) {
11919
11943
  refused.recordMissing += 1;
11920
- logger.warn(safeMsg` ! ${reportHeading(report)} ${reportResource(outcome)}: NOT ` + (mode === "revert" ? "reverted" : "accepted") + safeMsg` — ${nestedRecordMissingClause(report, outcome)} ${NESTED_RECORD_MISSING_REMEDY}`);
11944
+ logger.warn(safeMsg` ! ${reportHeading(report)} ${reportResource(outcome)}: NOT ` + (mode === "revert" ? "reverted" : "accepted") + safeMsg` — ${nestedRecordMissingClause(report, outcome)} ${nestedRecordMissingRemedy()}`);
11921
11945
  continue;
11922
11946
  }
11923
11947
  logger.warn(safeMsg` ! ${reportHeading(report)} ${reportResource(outcome)}: NOT ` + (mode === "revert" ? "reverted — AWS reports this resource no longer exists (deleted outside cdkd), and --revert updates a resource in place: it cannot recreate one." : "accepted — AWS reports this resource no longer exists (deleted outside cdkd), so there is no AWS-current value to write to state.") + safeMsg` ${DELETED_RESOURCE_REMEDY}`);
@@ -11930,7 +11954,7 @@ function deletedRefusalError({ deleted, recordMissing }, mode) {
11930
11954
  const parts = [...deleted > 0 ? [`${deleted} resource(s) deleted outside cdkd`] : [], ...recordMissing > 0 ? [`${recordMissing} nested stack(s) whose state record is gone`] : []];
11931
11955
  return new PartialFailureError(`${parts.join(" and ")} were not ${verb}; each is named above.`);
11932
11956
  }
11933
- const NESTED_RECORD_MISSING_REMEDY = "If the parent was imported with 'cdkd import --migrate-from-cloudformation' and that import stopped part-way, its nested stacks were not recorded yet: re-run that import with --force, which rebuilds the parent record from the stack and then records them. Otherwise the resources the nested stack held are no longer tracked by cdkd and may still exist in AWS, and recreating it can collide with them. A deploy that does not change the nested stack will not recreate it: to recreate it, remove it from the CDK app and deploy, then restore it and deploy again; if it is meant to be gone, the first of those deploys is enough.";
11957
+ const nestedRecordMissingRemedy = () => `If the parent was imported with ${proseQuoted(cdkdRemedy("cdkd import", "--migrate-from-cloudformation"))} and that import stopped part-way, its nested stacks were not recorded yet: re-run that import with --force, which rebuilds the parent record from the stack and then records them. Otherwise the resources the nested stack held are no longer tracked by cdkd and may still exist in AWS, and recreating it can collide with them. A deploy that does not change the nested stack will not recreate it: to recreate it, remove it from the CDK app and deploy, then restore it and deploy again; if it is meant to be gone, the first of those deploys is enough.`;
11934
11958
  function nestedRecordMissingClause(report, outcome) {
11935
11959
  return safeMsg`its nested stack's own state record ${reportIdent(nestedChildStackName(report.stackName, outcome.logicalId), STACK_REF_MAX_CODE_POINTS)} is not in state.`;
11936
11960
  }
@@ -11972,7 +11996,7 @@ function resolveTargetRefs(stacks, stateRefs, options) {
11972
11996
  }
11973
11997
  if (stacks.length === 0) {
11974
11998
  const candidates = options.stackRegion ? stateRefs.filter((r) => r.region === options.stackRegion) : stateRefs;
11975
- if (candidates.length === 0) throw new Error("No stacks found in state bucket. Run `cdkd deploy` first, or pass --all explicitly.");
11999
+ if (candidates.length === 0) throw new Error(`No stacks found in state bucket. Run ${proseQuoted(cdkdRemedy("cdkd deploy"), "`")} first, or pass --all explicitly.`);
11976
12000
  const roots = candidates.filter((r) => !candidates.some((a) => a !== r && isNestedDescendantOf(r, a)));
11977
12001
  if (roots.length === 1) return withNestedDescendants([roots[0]], candidates);
11978
12002
  const listing = roots.map((r) => `${r.stackName}${r.region ? ` (${r.region})` : ""}`).join(", ");
@@ -11981,7 +12005,7 @@ function resolveTargetRefs(stacks, stateRefs, options) {
11981
12005
  const out = [];
11982
12006
  for (const stackName of stacks) {
11983
12007
  const matches = stateRefs.filter((r) => r.stackName === stackName);
11984
- if (matches.length === 0) throw new Error(`No state found for stack '${stackName}'. Run 'cdkd state list' to see available stacks.`);
12008
+ if (matches.length === 0) throw new Error(`No state found for stack '${stackName}'. Run ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
11985
12009
  if (options.stackRegion) {
11986
12010
  const ref = matches.find((r) => r.region === options.stackRegion);
11987
12011
  if (!ref) {
@@ -12040,7 +12064,7 @@ function createIamPrincipalUniqueIdResolver(awsClients) {
12040
12064
 
12041
12065
  // src/cli/commands/drift.ts
12042
12066
  function createDriftCommand() {
12043
- const cmd = new Command("drift").description("Detect drift between cdkd state and AWS reality. Exits 0 when nothing drifted, 1 when drift is detected, and 2 when nothing drifted but cdkd REFUSED to compare a resource, because a dynamic reference its state records could not be attributed to a region. Pass --accept to update cdkd state from AWS, or --revert to push cdkd state values back into AWS.").argument("[stacks...]", "Stack name(s) to check (physical CloudFormation names), each with its nested stacks").option("--all", "Check every stack in the state bucket", false).option("--json", "Output as JSON", false).option("--accept", "Update cdkd state with the AWS-current values for every drifted property (state ← AWS). Mutually exclusive with --revert.", false).option("--revert", "Push cdkd state values back into AWS via provider.update for every drifted resource (AWS ← state). Mutually exclusive with --accept.", false).option("--dry-run", "Print the planned mutations without acquiring a lock or hitting AWS / S3. Honored by --accept and --revert.", false).option("--concurrency <number>", "Maximum concurrent provider.update calls during --revert", (value) => parseInt(value, 10), 4).addOption(stackRegionOption$2()).action(withErrorHandling(driftCommand));
12067
+ const cmd = new Command("drift").description("Detect drift between cdkd state and AWS reality. Exits 0 when nothing drifted, 1 when drift is detected, and 2 when nothing drifted but cdkd REFUSED to compare a resource, because a dynamic reference its state records could not be attributed to a region. Pass --accept to update cdkd state from AWS, or --revert to push cdkd state values back into AWS.").argument("[stacks...]", "Stack name(s) to check (physical CloudFormation names), each with its nested stacks").option("--all", "Check every stack in the state bucket", false).option("--json", "Output as JSON", false).option("--accept", "Update cdkd state with the AWS-current values for every drifted property (state ← AWS). Mutually exclusive with --revert.", false).option("--revert", "Push cdkd state values back into AWS via provider.update for every drifted resource (AWS ← state). Mutually exclusive with --accept.", false).option("--dry-run", "Print the planned mutations without acquiring a lock or hitting AWS / S3. Honored by --accept and --revert.", false).option("--concurrency <number>", "Maximum concurrent provider.update calls during --revert", parsePositiveIntegerOption, 4).addOption(stackRegionOption$2()).action(withErrorHandling(driftCommand));
12044
12068
  [...commonOptions, ...stateOptions].forEach((opt) => cmd.addOption(opt));
12045
12069
  cmd.addOption(deprecatedRegionOption);
12046
12070
  return cmd;
@@ -12053,7 +12077,7 @@ const NOECHO_PRINTING_BIND_CAP_MS = 1e4;
12053
12077
  async function purgeStateHistoryIfOptedIn(ctx, stackName, region) {
12054
12078
  if (ctx.purgeStateHistory === true) await ctx.stateBackend.purgeDeletedStateHistory(stackName, region);
12055
12079
  }
12056
- const NESTED_STACK_TYPE = "AWS::CloudFormation::Stack";
12080
+ const NESTED_STACK_TYPE$1 = "AWS::CloudFormation::Stack";
12057
12081
  function maskedSnapshotLogger(logger, mask) {
12058
12082
  return {
12059
12083
  info: (message) => logger.info(mask(message)),
@@ -12426,7 +12450,7 @@ function resolvablePrincipalLists(resource) {
12426
12450
  async function recheckUnderLock({ ctx, stackName, state, regionForState, refusalRecovery, lock, restoreBaseRegionAndClients, needsStrongRefCheck }) {
12427
12451
  try {
12428
12452
  const [current, marker] = await Promise.all([ctx.stateBackend.getState(stackName, regionForState), readRefactorMarker(ctx.stateBackend)]);
12429
- 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");
12453
+ 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 ${cdkdRemedy("cdkd destroy")}.`, "STATE_CHANGED");
12430
12454
  if (current.state.terminationProtection === true && ctx.removeProtection !== true) throw new StackTerminationProtectionError(stackName, void 0, {
12431
12455
  args: accountArgs(refusalRecovery),
12432
12456
  clause: withheldAccountClause(refusalRecovery, "the command below prints")
@@ -12475,7 +12499,7 @@ function makeSummaryHints(regionForState, refusalRecovery) {
12475
12499
  ...accountArgs(refusalRecovery)
12476
12500
  ]);
12477
12501
  const hintFor = (command, targets, label) => [...new Set(targets.map((t) => `\n${label}: ${hintCommand(command, t).command}`))].join("");
12478
- 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()));
12502
+ 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 ${proseQuoted(cdkdRemedy("cdkd state list", "--long"))}.`) + (targets.length === 0 ? "" : ((clause) => clause === "" ? "" : ` ${clause}`)(withheldAccountClause(refusalRecovery, "the command lines below print").trimEnd()));
12479
12503
  return {
12480
12504
  hintFor,
12481
12505
  hintHolesClause
@@ -12587,7 +12611,7 @@ function printDestroySummary({ result, ctx, stackName, logger, preserveState, gu
12587
12611
  if (!preserveState) {
12588
12612
  const leftInAws = result.journaledOrphanSkips > 0;
12589
12613
  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)`);
12590
- } 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.`);
12614
+ } 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 ${proseQuoted(cdkdRemedy("cdkd destroy"))} / ${proseQuoted(cdkdRemedy("cdkd state destroy"))} to finish.`);
12591
12615
  else if (result.errorCount === 0) {
12592
12616
  const targets = [...skippedStateTargets];
12593
12617
  const showHint = hintFor("cdkd state show", targets, "Inspect it with");
@@ -12601,7 +12625,7 @@ function printDestroySummary({ result, ctx, stackName, logger, preserveState, gu
12601
12625
  const droppableSkipped = journaledOrphanFailures > 0 ? skippedTargets.filter((t) => t !== stackName) : skippedTargets;
12602
12626
  const skippedCommands = hintFor("cdkd state show", skippedTargets, "Inspect it with") + hintFor("cdkd state orphan", droppableSkipped, "Drop the record with");
12603
12627
  const dedupedCommands = (lines) => [...new Set(lines.split("\n").filter((l) => l !== ""))].map((l) => `\n${l}`).join("");
12604
- 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));
12628
+ 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 ${proseQuoted(cdkdRemedy("cdkd destroy"))} / ${proseQuoted(cdkdRemedy("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));
12605
12629
  }
12606
12630
  }
12607
12631
 
@@ -13152,7 +13176,7 @@ async function destroyStackUnderLock({ stackName, state, ctx, logger, result, re
13152
13176
  if (result.interrupted) logger.warn(`Destroy interrupted — ${Object.keys(remainingResources).length} resource(s) not deleted. State preserved.`);
13153
13177
  else if (result.errorCount > 0) logger.warn(`${result.errorCount} resource(s) failed to delete` + (journaledOrphanFailures > 0 ? ` (${journaledOrphanFailures} of them recorded only in the rollback journal)` : "") + `. State preserved.`);
13154
13178
  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).`);
13155
- 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.");
13179
+ 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 " + safeMsg`${proseQuoted(cdkdRemedy("cdkd destroy"))} / ${proseQuoted(cdkdRemedy("cdkd state destroy"))} deletes them.`);
13156
13180
  }
13157
13181
  printDestroySummary({
13158
13182
  result,
@@ -13385,7 +13409,10 @@ function skippedDestroyMessage(totalSkipped, totalOrphanSkips, rerunCommand) {
13385
13409
  const recordSkips = totalSkipped - totalOrphanSkips;
13386
13410
  const orphanSentence = `${totalOrphanSkips} resource(s) a failed deploy created were left in AWS, and no state records them any more. The warning naming each says what to do with it.`;
13387
13411
  if (recordSkips <= 0) return `Destroy finished, but ${orphanSentence}`;
13388
- return `Destroy skipped ${recordSkips} entr${recordSkips === 1 ? "y" : "ies"} whose delete cdkd did not confirm, so the underlying resources may still exist in AWS. A skipped nested stack counts as ONE entry and may cover several of its own resources — the per-stack summaries above give the exact breakdown. State preserved (the records are kept). The per-resource 'skipped (...)' lines and their warnings name each cause and whether repairing the record in state.json helps: where it does, repair it and re-run '${rerunCommand}'; otherwise (for example a custom-resource Delete handler that reported FAILED), delete the resources by hand and drop the records with 'cdkd state orphan <stack> --stack-region <region>'.` + (totalOrphanSkips > 0 ? ` Separately, ${orphanSentence}` : "");
13412
+ return `Destroy skipped ${recordSkips} entr${recordSkips === 1 ? "y" : "ies"} whose delete cdkd did not confirm, so the underlying resources may still exist in AWS. A skipped nested stack counts as ONE entry and may cover several of its own resources — the per-stack summaries above give the exact breakdown. State preserved (the records are kept). The per-resource 'skipped (...)' lines and their warnings name each cause and whether repairing the record in state.json helps: where it does, repair it and re-run '${rerunCommand === "cdkd destroy" ? cdkdRemedy("cdkd destroy") : cdkdRemedy("cdkd state destroy")}'; otherwise (for example a custom-resource Delete handler that reported FAILED), delete the resources by hand and drop the records with ${pasteableCommand("cdkd state orphan", [{ hole: "stack" }, {
13413
+ flag: "--stack-region",
13414
+ hole: "region"
13415
+ }]).command}.` + (totalOrphanSkips > 0 ? ` Separately, ${orphanSentence}` : "");
13389
13416
  }
13390
13417
 
13391
13418
  // src/cli/commands/destroy/helpers.ts
@@ -13464,7 +13491,7 @@ async function selectDestroyTargets(stackArgs, options, stateBackend, logger) {
13464
13491
  synthesized = true;
13465
13492
  } catch (error) {
13466
13493
  if (error instanceof StageLoadError) {
13467
- const named = new StageLoadError(`${error.message} To destroy a deployed stack without the app: cdkd state destroy ${commandHole("stack")}.`);
13494
+ const named = new StageLoadError(`${error.message} To destroy a deployed stack without the app: ${pasteableCommand("cdkd state destroy", [{ hole: "stack" }]).command}.`);
13468
13495
  if (typeof error.stack === "string") {
13469
13496
  const headerLines = `${error.name}: ${error.message}`.split("\n").length;
13470
13497
  const frames = error.stack.split("\n").slice(headerLines).join("\n");
@@ -13480,8 +13507,7 @@ async function selectDestroyTargets(stackArgs, options, stateBackend, logger) {
13480
13507
  if (appStacks.length === 0 && (options.all || wildcardPatterns.length > 0)) {
13481
13508
  const selector = options.all ? "--all" : wildcardPatterns.map((p) => displaySafe(p)).join(", ");
13482
13509
  if (synthesized) throw new Error(`${selector} selects among the stacks this app synthesizes, and it synthesized none; refusing to fall back to every stack in state.`);
13483
- const hole = commandHole("stack");
13484
- throw new CdkdError(`${selector} selects among the stacks this app synthesizes, and ` + (synthError ? "the app could not be synthesized" : "no app is configured") + "; refusing to fall back to every stack in state, which spans every app sharing this state bucket. " + (synthError ? "Fix the app so it synthesizes" : "Configure the app with --app or cdk.json") + `, or name each stack exactly: cdkd destroy ${hole}, or cdkd state destroy ${hole}, which needs no app.`, "DESTROY_NO_APP_SCOPE", synthError);
13510
+ throw new CdkdError(`${selector} selects among the stacks this app synthesizes, and ` + (synthError ? "the app could not be synthesized" : "no app is configured") + "; refusing to fall back to every stack in state, which spans every app sharing this state bucket. " + (synthError ? "Fix the app so it synthesizes" : "Configure the app with --app or cdk.json") + `, or name each stack exactly: ${pasteableCommand("cdkd destroy", [{ hole: "stack" }]).command}, or ${pasteableCommand("cdkd state destroy", [{ hole: "stack" }]).command}, which needs no app.`, "DESTROY_NO_APP_SCOPE", synthError);
13485
13511
  }
13486
13512
  if (options.all && appStacks.length > 0) {
13487
13513
  const app = partitionTopLevel(appStacks);
@@ -13655,6 +13681,81 @@ async function orderDestroyTargets(targets, appStacks, synthScanStacks, regionFo
13655
13681
  };
13656
13682
  }
13657
13683
 
13684
+ // src/cli/commands/destroy-runner/emulator-custom-resources.ts
13685
+ const NAMED_MAX = 5;
13686
+ const MAX_NESTED_DEPTH = 32;
13687
+ const NESTED_STACK_TYPE = "AWS::CloudFormation::Stack";
13688
+ const LAMBDA_FUNCTION_ARN = /^arn:aws[a-z-]*:lambda:[^:]+:(\d{12}):function:[^:]+(?::[^:]+)?$/;
13689
+ async function refuseCustomResourcesWithoutApp(targets, deps) {
13690
+ const command = localCustomResourceCommand();
13691
+ if (command !== "destroy" && command !== "state destroy") return;
13692
+ if (!customResourcesRunWithoutApp() || targets.length === 0) return;
13693
+ const account = await deps.callerAccount().catch(() => void 0);
13694
+ const found = [];
13695
+ for (const target of targets) {
13696
+ const record = await deps.getState(target.stackName, target.region);
13697
+ if (record === null) continue;
13698
+ const root = target.stackName.split("~")[0] || target.stackName;
13699
+ const customResources = [];
13700
+ await collect(target.stackName, target.region, record.state, root === target.stackName ? void 0 : target.stackName, 0, account, deps, customResources);
13701
+ if (customResources.length === 0) continue;
13702
+ const existing = found.find((f) => f.stackName === root);
13703
+ if (existing === void 0) found.push({
13704
+ stackName: root,
13705
+ customResources
13706
+ });
13707
+ else existing.customResources.push(...customResources);
13708
+ }
13709
+ if (found.length === 0) return;
13710
+ throw new CdkdError(customResourcesWithoutAppMessage(found), "EMULATOR_CR_NO_APP");
13711
+ }
13712
+ function refuseDestroyTargetsWithoutApp(targets, stateBackend, clients) {
13713
+ return refuseCustomResourcesWithoutApp(targets, {
13714
+ getState: (stackName, region) => stateBackend.getState(stackName, region),
13715
+ callerAccount: () => callerAccountOf(clients)
13716
+ });
13717
+ }
13718
+ async function callerAccountOf(clients) {
13719
+ try {
13720
+ const { GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
13721
+ return (await clients.sts.send(new GetCallerIdentityCommand({}))).Account;
13722
+ } catch {
13723
+ return;
13724
+ }
13725
+ }
13726
+ function runsInLocalRuntime(serviceToken, account) {
13727
+ if (typeof serviceToken !== "string") return false;
13728
+ const match = LAMBDA_FUNCTION_ARN.exec(serviceToken);
13729
+ return match !== null && (account === void 0 || match[1] === account);
13730
+ }
13731
+ async function collect(stackName, region, state, nestedStack, depth, account, deps, out) {
13732
+ const label = (logicalId) => plainOrDescribed(logicalId, "logical id") + (nestedStack === void 0 ? "" : ` in nested stack ${plainOrDescribed(nestedStack, "stack name")}`);
13733
+ const rows = state.resources !== null && typeof state.resources === "object" ? state.resources : {};
13734
+ for (const [logicalId, row] of Object.entries(rows)) {
13735
+ if (row === null || typeof row !== "object") continue;
13736
+ if (isCustomResourceType$1(row.resourceType) && runsInLocalRuntime(row.properties?.["ServiceToken"], account)) out.push(label(logicalId));
13737
+ else if (row.resourceType === NESTED_STACK_TYPE && depth < MAX_NESTED_DEPTH) {
13738
+ const childName = `${stackName}~${logicalId}`;
13739
+ const child = await deps.getState(childName, region);
13740
+ if (child !== null) await collect(childName, region, child.state, childName, depth + 1, account, deps, out);
13741
+ }
13742
+ }
13743
+ for (const entry of supersededResourcesOf(state)) if (isCustomResourceType$1(entry.state.resourceType) && runsInLocalRuntime(entry.state.properties?.["ServiceToken"], account)) out.push(label(entry.logicalId));
13744
+ }
13745
+ function customResourcesWithoutAppMessage(found) {
13746
+ const stacks = found.map(({ stackName, customResources }) => {
13747
+ const named = customResources.slice(0, NAMED_MAX);
13748
+ const more = customResources.length - named.length;
13749
+ return `${plainOrDescribed(stackName, "stack name")} (` + named.join(", ") + (more > 0 ? ` and ${more} more` : "") + ")";
13750
+ }).join("; ");
13751
+ const destroy = pasteableCommand("cdkd destroy", found.map(({ stackName }) => ({
13752
+ value: stackName,
13753
+ hole: "stack",
13754
+ opts: { plainIdent: true }
13755
+ })));
13756
+ return `Custom resources in ${found.length === 1 ? "stack" : "stacks"} ${stacks} would run their Delete handlers in AWS Emulator's own Lambda runtime, because this command did not synthesize the CDK app, and that runtime fails CDK's own provider functions. The destroy would then delete the handler functions too, leaving what the custom resources manage behind with nothing left to delete it. Nothing was deleted.\nRun the destroy from the app's directory (Docker running), so the handlers run locally, or pass ${NO_LOCAL_CUSTOM_RESOURCES_FLAG} to send them to AWS Emulator's runtime anyway.` + withheldTargetClause(destroy, "stack", "cdkd destroy", "A stack's name") + `\nRun from the app's directory: ${destroy.command}`;
13757
+ }
13758
+
13658
13759
  // src/cli/commands/destroy/command.ts
13659
13760
  async function destroyCommand(stackArgs, options) {
13660
13761
  const providerClasses = await loadProviderClasses();
@@ -13768,7 +13869,7 @@ async function destroyCommand(stackArgs, options) {
13768
13869
  totalErrors++;
13769
13870
  } else if (appStacks.length > 0 && !notInApp.includes(pattern)) notInApp.push(pattern);
13770
13871
  }
13771
- if (totalErrors > 0) throw new PartialFailureError(`Destroy completed with ${totalErrors} resource error(s). State preserved — inspect 'cdkd state show <stack>' and re-run 'cdkd destroy' to retry.`);
13872
+ if (totalErrors > 0) throw new PartialFailureError(`Destroy completed with ${totalErrors} resource error(s). State preserved — inspect ${pasteableCommand("cdkd state show", [{ hole: "stack" }]).command} and re-run ${proseQuoted(cdkdRemedy("cdkd destroy"))} to retry.`);
13772
13873
  if (notInApp.length > 0) logger.warn(renderNotInAppWarning(notInApp));
13773
13874
  }
13774
13875
  logger.info("No matching stacks found in state");
@@ -13811,11 +13912,19 @@ async function destroyCommand(stackArgs, options) {
13811
13912
  if (strict !== void 0) return refs.some((r) => r.region === strict) ? strict : void 0;
13812
13913
  return plannedDestroyRegion(refs, target.synth?.region, fallbackRegionByName.get(target.stackName) ?? region);
13813
13914
  };
13915
+ const customResourceTargets = [];
13814
13916
  for (const target of targets) {
13815
13917
  if (target.synth?.terminationProtection === true && !(options.removeProtection === true && target.dependsOnSelected === void 0)) continue;
13816
13918
  const planned = plannedRegionFor(target);
13817
- if (planned !== void 0) crossPrefixCheck.cache.full(target.stackName, planned, "prestart");
13919
+ if (planned !== void 0) {
13920
+ crossPrefixCheck.cache.full(target.stackName, planned, "prestart");
13921
+ customResourceTargets.push({
13922
+ stackName: target.stackName,
13923
+ region: planned
13924
+ });
13925
+ }
13818
13926
  }
13927
+ await refuseDestroyTargetsWithoutApp(customResourceTargets, stateBackend, awsClients);
13819
13928
  for (const [stackIndex, target] of targets.entries()) {
13820
13929
  const stackName = target.stackName;
13821
13930
  logger.info(`\nPreparing to destroy stack: ${describeTarget(target)}`);
@@ -14004,8 +14113,11 @@ async function destroyCommand(stackArgs, options) {
14004
14113
  break;
14005
14114
  }
14006
14115
  }
14007
- if (totalErrors > 0) throw new PartialFailureError(`Destroy completed with ${totalErrors} resource error(s). State preserved — inspect 'cdkd state show <stack>' and re-run 'cdkd destroy' to retry. If the same resource keeps failing, 'cdkd state orphan <stack> --stack-region <region>' removes the stack's state in that region (every resource's record) without deleting AWS resources.`);
14008
- if (interrupted || interruptWatch.interrupted() && stoppedEarly) throw new PartialFailureError(`Destroy interrupted by Ctrl-C. State preserved — re-run 'cdkd destroy' to finish.`);
14116
+ if (totalErrors > 0) throw new PartialFailureError(`Destroy completed with ${totalErrors} resource error(s). State preserved — inspect ${pasteableCommand("cdkd state show", [{ hole: "stack" }]).command} and re-run ${proseQuoted(cdkdRemedy("cdkd destroy"))} to retry. If the same resource keeps failing, ${pasteableCommand("cdkd state orphan", [{ hole: "stack" }, {
14117
+ flag: "--stack-region",
14118
+ hole: "region"
14119
+ }]).command} removes the stack's state in that region (every resource's record) without deleting AWS resources.`);
14120
+ if (interrupted || interruptWatch.interrupted() && stoppedEarly) throw new PartialFailureError(`Destroy interrupted by Ctrl-C. State preserved — re-run ${proseQuoted(cdkdRemedy("cdkd destroy"))} to finish.`);
14009
14121
  if (totalSkipped > 0) throw new PartialFailureError(skippedDestroyMessage(totalSkipped, totalOrphanSkips, "cdkd destroy"));
14010
14122
  } finally {
14011
14123
  await Promise.allSettled(deferredTails);
@@ -14089,7 +14201,7 @@ async function stateMigrateCommand(options) {
14089
14201
  logger.info("Migrating state bucket:");
14090
14202
  logger.info(` source: ${legacyBucket} (resolved for --region ${sourceRegionLabel})`);
14091
14203
  logger.info(` destination: ${newBucket}`);
14092
- if (!sourceExists) throw new Error(`Source bucket '${legacyBucket}' does not exist. Nothing to migrate. (Tip: run \`cdkd state info\` to confirm which bucket cdkd is reading from.)`);
14204
+ if (!sourceExists) throw new Error(`Source bucket '${legacyBucket}' does not exist. Nothing to migrate. (Tip: run ${proseQuoted(cdkdRemedy("cdkd state info"), "`")} to confirm which bucket cdkd is reading from.)`);
14093
14205
  const legacyRegion = await resolveBucketRegion(legacyBucket);
14094
14206
  logger.info(` source bucket actual region: ${legacyRegion}`);
14095
14207
  const legacyS3 = new S3Client({
@@ -14207,7 +14319,7 @@ async function assertNoActiveLocks(s3, bucket) {
14207
14319
  if (locks.length > 0) {
14208
14320
  const sample = locks.slice(0, 3).join(", ");
14209
14321
  const more = locks.length > 3 ? ` (+${locks.length - 3} more)` : "";
14210
- throw new Error(`Refusing to migrate: ${locks.length} active lock file(s) found in '${bucket}': ${sample}${more}. Wait for in-flight cdkd operations to complete, or run 'cdkd force-unlock <stack>' if a lock is stale.`);
14322
+ throw new Error(`Refusing to migrate: ${locks.length} active lock file(s) found in '${bucket}': ${sample}${more}. Wait for in-flight cdkd operations to complete, or run ${pasteableCommand("cdkd force-unlock", [{ hole: "stack" }]).command} if a lock is stale.`);
14211
14323
  }
14212
14324
  }
14213
14325
  async function ensureDestinationBucket(bucketName, region, accountId, logger) {
@@ -14409,14 +14521,25 @@ function stackTreeToJson(roots) {
14409
14521
  }
14410
14522
 
14411
14523
  // src/cli/commands/state/refs.ts
14412
- const STATE_READ_FAILED_REASON = "state record could not be read; run `cdkd state show` for the error";
14413
- const LOCK_READ_FAILED_REASON = "lock could not be read; run `cdkd state show` for the error";
14524
+ function stateReadFailedReason() {
14525
+ return `state record could not be read; run ${proseQuoted(stateShowCommand$1(), "`")} for the error`;
14526
+ }
14527
+ function lockReadFailedReason() {
14528
+ return `lock could not be read; run ${proseQuoted(stateShowCommand$1(), "`")} for the error`;
14529
+ }
14530
+ function stateShowCommand$1() {
14531
+ return cdkdRemedy("cdkd state show");
14532
+ }
14414
14533
  const LEGACY_LOCK_READ_FAILED_REASON = "lock could not be read";
14415
- const RESOURCES_MALFORMED_REASON = "resources is not a JSON object; run `cdkd state show --json` to see the record";
14416
- const STATE_READ_REASONS = {
14417
- "read-failed": STATE_READ_FAILED_REASON,
14418
- "resources-malformed": RESOURCES_MALFORMED_REASON
14419
- };
14534
+ function resourcesMalformedReason() {
14535
+ return `resources is not a JSON object; run ${proseQuoted(cdkdRemedy("cdkd state show", "--json"), "`")} to see the record`;
14536
+ }
14537
+ function stateReadReasons() {
14538
+ return {
14539
+ "read-failed": stateReadFailedReason(),
14540
+ "resources-malformed": resourcesMalformedReason()
14541
+ };
14542
+ }
14420
14543
  function stateDestroyTargets(refs, stackRegion) {
14421
14544
  if (stackRegion) return refs.filter((r) => r.region === stackRegion || !r.region);
14422
14545
  return refs.length === 1 ? [...refs] : void 0;
@@ -14459,7 +14582,7 @@ function describedStackRef(ref) {
14459
14582
  return ref.region ? `${name} (${plainOrDescribed(ref.region, "region")})` : name;
14460
14583
  }
14461
14584
  function legacyRecordSubject(stackName) {
14462
- return isPasteableIdent(stackName) ? `Stack ${stackName}` : `A stack whose name is not a plain identifier (see 'cdkd state list --long')`;
14585
+ return isPasteableIdent(stackName) ? `Stack ${stackName}` : `A stack whose name is not a plain identifier (see ${proseQuoted(cdkdRemedy("cdkd state list", "--long"))})`;
14463
14586
  }
14464
14587
  function legacyRecordRefusal(stackName) {
14465
14588
  const migrate = pasteableCommand("cdkd deploy", [{
@@ -14472,7 +14595,9 @@ function legacyRecordRefusal(stackName) {
14472
14595
  }]);
14473
14596
  return /* @__PURE__ */ new Error(`${legacyRecordSubject(stackName)} has only a legacy state record without a region. A cdkd write migrates it to the region-scoped layout; re-run this command after it.` + withheldTargetClause(migrate, "stack", "cdkd deploy") + `\nMigrate with: ${migrate.command}`);
14474
14597
  }
14475
- const STATE_LIST_POINTER = `'cdkd state list --long' shows the records as stored.`;
14598
+ function stateListPointer() {
14599
+ return `${proseQuoted(cdkdRemedy("cdkd state list", "--long"))} shows the records as stored.`;
14600
+ }
14476
14601
  function refIsDescribed(ref) {
14477
14602
  return !isPasteableIdent(ref.stackName) || (ref.region ? !isPasteableIdent(ref.region) : false);
14478
14603
  }
@@ -14492,14 +14617,14 @@ function noStateInRegionError(stackName, requestedRegion, matches, opts) {
14492
14617
  requestedRegion,
14493
14618
  ...matches.flatMap((r) => r.region ? [r.region] : [])
14494
14619
  ].some((v) => !isPasteableIdent(v));
14495
- return /* @__PURE__ */ new Error(`No state found for ${subject} in region ${requested}. Available regions: ${candidates.join(", ")}.` + (anyDescribed ? ` ${STATE_LIST_POINTER}` : ""));
14620
+ return /* @__PURE__ */ new Error(`No state found for ${subject} in region ${requested}. Available regions: ${candidates.join(", ")}.` + (anyDescribed ? ` ${stateListPointer()}` : ""));
14496
14621
  }
14497
14622
  function multipleRegionsError(stackName, matches, remedy) {
14498
14623
  return /* @__PURE__ */ new Error(`Stack ${displayStackName(stackName)} has state in multiple regions: ${matches.map((r) => listedRegion(r.region)).join(", ")}.\n${remedy}`);
14499
14624
  }
14500
14625
  function resolveSingleRegion(stackName, refs, requestedRegion) {
14501
14626
  const matches = refs.filter((r) => r.stackName === stackName);
14502
- if (matches.length === 0) throw new Error(`No state found for stack ${displayStackName(stackName)}.\nRun 'cdkd state list' to see available stacks.`);
14627
+ if (matches.length === 0) throw new Error(`No state found for stack ${displayStackName(stackName)}.\nRun ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
14503
14628
  if (requestedRegion) {
14504
14629
  const ref = matches.find((r) => r.region === requestedRegion);
14505
14630
  if (!ref) throw noStateInRegionError(stackName, requestedRegion, matches);
@@ -14644,9 +14769,9 @@ async function stateListCommand(options) {
14644
14769
  resourceCount,
14645
14770
  lastModified: state ? isoTimestampOrNull(state.lastModified) : null,
14646
14771
  locked: lockRead.ok ? lockRead.value : null,
14647
- stateReadError: stateReadErrorKind === null ? null : STATE_READ_REASONS[stateReadErrorKind],
14772
+ stateReadError: stateReadErrorKind === null ? null : stateReadReasons()[stateReadErrorKind],
14648
14773
  stateReadErrorKind,
14649
- lockReadError: lockRead.ok ? null : ref.region ? LOCK_READ_FAILED_REASON : LEGACY_LOCK_READ_FAILED_REASON
14774
+ lockReadError: lockRead.ok ? null : ref.region ? lockReadFailedReason() : LEGACY_LOCK_READ_FAILED_REASON
14650
14775
  };
14651
14776
  }));
14652
14777
  const degraded = details.filter((d) => d.stateReadError !== null || d.lockReadError !== null);
@@ -14798,7 +14923,7 @@ async function printStackResources(stackName, options, setup) {
14798
14923
  const ref = resolveSingleRegion(stackName, refs, options.stackRegion);
14799
14924
  if (!ref.region) throw legacyRecordRefusal(stackName);
14800
14925
  const stateResult = await setup.stateBackend.getState(stackName, ref.region);
14801
- if (!stateResult) throw new Error(`No state found for stack ${formatStackRefSafe(ref)} in s3://${setup.bucket}/${setup.prefix}/. Run 'cdkd state list' to see available stacks.`);
14926
+ if (!stateResult) throw new Error(`No state found for stack ${formatStackRefSafe(ref)} in s3://${setup.bucket}/${setup.prefix}/. Run ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
14802
14927
  if (repairMalformedResourcesForReadOnly(stateResult.state)) logger.warn(malformedResourcesWarning(stackName, ref.region, renderRecovery(options, setup)));
14803
14928
  if (options.long || options.json) repairRenderedContainers(stateResult.state, RESOURCES_RENDERED_CONTAINERS, stackName, ref.region, logger, renderRecovery(options, setup));
14804
14929
  const resources = withSecretPhysicalIdsMaskedInState(stateResult.state).resources;
@@ -14983,7 +15108,7 @@ function orphanCommandFor(stackName, region, recovery) {
14983
15108
  },
14984
15109
  ...account
14985
15110
  ]).command,
14986
- note: ` The next line's command names neither value, because its record's ${reasons.join("; and its ")}. List the records with ` + (account.length > 0 ? `'cdkd state list --json' run with the same account flags as the next line's command, and ` : `'cdkd state list --json' and `) + (dashName ? "repair or remove the one whose stackName and region match by hand — this stack name begins with a '-' and could parse as an option in that position, so do not fill a hole with it." : `act on the one whose stackName and region match, replacing each quoted hole, quotes included, with ${JSON_LISTING_HOLE_VALUE}.`) + accountNote
15111
+ note: ` The next line's command names neither value, because its record's ${reasons.join("; and its ")}. List the records with ` + (account.length > 0 ? `${proseQuoted(cdkdRemedy("cdkd state list", "--json"))} run with the same account flags as the next line's command, and ` : `${proseQuoted(cdkdRemedy("cdkd state list", "--json"))} and `) + (dashName ? "repair or remove the one whose stackName and region match by hand — this stack name begins with a '-' and could parse as an option in that position, so do not fill a hole with it." : `act on the one whose stackName and region match, replacing each quoted hole, quotes included, with ${JSON_LISTING_HOLE_VALUE}.`) + accountNote
14987
15112
  };
14988
15113
  }
14989
15114
  function orphanWithheldPart(what, raw, built, hole) {
@@ -15179,7 +15304,7 @@ async function pickStackRegion$1(stateBackend, stackName, synthRegion, flag) {
15179
15304
  if (refs.length === 0) {
15180
15305
  if (flag) return flag;
15181
15306
  if (synthRegion) return synthRegion;
15182
- throw new Error(`No state found for stack ${quotedOrNotShown(stackName)}. Run 'cdkd state list' to see available stacks.`);
15307
+ throw new Error(`No state found for stack ${quotedOrNotShown(stackName)}. Run ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
15183
15308
  }
15184
15309
  if (flag) {
15185
15310
  if (!refs.find((r) => r.region === flag)) {
@@ -15228,7 +15353,7 @@ function refuseTransientContextIfUnsafe(options) {
15228
15353
  if (overrides.length === 0) return;
15229
15354
  if (!options.acceptTransientContext) {
15230
15355
  const indented = overrides.map((v) => ` -c ${quotedOrNotShown(v)}`).join("\n");
15231
- throw new Error(`Refusing to export: ${overrides.length} CLI context override(s) supplied via -c are not persisted to cdk.json / cdk.context.json, so subsequent \`cdk deploy\` invocations will synthesize a different template and CFn will see drift or replace resources.\n\nSupplied:\n${indented}\n\nChoose one:\n (recommended) Move these values into cdk.json's "context": { ... } field, then re-run\n cdkd export without -c. CDK CLI reads cdk.json on every synth, so they\n will be picked up automatically.\n (escape) Pass --accept-transient-context to proceed. You will then need to\n pass the SAME -c flags to every future \`cdk deploy\` for this stack.`);
15356
+ throw new Error(`Refusing to export: ${overrides.length} CLI context override(s) supplied via -c are not persisted to cdk.json / cdk.context.json, so subsequent \`cdk deploy\` invocations will synthesize a different template and CFn will see drift or replace resources.\n\nSupplied:\n${indented}\n\nChoose one:\n (recommended) Move these values into cdk.json's "context": { ... } field, then re-run\n ${cdkdRemedy("cdkd export")} without -c. CDK CLI reads cdk.json on every synth, so they\n will be picked up automatically.\n (escape) Pass --accept-transient-context to proceed. You will then need to\n pass the SAME -c flags to every future \`cdk deploy\` for this stack.`);
15232
15357
  }
15233
15358
  const logger = getLogger();
15234
15359
  logger.warn(`--accept-transient-context: ${overrides.length} CLI context override(s) will not be persisted to cdk.json / cdk.context.json. Remember to pass the same -c flags to every future \`cdk deploy\` for this stack, or move them to cdk.json before then.`);
@@ -15270,7 +15395,7 @@ function recordedRuleIdIdentifier() {
15270
15395
  if (typeof recorded === "string" && isUsableIdentifier(recorded)) return recorded.trim();
15271
15396
  if (isUsableIdentifier(physicalId)) return physicalId.trim();
15272
15397
  const recordedNote = typeof recorded === "string" && recorded.trim() ? `attributes.Id is recorded as ${showRecordValue(recorded)}, which is not an 'sgr-…' security-group rule id` : `attributes.Id is missing or empty`;
15273
- throw new Error(`cdkd's physical id for AWS::EC2::SecurityGroupIngress is the composite '<groupId>|<ipProtocol>|<fromPort>|<toPort>', but CloudFormation IMPORT identifies the rule by the 'sgr-...' security-group rule id AWS assigns, which cdkd state does not record usably for ${quotedOrNotShown(logicalId)} (${recordedNote}). Two causes, with different remedies. (1) The rule declares MORE THAN ONE source — e.g. both CidrIp and CidrIpv6 on the same resource — so AWS minted one rule per source and cdkd deliberately recorded neither id, because neither is 'the' identifier for this resource. Re-deploying does not help; split it into one AWS::EC2::SecurityGroupIngress resource per source, which is also the shape CloudFormation will manage after the export. (2) Otherwise the rule was deployed by a cdkd older than https://github.com/go-to-k/cdkd/issues/1761, which did not record the id at all. AWS returns it only from AuthorizeSecurityGroupIngress itself, so a no-op re-deploy will NOT heal the record either: change any property of the rule (cdkd revokes and re-authorizes, minting a fresh id, with a momentary traffic interruption) or destroy and re-deploy it, then re-run cdkd export. In both cases you can instead remove ${quotedOrNotShown(logicalId)} from the stack before exporting — the rule stays in AWS and can be re-declared in CloudFormation afterwards.`);
15398
+ throw new Error(`cdkd's physical id for AWS::EC2::SecurityGroupIngress is the composite '<groupId>|<ipProtocol>|<fromPort>|<toPort>', but CloudFormation IMPORT identifies the rule by the 'sgr-...' security-group rule id AWS assigns, which cdkd state does not record usably for ${quotedOrNotShown(logicalId)} (${recordedNote}). Two causes, with different remedies. (1) The rule declares MORE THAN ONE source — e.g. both CidrIp and CidrIpv6 on the same resource — so AWS minted one rule per source and cdkd deliberately recorded neither id, because neither is 'the' identifier for this resource. Re-deploying does not help; split it into one AWS::EC2::SecurityGroupIngress resource per source, which is also the shape CloudFormation will manage after the export. (2) Otherwise the rule was deployed by a cdkd older than https://github.com/go-to-k/cdkd/issues/1761, which did not record the id at all. AWS returns it only from AuthorizeSecurityGroupIngress itself, so a no-op re-deploy will NOT heal the record either: change any property of the rule (cdkd revokes and re-authorizes, minting a fresh id, with a momentary traffic interruption) or destroy and re-deploy it, then re-run ${cdkdRemedy("cdkd export")}. In both cases you can instead remove ${quotedOrNotShown(logicalId)} from the stack before exporting — the rule stays in AWS and can be re-declared in CloudFormation afterwards.`);
15274
15399
  }
15275
15400
  };
15276
15401
  }
@@ -15356,19 +15481,19 @@ function cachedSecurityGroupRules(groupId, { ec2Client, securityGroupRuleCache }
15356
15481
  securityGroupRuleCache.set(groupId, pending);
15357
15482
  return pending;
15358
15483
  }
15359
- const SG_INGRESS_AMBIGUITY_REMEDY = "Two causes, with different remedies. (1) ONE resource declaring MORE THAN ONE source (e.g. both CidrIp and CidrIpv6 on the same resource), for which AWS mints one rule per source: split it into one AWS::EC2::SecurityGroupIngress resource per source, which is also the shape CloudFormation will manage after the export. (2) TWO DISTINCT AWS::EC2::SecurityGroupIngress resources that differ only by SOURCE — port 443 from a CIDR and port 443 from a peer security group, say. cdkd's composite physical id carries no source, so those two rows carry byte-identical ids and splitting is not their remedy: set the row's attributes.Id to the 'sgr-...' id that belongs to it (cdkd then resolves from state and issues no lookup at all), or remove the row from the stack before exporting. Then re-run cdkd export.";
15484
+ const sgIngressAmbiguityRemedy = () => `Two causes, with different remedies. (1) ONE resource declaring MORE THAN ONE source (e.g. both CidrIp and CidrIpv6 on the same resource), for which AWS mints one rule per source: split it into one AWS::EC2::SecurityGroupIngress resource per source, which is also the shape CloudFormation will manage after the export. (2) TWO DISTINCT AWS::EC2::SecurityGroupIngress resources that differ only by SOURCE — port 443 from a CIDR and port 443 from a peer security group, say. cdkd's composite physical id carries no source, so those two rows carry byte-identical ids and splitting is not their remedy: set the row's attributes.Id to the 'sgr-...' id that belongs to it (cdkd then resolves from state and issues no lookup at all), or remove the row from the stack before exporting. Then re-run ${cdkdRemedy("cdkd export")}.`;
15360
15485
  function sgIngressExportEscapeHatch(logicalId) {
15361
15486
  return `You can instead remove ${quotedOrNotShown(logicalId)} from the stack before exporting — the rule stays in AWS and can be re-declared in CloudFormation afterwards.`;
15362
15487
  }
15363
15488
  async function backfillSecurityGroupIngressRuleId({ logicalId, physicalId }, deps) {
15364
15489
  const tuple = parseSecurityGroupIngressComposite(physicalId);
15365
- if (!tuple) throw new Error(`cdkd state records no 'sgr-...' security-group rule id for ${quotedOrNotShown(logicalId)}, and its physical id ${showRecordValue(physicalId)} is not cdkd's '<groupId>|<ipProtocol>|<fromPort>|<toPort>' composite either, so cdkd cannot look the rule up in AWS to recover the id CloudFormation IMPORT needs. Repair the record's physicalId (or its attributes.Id, which may be the 'sgr-...' id verbatim) and re-run cdkd export. ${sgIngressExportEscapeHatch(logicalId)}`);
15490
+ if (!tuple) throw new Error(`cdkd state records no 'sgr-...' security-group rule id for ${quotedOrNotShown(logicalId)}, and its physical id ${showRecordValue(physicalId)} is not cdkd's '<groupId>|<ipProtocol>|<fromPort>|<toPort>' composite either, so cdkd cannot look the rule up in AWS to recover the id CloudFormation IMPORT needs. Repair the record's physicalId (or its attributes.Id, which may be the 'sgr-...' id verbatim) and re-run ${cdkdRemedy("cdkd export")}. ${sgIngressExportEscapeHatch(logicalId)}`);
15366
15491
  const portRange = tuple.fromPort === tuple.toPort ? `${tuple.fromPort}` : `${tuple.fromPort}-${tuple.toPort}`;
15367
15492
  const tupleNote = `protocol ${showRecordValue(tuple.ipProtocol)}, ports ${portRange} on security group ${showRecordValue(tuple.groupId)}`;
15368
15493
  const lookup = await cachedSecurityGroupRules(tuple.groupId, deps);
15369
15494
  if (!lookup.ok) {
15370
15495
  if (lookup.kind === "truncated") throw new Error(`cdkd state records no 'sgr-...' security-group rule id for ${quotedOrNotShown(logicalId)}, and the DescribeSecurityGroupRules lookup on ${showRecordValue(tuple.groupId)} was still paginating after ${MAX_SG_RULE_PAGES} pages — cdkd cannot prove a match is unique without seeing the whole group, and adopting an unproven id would name the wrong rule. ${sgIngressExportEscapeHatch(logicalId)}`);
15371
- const remedy = lookup.kind === "auth" ? `Grant ec2:DescribeSecurityGroupRules and re-run cdkd export.` : lookup.kind === "throttled" ? `AWS throttled the lookup and cdkd retried it ${MAX_SG_RULE_THROTTLE_RETRIES} times before giving up — no permission is missing. Re-run cdkd export once the account's EC2 describe rate has recovered.` : `Re-run cdkd export once that cause is resolved.`;
15496
+ const remedy = lookup.kind === "auth" ? `Grant ec2:DescribeSecurityGroupRules and re-run ${cdkdRemedy("cdkd export")}.` : lookup.kind === "throttled" ? `AWS throttled the lookup and cdkd retried it ${MAX_SG_RULE_THROTTLE_RETRIES} times before giving up — no permission is missing. Re-run ${cdkdRemedy("cdkd export")} once the account's EC2 describe rate has recovered.` : `Re-run ${cdkdRemedy("cdkd export")} once that cause is resolved.`;
15372
15497
  throw new Error(`cdkd state records no 'sgr-...' security-group rule id for ${quotedOrNotShown(logicalId)} (the rule was deployed by a cdkd older than https://github.com/go-to-k/cdkd/issues/1761), and the DescribeSecurityGroupRules lookup that would have recovered it failed: ${lookup.detail}. ${remedy} ${sgIngressExportEscapeHatch(logicalId)}`);
15373
15498
  }
15374
15499
  const matched = lookup.rules.filter((rule) => ruleMatchesIngressTuple(rule, tuple));
@@ -15376,12 +15501,12 @@ async function backfillSecurityGroupIngressRuleId({ logicalId, physicalId }, dep
15376
15501
  if (ids.length < matched.length) {
15377
15502
  const unusable = matched.filter((rule) => !(typeof rule.SecurityGroupRuleId === "string" && SG_RULE_ID_PATTERN.test(rule.SecurityGroupRuleId.trim()))).map((rule) => typeof rule.SecurityGroupRuleId === "string" ? `${quotedOrNotShown(rule.SecurityGroupRuleId)}` : "<absent>");
15378
15503
  const readableNote = ids.length > 0 ? ` The readable candidates cdkd did see: ${ids.map((id) => `${quotedOrNotShown(id)}`).join(", ")}.` : "";
15379
- const ambiguityNote = matched.length > 1 ? ` Note that ${matched.length} rules matching one row is an ambiguity in its own right, which cdkd could not resolve even if every id were readable: ${SG_INGRESS_AMBIGUITY_REMEDY}${readableNote}` : "";
15504
+ const ambiguityNote = matched.length > 1 ? ` Note that ${matched.length} rules matching one row is an ambiguity in its own right, which cdkd could not resolve even if every id were readable: ${sgIngressAmbiguityRemedy()}${readableNote}` : "";
15380
15505
  throw new Error(`cdkd state records no 'sgr-...' security-group rule id for ${quotedOrNotShown(logicalId)}, and a live DescribeSecurityGroupRules lookup found ${matched.length} ingress rule(s) matching ${tupleNote}, but ${unusable.length} of them carry no usable 'sgr-...' rule id (AWS reported ${unusable.join(", ")}). cdkd adopts an id only on an EXACTLY ONE match, and that is a count of MATCHING RULES — so discarding the unreadable ones first would let a genuine two-match pass as "exactly one" and record an identifier naming the wrong rule. cdkd refuses instead. This is a DescribeSecurityGroupRules response shape cdkd does not expect; please open a cdkd issue if it persists.${ambiguityNote} ${sgIngressExportEscapeHatch(logicalId)}`);
15381
15506
  }
15382
15507
  if (ids.length === 1) return ids[0];
15383
- if (ids.length === 0) throw new Error(`cdkd state records no 'sgr-...' security-group rule id for ${quotedOrNotShown(logicalId)} (the rule was deployed by a cdkd older than https://github.com/go-to-k/cdkd/issues/1761), and a live DescribeSecurityGroupRules lookup found NO ingress rule matching ${tupleNote} — so cdkd has no id to hand CloudFormation IMPORT. Either the rule was revoked outside cdkd, or the group lives in a region other than the one this export is running against. Run cdkd deploy to reconcile the stack, then re-run cdkd export. ${sgIngressExportEscapeHatch(logicalId)}`);
15384
- throw new Error(`cdkd state records no 'sgr-...' security-group rule id for ${quotedOrNotShown(logicalId)}, and a live DescribeSecurityGroupRules lookup found ${ids.length} ingress rules matching ${tupleNote} (${ids.join(", ")}). cdkd's physical id identifies a rule only by group, protocol and port range, so it cannot say which of them ${quotedOrNotShown(logicalId)} is, and CloudFormation IMPORT needs exactly one — adopting either would record the wrong rule. ${SG_INGRESS_AMBIGUITY_REMEDY} ${sgIngressExportEscapeHatch(logicalId)}`);
15508
+ if (ids.length === 0) throw new Error(`cdkd state records no 'sgr-...' security-group rule id for ${quotedOrNotShown(logicalId)} (the rule was deployed by a cdkd older than https://github.com/go-to-k/cdkd/issues/1761), and a live DescribeSecurityGroupRules lookup found NO ingress rule matching ${tupleNote} — so cdkd has no id to hand CloudFormation IMPORT. Either the rule was revoked outside cdkd, or the group lives in a region other than the one this export is running against. Run ${cdkdRemedy("cdkd deploy")} to reconcile the stack, then re-run ${cdkdRemedy("cdkd export")}. ${sgIngressExportEscapeHatch(logicalId)}`);
15509
+ throw new Error(`cdkd state records no 'sgr-...' security-group rule id for ${quotedOrNotShown(logicalId)}, and a live DescribeSecurityGroupRules lookup found ${ids.length} ingress rules matching ${tupleNote} (${ids.join(", ")}). cdkd's physical id identifies a rule only by group, protocol and port range, so it cannot say which of them ${quotedOrNotShown(logicalId)} is, and CloudFormation IMPORT needs exactly one — adopting either would record the wrong rule. ${sgIngressAmbiguityRemedy()} ${sgIngressExportEscapeHatch(logicalId)}`);
15385
15510
  }
15386
15511
 
15387
15512
  // src/cli/commands/export/composite-physical-id.ts
@@ -15429,18 +15554,15 @@ async function resolveIdentifierValue(entry, ctx, deps) {
15429
15554
  }
15430
15555
  }
15431
15556
  function maskedIdentifierAttributeReason(field, logicalId) {
15432
- return `cdkd state holds only the redaction mask ('***') at attributes.${field} for ${isPasteableIdent(logicalId) ? logicalId : `this resource (its logical id is not a plain identifier; read it with 'cdkd state show')`}, and that attribute is the value cdkd export reads as this resource type's CloudFormation import identifier (${field}); nothing masked may reach the exported template, since CloudFormation would either refuse it at IMPORT or write it onto the live resource at the next update. The mask is what 'cdkd import' writes for a Cloud Control model key it could not certify as read-only — every key when cloudformation:DescribeType was unavailable. Re-deploying does NOT clear it. Repair the record with the command below, after granting cloudformation:DescribeType, or export the stack without this resource and adopt it into CloudFormation by hand. See https://github.com/go-to-k/cdkd/issues/2932.`;
15557
+ return `cdkd state holds only the redaction mask ('***') at attributes.${field} for ${isPasteableIdent(logicalId) ? logicalId : `this resource (its logical id is not a plain identifier; read it with ${proseQuoted(cdkdRemedy("cdkd state show"))})`}, and that attribute is the value cdkd export reads as this resource type's CloudFormation import identifier (${field}); nothing masked may reach the exported template, since CloudFormation would either refuse it at IMPORT or write it onto the live resource at the next update. The mask is what 'cdkd import' writes for a Cloud Control model key it could not certify as read-only — every key when cloudformation:DescribeType was unavailable. Re-deploying does NOT clear it. Repair the record with the command below, after granting cloudformation:DescribeType, or export the stack without this resource and adopt it into CloudFormation by hand. See https://github.com/go-to-k/cdkd/issues/2932.`;
15433
15558
  }
15434
15559
  function importRepairCommand(logicalId) {
15435
- const named = isPasteableIdent(logicalId);
15436
- return `${pasteableCommand("cdkd import", [{ hole: "stack" }, named ? {
15437
- flag: "--resource",
15438
- value: logicalId,
15439
- hole: "logicalId"
15440
- } : {
15441
- flag: "--resource",
15442
- hole: "logicalId"
15443
- }]).command}=${commandHole("physicalId")} --force`;
15560
+ const pair = `${isPasteableIdent(logicalId) ? shellQuote(logicalId) : commandHole("logicalId")}=${commandHole("physicalId")}`;
15561
+ return pasteableCommand("cdkd import", [
15562
+ { hole: "stack" },
15563
+ { literal: `--resource ${pair}` },
15564
+ { literal: "--force" }
15565
+ ]).command;
15444
15566
  }
15445
15567
  function deployRepairCommand(stackName) {
15446
15568
  return pasteableCommand("cdkd deploy", [repairStackArg(stackName)]).command;
@@ -15470,7 +15592,7 @@ function recordedArnIdentifier(options) {
15470
15592
  if (isUsableIdentifier(physicalId)) return physicalId.trim();
15471
15593
  const recordedNote = typeof recorded === "string" && recorded.trim() ? `attributes.${field} is recorded as ${showRecordValue(recorded)}, which is not a ${arnServiceSegment} ARN` : `attributes.${field} is missing or empty`;
15472
15594
  const shapeWord = physicalIdShape.includes("|") ? "the composite" : "the bare";
15473
- throw new Error(`cdkd's physical id for ${resourceType} is ${shapeWord} '${physicalIdShape}', but CloudFormation IMPORT identifies the resource by its ${field}, which cdkd state does not record usably for ${quotedOrNotShown(logicalId)} (${recordedNote}). Re-deploy the stack once so cdkd records ${field}, then re-run cdkd export.`);
15595
+ throw new Error(`cdkd's physical id for ${resourceType} is ${shapeWord} '${physicalIdShape}', but CloudFormation IMPORT identifies the resource by its ${field}, which cdkd state does not record usably for ${quotedOrNotShown(logicalId)} (${recordedNote}). Re-deploy the stack once so cdkd records ${field}, then re-run ${cdkdRemedy("cdkd export")}.`);
15474
15596
  }
15475
15597
  };
15476
15598
  }
@@ -15531,7 +15653,7 @@ function resolveRouteDestination(segment, properties) {
15531
15653
  if (declaredValues.some((value) => (canonicalizeIpv4Cidr(value) ?? value) === identifier)) return identifier;
15532
15654
  const shared = `AWS::EC2::Route: cdkd state's recorded properties declare ${declared.map((key) => `${key}=${recordValueOrNotShown(properties[key])}`).join(", ")}, but the physical id's destination segment is ${recordValueOrNotShown(segment)}. CloudFormation identifies the route by the destination, so IMPORT would adopt whatever route currently sits at ${recordValueOrNotShown(identifier)} — and if that is a DIFFERENT route than the template declares, phase 2 would then REPLACE (delete) it. The state entry is stale; re-deploy the resource to refresh it`;
15533
15655
  if (declaredValues.every((value) => routeDestinationNormalizationIsModelled(value))) throw new Error(`${shared}.`);
15534
- getLogger().warn(displayAwsMessage(`${shared}, or pass the resource through 'cdkd import --resource' with the correct id. Continuing with the physical id because at least one recorded destination is an IPv6 CIDR, whose AWS-side canonicalization cdkd does not model — so the difference may be benign.`));
15656
+ getLogger().warn(displayAwsMessage(`${shared}, or pass the resource through ${proseQuoted(cdkdRemedy("cdkd import", "--resource"))} with the correct id. Continuing with the physical id because at least one recorded destination is an IPv6 CIDR, whose AWS-side canonicalization cdkd does not model — so the difference may be benign.`));
15535
15657
  return identifier;
15536
15658
  }
15537
15659
  const ROUTE_PREFIX_LIST_ID_PATTERN = /^pl-[0-9a-f]+$/;
@@ -16476,7 +16598,7 @@ function refusalReason(current) {
16476
16598
  return Array.isArray(current) && current.some((e) => e !== null && typeof e === "object" && !Array.isArray(e)) ? "cdkd will not rewrite it, because doing so would discard the intrinsic it carries" : "cdkd will not replace a value it cannot represent as the scalar the schema declares";
16477
16599
  }
16478
16600
  function unrepresentableOverlayMessage(entry, field, current, value) {
16479
- return `${rowIdent(entry.logicalId)} (${rowIdent(entry.resourceType)}): the identifier property ${displayIdent(field)} is ${describeOverlayValueShape(current)}, but CloudFormation types it as a string. ${refusalReason(current)}. Declare ${displayIdent(field)} as the scalar ${showRecordValue(value)} (or drop the addPropertyOverride that made it a list) and re-run 'cdkd export'.`;
16601
+ return `${rowIdent(entry.logicalId)} (${rowIdent(entry.resourceType)}): the identifier property ${displayIdent(field)} is ${describeOverlayValueShape(current)}, but CloudFormation types it as a string. ${refusalReason(current)}. Declare ${displayIdent(field)} as the scalar ${showRecordValue(value)} (or drop the addPropertyOverride that made it a list) and re-run ${proseQuoted(cdkdRemedy("cdkd export"))}.`;
16480
16602
  }
16481
16603
  function unrepresentableOverlayFields(resource, overlay) {
16482
16604
  if (!resource || typeof resource !== "object" || Array.isArray(resource)) return [];
@@ -16674,7 +16796,12 @@ async function buildImportPlan(state, template, cfnClient, parentStackName, opti
16674
16796
  blocked.push({
16675
16797
  logicalId,
16676
16798
  resourceType,
16677
- reason: `cdkd state holds only the redaction mask ('***') for at least one property, and cdkd cannot re-derive the value. There are four ways a record comes to hold it. (1) A NoEcho custom-resource value: forcing the custom resource to update does NOT clear this — the handler supplies the value to the deploy and cdkd re-masks it on the way into state, so the export still has nothing to declare. Stop setting NoEcho on that response and re-deploy, then export again. (2) The Fn::Base64 encoding of a secret value (a {{resolve:...}} dynamic reference under Fn::Base64, such as EC2 UserData): cdkd never records that encoding, so re-deploying the same template does not clear this. Stop encoding the secret into the property (have the resource read the secret at run time instead — not by writing the secret's plaintext into the template, which cdkd would then record in state in the clear) and re-deploy, then export again. (3) The value was SPLICED from a masked record of ANOTHER resource — by 'cdkd orphan --force', or by 'cdkd import' resolving an Fn::GetAtt or a Ref over a value the Cloud Control fallback had masked. Repair the record that HOLDS the mask with cdkd import ${commandHole("stack")} --resource ${commandHole("logicalId")}=${commandHole("physicalId")} --force (granting cloudformation:DescribeType first if the import warned that it could not read the schema), then re-run whichever command wrote this property. (4) Two secret values cdkd resolved overlap inside the value, so no single {{resolve:...}} reference renders it: change the property (or rotate one of the secrets) so that they no longer overlap, re-deploy, then export again. In every case you can also export this stack without that resource and adopt it into CloudFormation by hand. See https://github.com/go-to-k/cdkd/issues/2274.`
16799
+ reason: `cdkd state holds only the redaction mask ('***') for at least one property, and cdkd cannot re-derive the value. There are four ways a record comes to hold it. (1) A NoEcho custom-resource value: forcing the custom resource to update does NOT clear this — the handler supplies the value to the deploy and cdkd re-masks it on the way into state, so the export still has nothing to declare. Stop setting NoEcho on that response and re-deploy, then export again. (2) The Fn::Base64 encoding of a secret value (a {{resolve:...}} dynamic reference under Fn::Base64, such as EC2 UserData): cdkd never records that encoding, so re-deploying the same template does not clear this. Stop encoding the secret into the property (have the resource read the secret at run time instead — not by writing the secret's plaintext into the template, which cdkd would then record in state in the clear) and re-deploy, then export again. (3) The value was SPLICED from a masked record of ANOTHER resource — by 'cdkd orphan --force', or by 'cdkd import' resolving an Fn::GetAtt or a Ref over a value the Cloud Control fallback had masked. Repair the record that HOLDS the mask with ${pasteableCommand("cdkd import", [
16800
+ { hole: "stack" },
16801
+ { literal: "--resource" },
16802
+ { literal: `${commandHole("logicalId")}=${commandHole("physicalId")}` },
16803
+ { literal: "--force" }
16804
+ ]).command} (granting cloudformation:DescribeType first if the import warned that it could not read the schema), then re-run whichever command wrote this property. (4) Two secret values cdkd resolved overlap inside the value, so no single {{resolve:...}} reference renders it: change the property (or rotate one of the secrets) so that they no longer overlap, re-deploy, then export again. In every case you can also export this stack without that resource and adopt it into CloudFormation by hand. See https://github.com/go-to-k/cdkd/issues/2274.`
16678
16805
  });
16679
16806
  continue;
16680
16807
  }
@@ -16839,12 +16966,12 @@ function sharedImportIdentifierReason(others) {
16839
16966
  return `this resource and ${named.length === others.length ? `${others.length === 1 ? "resource" : "resources"} ${named.join(", ")}` : `${others.length} other resource(s) of this stack`} are the SAME AWS resource (template rules that resolve to one security group rule), and a CloudFormation import adopts a resource into only one logical id. Remove all but one of them from the app before exporting, then add the others back with a CloudFormation stack update: CloudFormation accepts a rule identical to an existing one and records the same rule for it.`;
16840
16967
  }
16841
16968
  function blockedMigrationTail(blocked) {
16842
- const generic = "destroy them first (cdkd destroy / cdkd state destroy cherry-picked), or remove them from the CDK app and re-synthesize.";
16969
+ const generic = `destroy them first (${cdkdRemedy("cdkd destroy")} / ${cdkdRemedy("cdkd state destroy")} cherry-picked), or remove them from the CDK app and re-synthesize.`;
16843
16970
  const manualIds = new Set(blocked.filter((b) => b.manual).map((b) => b.logicalId));
16844
16971
  const genericIds = new Set(blocked.filter((b) => b.repair === void 0 && !b.manual && !manualIds.has(b.logicalId)).map((b) => b.logicalId));
16845
16972
  const hasRepair = blocked.some((b) => b.repair !== void 0 && !genericIds.has(b.logicalId) && !manualIds.has(b.logicalId));
16846
16973
  const hasManual = manualIds.size > 0;
16847
- if (genericIds.size === 0 && !hasManual) return "Run each row's 'Repair with:' command, then re-run cdkd export.";
16974
+ if (genericIds.size === 0 && !hasManual) return `Run each row's 'Repair with:' command, then re-run ${cdkdRemedy("cdkd export")}.`;
16848
16975
  if (!hasRepair && !hasManual) return `Either ${generic}`;
16849
16976
  const steps = [];
16850
16977
  if (hasRepair) steps.push("run each 'Repair with:' command given");
@@ -16968,7 +17095,7 @@ function reportDriftBaselineGaps(state, logger, loaded, template, recovery) {
16968
17095
  ...account
16969
17096
  ]).command;
16970
17097
  const unreadable = entries.filter(([, r]) => !isReadableResourceEntry(r)).map(([logicalId]) => logicalId);
16971
- logger.warn(`${unreadable.length} of ${entries.length} resource(s) in cdkd state have a record that is not readable as a resource — not an object, or carrying no resource type — so their drift baseline cannot be reported on. The state record is malformed or truncated. ` + (inspect.exact ? "" : `A quoted '<...>' hole in the command after the list below stands for a value cdkd could not ` + (stackName.startsWith("-") ? "print safely. This stack name begins with '-', which the CLI could read as an option however it is quoted, so do not fill the stack hole with it: repair or remove the record by hand. " : `print safely; fill it from 'cdkd state list --json'` + (account.length > 0 ? ` run with the same account flags as the command after the list below` : "") + `, replacing the hole, quotes included, with ${JSON_LISTING_HOLE_VALUE}. `)) + accountNote("the command after the list below prints") + `Inspect it with the command after the list below.`);
17098
+ logger.warn(`${unreadable.length} of ${entries.length} resource(s) in cdkd state have a record that is not readable as a resource — not an object, or carrying no resource type — so their drift baseline cannot be reported on. The state record is malformed or truncated. ` + (inspect.exact ? "" : `A quoted '<...>' hole in the command after the list below stands for a value cdkd could not ` + (stackName.startsWith("-") ? "print safely. This stack name begins with '-', which the CLI could read as an option however it is quoted, so do not fill the stack hole with it: repair or remove the record by hand. " : `print safely; fill it from ${proseQuoted(cdkdRemedy("cdkd state list", "--json"))}` + (account.length > 0 ? ` run with the same account flags as the command after the list below` : "") + `, replacing the hole, quotes included, with ${JSON_LISTING_HOLE_VALUE}. `)) + accountNote("the command after the list below prints") + `Inspect it with the command after the list below.`);
16972
17099
  for (const logicalId of unreadable.slice(0, NAMED_BASELINE_IDS)) logger.warn(` ${displayLogicalId(logicalId)}`);
16973
17100
  if (unreadable.length > NAMED_BASELINE_IDS) logger.warn(` ... and ${unreadable.length - NAMED_BASELINE_IDS} more`);
16974
17101
  logger.warn(safeMsg`Inspect it with: ${inspectCommand}`);
@@ -16982,7 +17109,7 @@ function reportDriftBaselineGaps(state, logger, loaded, template, recovery) {
16982
17109
  const refused = missing.filter(([, r]) => r.observedBaselineRefused === true);
16983
17110
  const refreshable = missing.filter(([, r]) => r.observedBaselineRefused !== true);
16984
17111
  if (refreshable.length > 0) {
16985
- logger.warn(`${refreshable.length} of ${entries.length} resource(s) in cdkd state lack an AWS-current baseline (observedProperties). cdkd drift may produce false positives for them; the next 'cdk deploy' after migration may surface unexpected changes. ` + (unreadableCount > 0 ? `Repair the ${unreadableCount} unreadable record(s) named above first — 'cdkd state refresh-observed' refuses a record that holds one. Then capture a baseline and run 'cdkd drift' to verify the stack matches AWS.` : refreshCommand !== void 0 ? `${refreshNote}Capture a baseline before export, then run 'cdkd drift' to verify the stack matches AWS, with: ${refreshCommand}` : `Capture a baseline before export with ${refreshWithheld} Then run 'cdkd drift' to verify the stack matches AWS.`));
17112
+ logger.warn(`${refreshable.length} of ${entries.length} resource(s) in cdkd state lack an AWS-current baseline (observedProperties). cdkd drift may produce false positives for them; the next 'cdk deploy' after migration may surface unexpected changes. ` + (unreadableCount > 0 ? `Repair the ${unreadableCount} unreadable record(s) named above first — 'cdkd state refresh-observed' refuses a record that holds one. Then capture a baseline and run ${proseQuoted(cdkdRemedy("cdkd drift"))} to verify the stack matches AWS.` : refreshCommand !== void 0 ? `${refreshNote}Capture a baseline before export, then run ${proseQuoted(cdkdRemedy("cdkd drift"))} to verify the stack matches AWS, with: ${refreshCommand}` : `Capture a baseline before export with ${refreshWithheld} Then run ${proseQuoted(cdkdRemedy("cdkd drift"))} to verify the stack matches AWS.`));
16986
17113
  for (const [logicalId] of refreshable.slice(0, NAMED_BASELINE_IDS)) logger.warn(` ${displayLogicalId(logicalId)}`);
16987
17114
  if (refreshable.length > NAMED_BASELINE_IDS) logger.warn(` ... and ${refreshable.length - NAMED_BASELINE_IDS} more`);
16988
17115
  }
@@ -17730,7 +17857,7 @@ async function exportCommand(stackArg, options) {
17730
17857
  refuseMalformedResourcePropertiesForExport(state, resolvedStackName, recordRegion, lockRecovery);
17731
17858
  const exportJournal = await stateBackend.loadRollbackJournal(resolvedStackName, targetRegion);
17732
17859
  if (exportJournal && exportJournal.segments.length > 0) {
17733
- logger.warn(`Stack ${quotedOrNotShown(resolvedStackName)} has a rollback journal — a previous deploy failed or was interrupted and has not been reverted. Exporting this half-deployed state to CloudFormation is likely unintended; revert it first (or 'cdkd deploy' to fix forward).\nRevert it with: ${pasteableCommand("cdkd rollback", [{
17860
+ logger.warn(`Stack ${quotedOrNotShown(resolvedStackName)} has a rollback journal — a previous deploy failed or was interrupted and has not been reverted. Exporting this half-deployed state to CloudFormation is likely unintended; revert it first (or ${proseQuoted(cdkdRemedy("cdkd deploy"))} to fix forward).\nRevert it with: ${pasteableCommand("cdkd rollback", [{
17734
17861
  value: resolvedStackName,
17735
17862
  hole: "stack"
17736
17863
  }]).command}`);
@@ -17967,7 +18094,7 @@ async function printStackShow(stackName, options, setup) {
17967
18094
  const ref = resolveSingleRegion(stackName, refs, options.stackRegion);
17968
18095
  if (!ref.region) throw legacyRecordRefusal(stackName);
17969
18096
  const [stateResult, lockInfo] = await Promise.all([setup.stateBackend.getState(stackName, ref.region), setup.lockManager.getLockInfo(stackName, ref.region)]);
17970
- if (!stateResult) throw new Error(`No state found for stack ${formatStackRefSafe(ref)} in s3://${setup.bucket}/${setup.prefix}/. Run 'cdkd state list' to see available stacks.`);
18097
+ if (!stateResult) throw new Error(`No state found for stack ${formatStackRefSafe(ref)} in s3://${setup.bucket}/${setup.prefix}/. Run ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
17971
18098
  if (options.showNested) {
17972
18099
  const treeWithLocks = await loadLocksForTree(await buildCdkdStateStackTree(stackName, ref.region, setup.stateBackend, stateResult.state, renderRecovery(options, setup)), setup.lockManager, lockInfo);
17973
18100
  if (options.json) {
@@ -18545,8 +18672,17 @@ async function orphanCommand(pathArgs, options) {
18545
18672
  roleArn: options.roleArn,
18546
18673
  region: options.region
18547
18674
  });
18548
- if (pathArgs.length === 0) throw new Error("'cdkd orphan' requires at least one construct path, e.g. 'cdkd orphan MyStack/MyTable'.\n To remove a stack's state record (the previous behavior), use:\n cdkd state orphan MyStack");
18549
- for (const p of pathArgs) if (!p.includes("/")) throw new Error(`'cdkd orphan' now expects a construct path like 'MyStack/MyTable'.\n Got: '${p}'\n To remove a stack's state record (the previous behavior), use:\n cdkd state orphan ${p}`);
18675
+ if (pathArgs.length === 0) throw new Error(`'cdkd orphan' requires at least one construct path, e.g. 'cdkd orphan MyStack/MyTable'.
18676
+ To remove a stack's state record (the previous behavior), use:
18677
+ ${pasteableCommand("cdkd state orphan", [{
18678
+ value: "MyStack",
18679
+ hole: "stack"
18680
+ }]).command}`);
18681
+ for (const p of pathArgs) if (!p.includes("/")) throw new Error(`'cdkd orphan' now expects a construct path like 'MyStack/MyTable'.\n Got: '${p}'\n To remove a stack's state record (the previous behavior), use:\n ${pasteableCommand("cdkd state orphan", [{
18682
+ value: p,
18683
+ hole: "stack",
18684
+ opts: { patternMatched: true }
18685
+ }]).command}`);
18550
18686
  const effectiveRegion = await resolveEffectiveRegion(options);
18551
18687
  exportInferredRegionForSdk(effectiveRegion);
18552
18688
  const region = effectiveRegion.region;
@@ -18680,7 +18816,7 @@ function resolveConstructPaths(paths, stacks) {
18680
18816
  throw new Error(`Construct path '${p}' does not start with the path of any stack in the synthesized app. ` + (stacks.length > 0 ? `Available: ${available}` : "The assembly has no stacks"));
18681
18817
  }
18682
18818
  if (stack === void 0) stack = candidate;
18683
- else if (stack.stackName !== candidate.stackName) throw new Error(`All construct paths must reference the same stack. Got ${displayStackName(stack.stackName)} and ${displayStackName(candidate.stackName)}. Run 'cdkd orphan' once per stack.`);
18819
+ else if (stack.stackName !== candidate.stackName) throw new Error(`All construct paths must reference the same stack. Got ${displayStackName(stack.stackName)} and ${displayStackName(candidate.stackName)}. Run ${proseQuoted(cdkdRemedy("cdkd orphan"))} once per stack.`);
18684
18820
  const index = buildCdkPathIndex(candidate.template);
18685
18821
  const matches = resolveCdkPathToLogicalIds(p, index);
18686
18822
  if (matches.length === 0) {
@@ -18706,7 +18842,7 @@ async function pickStackRegion(stateBackend, stackName, synthRegion, flag) {
18706
18842
  region: synthRegion,
18707
18843
  recordRegion: synthRegion
18708
18844
  };
18709
- throw new Error(`No state found for stack ${displayStackName(stackName)}. Run 'cdkd state list' to see available stacks.`);
18845
+ throw new Error(`No state found for stack ${displayStackName(stackName)}. Run ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
18710
18846
  }
18711
18847
  if (flag) {
18712
18848
  if (!refs.find((r) => r.region === flag)) {
@@ -18782,7 +18918,7 @@ async function clearRetainedQuietly(backend, stackName, region, logger) {
18782
18918
  await backend.saveRetainedResources(stackName, region, []);
18783
18919
  return true;
18784
18920
  } catch (error) {
18785
- logger.warn(safeMsg`Could not empty the kept-resource record of ${displayStackName(stackName)} ` + safeMsg`(${describeAwsFailure(error).summary}): a later deploy here may still take a kept ` + `resource back. Re-run 'cdkd state orphan' once it can write.`);
18921
+ logger.warn(safeMsg`Could not empty the kept-resource record of ${displayStackName(stackName)} ` + safeMsg`(${describeAwsFailure(error).summary}): a later deploy here may still take a kept ` + safeMsg`resource back. Re-run ${proseQuoted(cdkdRemedy("cdkd state orphan"))} once it can write.`);
18786
18922
  return false;
18787
18923
  }
18788
18924
  }
@@ -18817,9 +18953,9 @@ async function clearRetainedWithoutRecord(backend, stackName, stackRegion, logge
18817
18953
  async function stateOrphanCommand(stackArgs, options) {
18818
18954
  const logger = getLogger();
18819
18955
  if (options.verbose) logger.setLevel("debug");
18820
- if (stackArgs.length === 0) throw new Error(`Stack name is required. Usage: cdkd state orphan ${commandHole("stacks...")}`);
18956
+ if (stackArgs.length === 0) throw new Error(`Stack name is required. Usage: ${pasteableCommand("cdkd state orphan", [{ hole: "stacks..." }]).command}`);
18821
18957
  if (options.resource !== void 0 && options.resource.length > 0) {
18822
- if (stackArgs.length !== 1) throw new Error(`--resource names resources of ONE stack, but ${stackArgs.length} stacks were given. Run 'cdkd state orphan' once per stack.`);
18958
+ if (stackArgs.length !== 1) throw new Error(`--resource names resources of ONE stack, but ${stackArgs.length} stacks were given. Run ${proseQuoted(cdkdRemedy("cdkd state orphan"))} once per stack.`);
18823
18959
  await stateOrphanResources(stackArgs[0], options.resource, options);
18824
18960
  return;
18825
18961
  }
@@ -18835,7 +18971,7 @@ async function stateOrphanCommand(stackArgs, options) {
18835
18971
  logger.info(safeMsg`Cleared the kept-resource record of ${plainOrDescribed(stackName, "stack name")} ` + safeMsg`(${cleared.map((r) => displaySafe(r, { asciiOnly: true })).join(", ")}): ` + `a later deploy here no longer takes a kept resource back.`);
18836
18972
  continue;
18837
18973
  }
18838
- logger.info(safeMsg`No state found for stack: ${plainOrDescribed(stackName, "stack name")}, skipping` + (isPasteableIdent(stackName) ? "" : safeMsg`. ${STATE_LIST_POINTER}`));
18974
+ logger.info(safeMsg`No state found for stack: ${plainOrDescribed(stackName, "stack name")}, skipping` + (isPasteableIdent(stackName) ? "" : safeMsg`. ${stateListPointer()}`));
18839
18975
  continue;
18840
18976
  }
18841
18977
  const targets = options.stackRegion !== void 0 ? stackRefs.filter((r) => r.region === options.stackRegion) : stackRefs;
@@ -18867,7 +19003,7 @@ async function stateOrphanCommand(stackArgs, options) {
18867
19003
  }
18868
19004
  }, ...accountArgs(bannerAccount)]);
18869
19005
  const bannerAccountClause = withheldAccountClause(bannerAccount, "the command below prints").trimEnd();
18870
- process.stdout.write(`\nWARNING: This removes cdkd's state record for [${targetList}] only. AWS resources will NOT be deleted.` + (targets.some(refIsDescribed) ? ` ${STATE_LIST_POINTER}` : "") + "\nDelete the actual resources instead with the command below." + withheldTargetClause(destroyCmd, "stack", "cdkd destroy") + (bannerAccountClause === "" ? "" : ` ${bannerAccountClause}`) + `\nDestroy with: ${destroyCmd.command}\n\n`);
19006
+ process.stdout.write(`\nWARNING: This removes cdkd's state record for [${targetList}] only. AWS resources will NOT be deleted.` + (targets.some(refIsDescribed) ? ` ${stateListPointer()}` : "") + "\nDelete the actual resources instead with the command below." + withheldTargetClause(destroyCmd, "stack", "cdkd destroy") + (bannerAccountClause === "" ? "" : ` ${bannerAccountClause}`) + `\nDestroy with: ${destroyCmd.command}\n\n`);
18871
19007
  if (!await confirmStateOrphanRemoval(`Remove state for ${targetList} from s3://${setup.bucket}/${setup.prefix}/?`)) {
18872
19008
  logger.info(safeMsg`Cancelled removal of state for stack: ${plainOrDescribed(stackName, "stack name")}`);
18873
19009
  continue;
@@ -18886,7 +19022,7 @@ async function stateOrphanCommand(stackArgs, options) {
18886
19022
  await setup.lockManager.forceReleaseLock(stackName, void 0);
18887
19023
  await clearRetainedWithoutRecord(setup.stateBackend, stackName, void 0, logger);
18888
19024
  }
18889
- logger.info(safeMsg`✓ Removed state for stack: ${describedStackRef(target)}` + ((options.yes || options.force) && refIsDescribed(target) ? safeMsg`. ${STATE_LIST_POINTER}` : ""));
19025
+ logger.info(safeMsg`✓ Removed state for stack: ${describedStackRef(target)}` + ((options.yes || options.force) && refIsDescribed(target) ? safeMsg`. ${stateListPointer()}` : ""));
18890
19026
  }
18891
19027
  }
18892
19028
  } finally {
@@ -18922,7 +19058,7 @@ async function stateOrphanResources(stackName, requested, options) {
18922
19058
  }));
18923
19059
  try {
18924
19060
  const stateData = await setup.stateBackend.getState(stackName, region);
18925
- if (!stateData) throw new Error(`No state found for ${describedStackRef(ref)} in s3://${setup.bucket}/${setup.prefix}/. Run 'cdkd state list' to see available stacks.`);
19061
+ if (!stateData) throw new Error(`No state found for ${describedStackRef(ref)} in s3://${setup.bucket}/${setup.prefix}/. Run ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
18926
19062
  const { state, etag, migrationPending } = stateData;
18927
19063
  refuseMalformedState(state, stackName, region, recovery);
18928
19064
  refuseMalformedOutputs(state, stackName, region, recovery);
@@ -18954,7 +19090,7 @@ async function stateOrphanResources(stackName, requested, options) {
18954
19090
  ...accountArgs(recovery)
18955
19091
  ]);
18956
19092
  const accountClause = withheldAccountClause(recovery, "the command below prints").trimEnd();
18957
- throw new Error(`${capitalize(plainOrDescribed(id, "logical id"))} has a nested stack's state record of its own. The child's resources are recorded there, and removing this row would leave that record behind with nothing that removes it. Drop the child's record first (it keeps the child's AWS resources; a child with nested stacks of its own has records under '<child>~<logicalId>' too), then re-run.` + withheldTargetClause(childCommand, "stack", "cdkd state orphan") + (otherRegions > 0 ? ` The child also has records in ${otherRegions} other region(s); 'cdkd state list' shows them, and each needs the same drop.` : "") + (accountClause === "" ? "" : ` ${accountClause}`) + `\nDrop the child with: ${childCommand.command}`);
19093
+ throw new Error(`${capitalize(plainOrDescribed(id, "logical id"))} has a nested stack's state record of its own. The child's resources are recorded there, and removing this row would leave that record behind with nothing that removes it. Drop the child's record first (it keeps the child's AWS resources; a child with nested stacks of its own has records under '<child>~<logicalId>' too), then re-run.` + withheldTargetClause(childCommand, "stack", "cdkd state orphan") + (otherRegions > 0 ? ` The child also has records in ${otherRegions} other region(s); ${proseQuoted(cdkdRemedy("cdkd state list"))} shows them, and each needs the same drop.` : "") + (accountClause === "" ? "" : ` ${accountClause}`) + `\nDrop the child with: ${childCommand.command}`);
18958
19094
  }
18959
19095
  clients = new AwsClients({
18960
19096
  region,
@@ -18981,7 +19117,7 @@ async function stateOrphanResources(stackName, requested, options) {
18981
19117
  });
18982
19118
  const idList = logicalIds.map((id) => displayIdent(id)).join(", ");
18983
19119
  if (!options.yes && !options.force) {
18984
- process.stdout.write(`\nWARNING: This removes cdkd's state record of ${logicalIds.length} resource(s) [${idList}] from ${describedStackRef(ref)} only. AWS resources will NOT be deleted, and cdkd stops managing them. The stack's other records are kept.` + (refIsDescribed(ref) ? ` ${STATE_LIST_POINTER}` : "") + `\n\n`);
19120
+ process.stdout.write(`\nWARNING: This removes cdkd's state record of ${logicalIds.length} resource(s) [${idList}] from ${describedStackRef(ref)} only. AWS resources will NOT be deleted, and cdkd stops managing them. The stack's other records are kept.` + (refIsDescribed(ref) ? ` ${stateListPointer()}` : "") + `\n\n`);
18985
19121
  if (!await confirmStateOrphanRemoval(`Remove the record(s) of ${idList} from state for ${describedStackRef(ref)}?`, { resource: true })) {
18986
19122
  logger.info(safeMsg`Cancelled removal of resource record(s) for stack: ${plainOrDescribed(stackName, "stack name")}`);
18987
19123
  return;
@@ -19032,7 +19168,7 @@ async function protectedRootOf(stackName, state, region, backend) {
19032
19168
  }
19033
19169
  }
19034
19170
  async function stateDestroyCommand(stackArgs, options) {
19035
- if (options.all) throw new CdkdError(`cdkd state destroy no longer accepts --all: it destroyed every stack in the state bucket, which every CDK app deployed to this account shares, so one command reached across apps. Name each stack to destroy: cdkd state destroy ${commandHole("stacks...")} (cdkd state list shows them), or run cdkd destroy --all from the CDK app, which destroys only that app's top-level stacks (cdkd destroy '**' destroys its CDK Stage stacks too).`, "STATE_DESTROY_ALL_REMOVED");
19171
+ if (options.all) throw new CdkdError(`cdkd state destroy no longer accepts --all: it destroyed every stack in the state bucket, which every CDK app deployed to this account shares, so one command reached across apps. Name each stack to destroy: ${pasteableCommand("cdkd state destroy", [{ hole: "stacks..." }]).command} (${cdkdRemedy("cdkd state list")} shows them), or run ${cdkdRemedy("cdkd destroy", "--all")} from the CDK app, which destroys only that app's top-level stacks (cdkd destroy '**' destroys its CDK Stage stacks too).`, "STATE_DESTROY_ALL_REMOVED");
19036
19172
  const providerClasses = await loadProviderClasses();
19037
19173
  const logger = getLogger();
19038
19174
  if (options.verbose) {
@@ -19041,7 +19177,7 @@ async function stateDestroyCommand(stackArgs, options) {
19041
19177
  }
19042
19178
  validateResourceTimeouts(options);
19043
19179
  setResolvedResourceTimeouts(options.resourceTimeout);
19044
- if (stackArgs.length === 0) throw new Error(`Stack name is required. Usage: cdkd state destroy ${commandHole("stacks...")}`);
19180
+ if (stackArgs.length === 0) throw new Error(`Stack name is required. Usage: ${pasteableCommand("cdkd state destroy", [{ hole: "stacks..." }]).command}`);
19045
19181
  const setup = await setupStateBackend(options);
19046
19182
  if (options.region) {
19047
19183
  process.env["AWS_REGION"] = setup.region;
@@ -19065,7 +19201,7 @@ async function stateDestroyCommand(stackArgs, options) {
19065
19201
  const stateRefs = await setup.stateBackend.listStacks();
19066
19202
  const knownStackNames = new Set(stateRefs.map((r) => r.stackName));
19067
19203
  const missing = stackArgs.filter((name) => !knownStackNames.has(name));
19068
- if (missing.length > 0) throw new Error(`No state found for stack(s): ${missing.map(listedStackName).join(", ")}.\nRun 'cdkd state list' to see available stacks.`);
19204
+ if (missing.length > 0) throw new Error(`No state found for stack(s): ${missing.map(listedStackName).join(", ")}.\nRun ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
19069
19205
  const stackNames = stackArgs;
19070
19206
  logger.info(safeMsg`Found ${stackNames.length} stack(s) to destroy: ${stackNames.map(listedStackName).join(", ")}`);
19071
19207
  let totalErrors = 0;
@@ -19081,10 +19217,19 @@ async function stateDestroyCommand(stackArgs, options) {
19081
19217
  });
19082
19218
  const crossPrefixCheck = { cache: new CrossPrefixGuard(setup.stateBackend) };
19083
19219
  if (stackNames.length > 1) deferRegistryTail = (released) => deferredTails.push(released);
19220
+ const customResourceTargets = [];
19084
19221
  for (const name of stackNames) {
19085
19222
  const refs = stateRefs.filter((r) => r.stackName === name);
19086
- for (const ref of stateDestroyTargets(refs, options.stackRegion) ?? []) crossPrefixCheck.cache.full(name, ref.region ?? await setup.regionFor(name), "prestart");
19223
+ for (const ref of stateDestroyTargets(refs, options.stackRegion) ?? []) {
19224
+ const targetRegion = ref.region ?? await setup.regionFor(name);
19225
+ crossPrefixCheck.cache.full(name, targetRegion, "prestart");
19226
+ customResourceTargets.push({
19227
+ stackName: name,
19228
+ region: targetRegion
19229
+ });
19230
+ }
19087
19231
  }
19232
+ await refuseDestroyTargetsWithoutApp(customResourceTargets, setup.stateBackend, setup.awsClients);
19088
19233
  for (const [stackIndex, stackName] of stackNames.entries()) {
19089
19234
  const refs = stateRefs.filter((r) => r.stackName === stackName);
19090
19235
  let targets;
@@ -19213,8 +19358,11 @@ async function stateDestroyCommand(stackArgs, options) {
19213
19358
  break;
19214
19359
  }
19215
19360
  }
19216
- if (totalErrors > 0) throw new PartialFailureError(`Destroy completed with ${totalErrors} resource error(s). State preserved — inspect 'cdkd state show <stack>' and re-run 'cdkd state destroy' to retry. If the same resource keeps failing, 'cdkd state orphan <stack> --stack-region <region>' removes the stack's state in that region (every resource's record) without deleting AWS resources.`);
19217
- if (interrupted || interruptWatch.interrupted() && stoppedEarly) throw new PartialFailureError(`Destroy interrupted by Ctrl-C. State preserved — re-run 'cdkd state destroy' to finish.`);
19361
+ if (totalErrors > 0) throw new PartialFailureError(`Destroy completed with ${totalErrors} resource error(s). State preserved — inspect ${pasteableCommand("cdkd state show", [{ hole: "stack" }]).command} and re-run ${proseQuoted(cdkdRemedy("cdkd state destroy"))} to retry. If the same resource keeps failing, ${pasteableCommand("cdkd state orphan", [{ hole: "stack" }, {
19362
+ flag: "--stack-region",
19363
+ hole: "region"
19364
+ }]).command} removes the stack's state in that region (every resource's record) without deleting AWS resources.`);
19365
+ if (interrupted || interruptWatch.interrupted() && stoppedEarly) throw new PartialFailureError(`Destroy interrupted by Ctrl-C. State preserved — re-run ${proseQuoted(cdkdRemedy("cdkd state destroy"))} to finish.`);
19218
19366
  if (totalSkipped > 0) throw new PartialFailureError(skippedDestroyMessage(totalSkipped, totalOrphanSkips, "cdkd state destroy"));
19219
19367
  } finally {
19220
19368
  await Promise.allSettled(deferredTails);
@@ -19401,7 +19549,7 @@ async function stateInfoCommand(options) {
19401
19549
  lines.push(`Source: ${formatBucketSource(resolved.source)}`);
19402
19550
  lines.push(`Schema version: ${schemaVersion}`);
19403
19551
  lines.push(`Stacks: ${stateFileKeys.length}`);
19404
- if (assetStorage.length === 0) lines.push("Asset storage: legacy (CDK bootstrap) — run cdkd bootstrap to opt in");
19552
+ if (assetStorage.length === 0) lines.push(`Asset storage: legacy (CDK bootstrap) — run ${cdkdRemedy("cdkd bootstrap")} to opt in`);
19405
19553
  else {
19406
19554
  lines.push(`Asset storage: cdkd-assets mode in ${assetStorage.length} region(s)`);
19407
19555
  for (const entry of assetStorage) lines.push(` ${displayIdent(entry.region)}: ${displayIdent(entry.assetBucket)} / ${displayIdent(entry.containerRepo, { maxCodePoints: STACK_REF_MAX_CODE_POINTS })}`);
@@ -19448,7 +19596,7 @@ function judgeAcceptRefused(record, logicalId, template, stack) {
19448
19596
  };
19449
19597
  if (record.observedBaselineRefused !== true) return {
19450
19598
  ok: false,
19451
- reason: `${id} carries no observed-baseline refusal, so there is nothing to accept. Run 'cdkd state refresh-observed' without --accept-refused to refresh it.`
19599
+ reason: `${id} carries no observed-baseline refusal, so there is nothing to accept. Run ${proseQuoted(cdkdRemedy("cdkd state refresh-observed"))} without --accept-refused to refresh it.`
19452
19600
  };
19453
19601
  const reason = record.observedBaselineRefusalReason;
19454
19602
  if (reason === "incomplete-resolution") return {
@@ -19737,7 +19885,7 @@ async function refreshObservedForStack(stackName, region, stateBackend, lockMana
19737
19885
  region
19738
19886
  });
19739
19887
  const result = await stateBackend.getState(stackName, region);
19740
- if (!result) throw new Error(safeMsg`No state found for stack ${ref}. ` + `Run 'cdkd state list' to see available stacks.`);
19888
+ if (!result) throw new Error(safeMsg`No state found for stack ${ref}. ` + `Run ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
19741
19889
  const { state, etag, migrationPending } = result;
19742
19890
  refuseMalformedState(state, stackName, region, lockRecovery);
19743
19891
  refuseMalformedResourceEntries(state, stackName, region, lockRecovery);
@@ -19986,7 +20134,7 @@ async function stateRefreshObservedCommand(stackArgs, options) {
19986
20134
  }
19987
20135
  if (!options.yes && !options.dryRun && accept === void 0) {
19988
20136
  const targetList = targets.map(describedStackRef).join(", ");
19989
- if (targets.some(refIsDescribed)) logger.info(STATE_LIST_POINTER);
20137
+ if (targets.some(refIsDescribed)) logger.info(stateListPointer());
19990
20138
  if (!await confirmRefresh(`Refresh observedProperties for ${targets.length} stack(s) (${targetList})?`)) {
19991
20139
  logger.info("Aborted.");
19992
20140
  return;
@@ -20034,7 +20182,7 @@ async function stateRefreshObservedCommand(stackArgs, options) {
20034
20182
  }
20035
20183
  if (totalFailed > 0 || totalNotFound > 0) {
20036
20184
  const parts = [];
20037
- if (totalFailed > 0) parts.push(`${totalFailed} per-resource readback failure(s); re-run 'cdkd state refresh-observed' to retry them.`);
20185
+ if (totalFailed > 0) parts.push(`${totalFailed} per-resource readback failure(s); re-run ${proseQuoted(cdkdRemedy("cdkd state refresh-observed"))} to retry them.`);
20038
20186
  if (totalNotFound > 0) parts.push(`${totalNotFound} resource(s) not found in AWS (deleted outside cdkd); a retry will not change that, and 'cdkd drift' reports them as deleted.`);
20039
20187
  throw new PartialFailureError(`Refresh completed with ${parts.join(" ")} Affected resources keep their previous observedProperties (or no observedProperties at all).`);
20040
20188
  }
@@ -20173,7 +20321,7 @@ const VIEW_ITEMS = [
20173
20321
  }
20174
20322
  ];
20175
20323
  function nonInteractiveBrowseRefusal() {
20176
- return new CdkdError("cdkd state browse needs an interactive terminal. Without one, use cdkd state list, cdkd state resources <stack> and cdkd state show <stack>.", "NON_INTERACTIVE");
20324
+ return new CdkdError(`cdkd state browse needs an interactive terminal. Without one, use ${cdkdRemedy("cdkd state list")}, ${pasteableCommand("cdkd state resources", [{ hole: "stack" }]).command} and ${pasteableCommand("cdkd state show", [{ hole: "stack" }]).command}.`, "NON_INTERACTIVE");
20177
20325
  }
20178
20326
  async function runStateBrowse(deps) {
20179
20327
  if (!isInteractiveTerminal(deps.streams)) throw nonInteractiveBrowseRefusal();
@@ -20436,6 +20584,24 @@ function rerunRollback(stackName) {
20436
20584
  }]);
20437
20585
  return withheldTargetClause(rerun, "stack", "cdkd rollback", "This stack's name") + `\nRe-run with: ${rerun.command}`;
20438
20586
  }
20587
+ function failedRollbackTail(stackName, region, failedOrphanIds) {
20588
+ const emulatorFailures = customResourcesFailedWithoutApp();
20589
+ const drop = dropFailedHint(stackName, region, failedOrphanIds);
20590
+ if (emulatorFailures.length === 0) return " — re-run the rollback to retry." + drop + rerunRollback(stackName);
20591
+ const forward = deployForwardForEmulatorCustomResources(stackName, emulatorFailures);
20592
+ return "." + forward.prose + drop + forward.line;
20593
+ }
20594
+ function deployForwardForEmulatorCustomResources(stackName, logicalIds) {
20595
+ const deploy = pasteableCommand("cdkd deploy", [{
20596
+ value: stackName,
20597
+ hole: "stack",
20598
+ opts: { plainIdent: true }
20599
+ }]);
20600
+ return {
20601
+ prose: ` Custom resource(s) ${logicalIds.map((id) => plainOrDescribed(id, "logical id")).join(", ")} failed in AWS Emulator's own Lambda runtime, which cdkd rollback uses because it never reads the CDK app, so a re-run fails the same way. Deploy forward instead, from the app's directory with the version you want to keep (Docker running), which runs the handlers locally.` + withheldTargetClause(deploy, "stack", "cdkd deploy", "This stack's name"),
20602
+ line: `\nDeploy forward with: ${deploy.command}`
20603
+ };
20604
+ }
20439
20605
  function backendErrorText(error, stackName, region) {
20440
20606
  if (!isPasteableIdent(stackName) || !isPasteableIdent(region)) return "its error text names a stack or region that is not a plain identifier, so it is not shown";
20441
20607
  return displaySafe(describeAwsFailure(error).detail);
@@ -20446,8 +20612,12 @@ function stackRegionShown(stackName, region) {
20446
20612
  function stackRegionIsPlain(stackName, region) {
20447
20613
  return isPasteableIdent(stackName) && isPasteableIdent(region);
20448
20614
  }
20449
- const NESTED_NAME_DESCRIBED_NOTE = "(The nested stack's name is not a plain identifier, so it is described, not named; list the records as stored with 'cdkd state list --long'.)";
20450
- const STACK_REGION_DESCRIBED_NOTE = " (The stack name or region is not a plain identifier, so it is described, not named; list the records as stored with 'cdkd state list --long'.)";
20615
+ function nestedNameDescribedNote() {
20616
+ return `(The nested stack's name is not a plain identifier, so it is described, not named; list the records as stored with ${proseQuoted(cdkdRemedy("cdkd state list", "--long"))}.)`;
20617
+ }
20618
+ function stackRegionDescribedNote() {
20619
+ return ` (The stack name or region is not a plain identifier, so it is described, not named; list the records as stored with ${proseQuoted(cdkdRemedy("cdkd state list", "--long"))}.)`;
20620
+ }
20451
20621
  function snapshotNote(resourceType, effectiveProvisionedBy, skipFinalSnapshot) {
20452
20622
  if (skipFinalSnapshot) return "DeletionPolicy Snapshot — NO final snapshot (--skip-final-snapshot)";
20453
20623
  if (refusesFinalSnapshot(resourceType, effectiveProvisionedBy)) {
@@ -20601,7 +20771,7 @@ async function printRollbackPlanSegments(ctx) {
20601
20771
  async function previewNestedChildRevert(backend, childStackName, region, runId, skipFinalSnapshot) {
20602
20772
  const plain = isPasteableIdent(childStackName);
20603
20773
  const shown = plain ? `nested stack ${childStackName}` : "a nested stack whose name is not a plain identifier";
20604
- const withPointer = (lines) => plain ? lines : [...lines, ` ${NESTED_NAME_DESCRIBED_NOTE}`];
20774
+ const withPointer = (lines) => plain ? lines : [...lines, ` ${nestedNameDescribedNote()}`];
20605
20775
  if (runId === void 0) return withPointer([` (${shown}: this segment carries no deploy run id — its revert will FAIL and the segment is kept)`]);
20606
20776
  try {
20607
20777
  const [childState, journal] = await Promise.all([backend.getState(childStackName, region), backend.loadRollbackJournal(childStackName, region)]);
@@ -20712,7 +20882,7 @@ async function runRollbackReplay(ctx) {
20712
20882
  ...journal,
20713
20883
  segments: journal.segments.filter((s) => s.reason !== NESTED_PENDING_PARENT_REASON)
20714
20884
  };
20715
- if (!journal || journal.segments.length === 0 && orphanedPending === 0) throw new Error(`Nothing to roll back for ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")}). Run 'cdkd deploy' to (re)deploy, or 'cdkd destroy' to clean up.`);
20885
+ if (!journal || journal.segments.length === 0 && orphanedPending === 0) throw new Error(`Nothing to roll back for ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(region, "region")}). Run ${proseQuoted(cdkdRemedy("cdkd deploy"))} to (re)deploy, or ${proseQuoted(cdkdRemedy("cdkd destroy"))} to clean up.`);
20716
20886
  applyCrossPrefixScan(await crossPrefixScan, {
20717
20887
  stackName,
20718
20888
  region,
@@ -20758,7 +20928,7 @@ async function runRollbackReplay(ctx) {
20758
20928
  const createTokenLedger = ledgerForStack(setup.stateBackend, stackName, region);
20759
20929
  const inSegmentScope = (segment, fn) => withSkipPrefix(segment.skipPrefix ?? legacySkipPrefix(), () => withStackScope(nameScopeOf(stackName, stackInstanceId, stateData?.state), () => withCreateTokenLedger(createTokenLedger, fn)));
20760
20930
  logger.info(`\nRollback plan for ${stackRegionShown(stackName, region)}:`);
20761
- if (!stackRegionIsPlain(stackName, region)) logger.info(STACK_REGION_DESCRIBED_NOTE);
20931
+ if (!stackRegionIsPlain(stackName, region)) logger.info(stackRegionDescribedNote());
20762
20932
  if (orphanedPending > 0) logger.info(safeMsg`\n Discard ${orphanedPending} record(s) of nested deploys whose parent run no longer ` + `has a journal to replay them (nothing else would ever replay them).`);
20763
20933
  const planStateView = { ...stateResources };
20764
20934
  await printRollbackPlanSegments({
@@ -20963,7 +21133,7 @@ async function runRollbackReplay(ctx) {
20963
21133
  }
20964
21134
  if (declinedDivergentRewrite) throw new PartialFailureError(`Rollback stopped: ${declinedDivergentReason}.` + (totalFailures > 0 ? ` ${totalFailures} operation(s) also failed.` : "") + " Journal preserved (this segment, any older ones, and their failed operations) — re-run the rollback once the record's region field matches its key.");
20965
21135
  if (interrupted) throw new PartialFailureError(`Rollback interrupted. Journal preserved — re-run the rollback to finish.` + rerunRollback(stackName));
20966
- if (totalFailures > 0) throw new PartialFailureError(`Rollback completed with ${totalFailures} failed operation(s). Journal preserved — re-run the rollback to retry.` + dropFailedHint(stackName, region, failedOrphanIds) + rerunRollback(stackName));
21136
+ if (totalFailures > 0) throw new PartialFailureError(`Rollback completed with ${totalFailures} failed operation(s). Journal preserved` + failedRollbackTail(stackName, region, failedOrphanIds));
20967
21137
  if (totalWarnings > 0) throw new PartialFailureError(`Rollback completed with ${totalWarnings} skipped/unrecoverable operation(s) (see warnings above).`);
20968
21138
  logger.info(`\nRollback of ${stackRegionShown(stackName, region)} complete.`);
20969
21139
  } finally {
@@ -21006,13 +21176,13 @@ async function rollbackCommand(stackArg, options) {
21006
21176
  return !inRegion.some((p) => p.stackName === parent && p.region === c.region);
21007
21177
  });
21008
21178
  if (scoped.length === 0) {
21009
- logger.info("Nothing to roll back — no stack has a rollback journal. Run 'cdkd deploy' to (re)deploy, or 'cdkd destroy' to clean up.");
21179
+ logger.info("Nothing to roll back — no stack has a rollback journal. " + safeMsg`Run ${proseQuoted(cdkdRemedy("cdkd deploy"))} to (re)deploy, or ${proseQuoted(cdkdRemedy("cdkd destroy"))} to clean up.`);
21010
21180
  return;
21011
21181
  }
21012
21182
  if (scoped.length > 1) {
21013
21183
  const list = scoped.map((c) => ` - ${plainOrDescribed(c.stackName, "stack name")} (${plainOrDescribed(c.region ?? "", "region")})`).join("\n");
21014
- const described = scoped.some((c) => !isPasteableIdent(c.stackName) || !isPasteableIdent(c.region ?? "")) ? "A row whose stack name or region is not a plain identifier is described, not named; list the records as stored with 'cdkd state list --long'.\n" : "";
21015
- throw new Error(`Multiple stacks have a rollback journal. Pick one:\n${list}\n` + described + `Re-run 'cdkd rollback <stack>' (add --stack-region if the same name spans regions).`);
21184
+ const described = scoped.some((c) => !isPasteableIdent(c.stackName) || !isPasteableIdent(c.region ?? "")) ? `A row whose stack name or region is not a plain identifier is described, not named; list the records as stored with ${proseQuoted(cdkdRemedy("cdkd state list", "--long"))}.\n` : "";
21185
+ throw new Error(`Multiple stacks have a rollback journal. Pick one:\n${list}\n` + described + `Re-run ${pasteableCommand("cdkd rollback", [{ hole: "stack" }]).command} (add --stack-region if the same name spans regions).`);
21016
21186
  }
21017
21187
  ref = scoped[0];
21018
21188
  }
@@ -21315,11 +21485,11 @@ function createEventsCommand() {
21315
21485
  return cmd;
21316
21486
  }
21317
21487
  function createEventsPruneCommand() {
21318
- return new Command("prune").description("Delete old per-run deployment-event streams. On a versioned state bucket the earlier versions of the deleted keys are purged too (with --all, every earlier version under the stack's deployments/ prefix), unless a warning says otherwise.").argument("<stack>", "Stack name (physical CloudFormation name)").addOption(new Option("--keep <N>", "Retain only the newest N runs").argParser((v) => {
21488
+ return new Command("prune").description("Delete old per-run deployment-event streams. On a versioned state bucket the earlier versions of the deleted keys are purged too (with --all, every earlier version under the stack's deployments/ prefix), unless a warning says otherwise.").argument("<stack>", "Stack name (physical CloudFormation name)").addOption(new Option("--keep <N>", "Retain only the newest N runs").argParser(cliArgParser((v) => {
21319
21489
  const n = parseInt(v, 10);
21320
21490
  if (!Number.isInteger(n) || n < 0) throw new Error(`Invalid --keep value ${v === "" ? "\"\"" : displayIdent(v)}: expected a non-negative integer.`);
21321
21491
  return n;
21322
- })).option("--older-than <duration>", "Delete runs older than this duration (e.g. 24h, 90m)").option("--all", "Delete every recorded run and the index, and purge every earlier version under the stack's deployments/ prefix on a versioned state bucket", false).action(withErrorHandling((stack, _options, command) => eventsPruneCommand(stack, command.optsWithGlobals())));
21492
+ }))).option("--older-than <duration>", "Delete runs older than this duration (e.g. 24h, 90m)").option("--all", "Delete every recorded run and the index, and purge every earlier version under the stack's deployments/ prefix on a versioned state bucket", false).action(withErrorHandling((stack, _options, command) => eventsPruneCommand(stack, command.optsWithGlobals())));
21323
21493
  }
21324
21494
 
21325
21495
  // src/cli/commands/gc/asset-references.ts
@@ -21688,7 +21858,7 @@ async function gcCommand(options) {
21688
21858
  const lockKeys = await listAllLockKeys(stateBackend);
21689
21859
  if (lockKeys.length > 0) {
21690
21860
  const listing = lockKeys.map((k) => ` - ${describeStateKey(k, LOCK_FILE_SUFFIX, DEFAULT_STATE_PREFIX)} [${displayIdent(k, { maxCodePoints: STATE_KEY_MAX_CODE_POINTS })}]`).join("\n");
21691
- throw new CdkdError(`Refusing to gc while ${lockKeys.length} stack(s) hold an active lock (a deploy in flight may have published assets whose state write has not landed yet):\n${listing}\nWait for the operation(s) to finish — or clear a stale lock with 'cdkd force-unlock <stack>' — then re-run 'cdkd gc'.`, "GC_LOCKED");
21861
+ throw new CdkdError(`Refusing to gc while ${lockKeys.length} stack(s) hold an active lock (a deploy in flight may have published assets whose state write has not landed yet):\n${listing}\nWait for the operation(s) to finish — or clear a stale lock with ${pasteableCommand("cdkd force-unlock", [{ hole: "stack" }]).command} — then re-run ${proseQuoted(cdkdRemedy("cdkd gc"))}.`, "GC_LOCKED");
21692
21862
  }
21693
21863
  const cutoffMs = Date.now() - options.olderThan;
21694
21864
  const responseCandidates = await listResponsePlaceholderCandidates(stateBackend, cutoffMs, logger);
@@ -21782,7 +21952,7 @@ function parseOlderThan(value) {
21782
21952
  return Math.round(num * multiplier);
21783
21953
  }
21784
21954
  function createGcCommand() {
21785
- const cmd = new Command("gc").description("Garbage-collect unreferenced objects / images from ONE region's cdkd-owned asset storage (asset bucket + container-asset ECR repo), plus abandoned custom-resource response placeholders in the state bucket (account-wide). References are collected from every cdkd state file; CDK bootstrap storage is never touched (use cdk gc).").option("--state-bucket <bucket>", "S3 bucket holding cdkd state (default: cdkd-state-{accountId})").addOption(new Option("--older-than <duration>", "Never delete an object / image newer than this age, even when unreferenced (protects in-flight publishes and recent rollback targets). Accepts <n>d / <n>h.").default(DEFAULT_OLDER_THAN_MS, "30d").argParser(parseOlderThan)).option("--dry-run", "Print the reclaim plan (per-item list + totals) without deleting", false).addOption(new Option("--region <region>", "Region whose cdkd asset storage to garbage-collect (defaults to AWS_REGION, then AWS_DEFAULT_REGION, then your AWS profile's region, then us-east-1)")).action(withErrorHandling(async (options) => {
21955
+ const cmd = new Command("gc").description("Garbage-collect unreferenced objects / images from ONE region's cdkd-owned asset storage (asset bucket + container-asset ECR repo), plus abandoned custom-resource response placeholders in the state bucket (account-wide). References are collected from every cdkd state file; CDK bootstrap storage is never touched (use cdk gc).").option("--state-bucket <bucket>", "S3 bucket holding cdkd state (default: cdkd-state-{accountId})").addOption(new Option("--older-than <duration>", "Never delete an object / image newer than this age, even when unreferenced (protects in-flight publishes and recent rollback targets). Accepts <n>d / <n>h.").default(DEFAULT_OLDER_THAN_MS, "30d").argParser(cliArgParser(parseOlderThan))).option("--dry-run", "Print the reclaim plan (per-item list + totals) without deleting", false).addOption(new Option("--region <region>", "Region whose cdkd asset storage to garbage-collect (defaults to AWS_REGION, then AWS_DEFAULT_REGION, then your AWS profile's region, then us-east-1)")).action(withErrorHandling(async (options) => {
21786
21956
  await gcCommand(options);
21787
21957
  }));
21788
21958
  commonOptions.forEach((opt) => cmd.addOption(opt));
@@ -22016,6 +22186,11 @@ function withoutDependencies(record, drop) {
22016
22186
  }
22017
22187
 
22018
22188
  // src/cli/commands/refactor-move.ts
22189
+ const stackArg = (value) => ({
22190
+ value,
22191
+ hole: "stack",
22192
+ opts: { patternMatched: true }
22193
+ });
22019
22194
  const rowKey = (stack, region, logicalId) => JSON.stringify([
22020
22195
  stack,
22021
22196
  region,
@@ -22231,9 +22406,9 @@ async function applyMoveGroup(input) {
22231
22406
  const loaded = /* @__PURE__ */ new Map();
22232
22407
  for (const plan of plans) {
22233
22408
  const stateData = await stateBackend.getState(plan.stackName, plan.region);
22234
- if (!stateData || stateData.etag !== plan.etag) throw new CdkdError(safeMsg`The state of stack ${plan.stackName} (${plan.region}) changed after cdkd ` + "refactor planned it, so nothing was written. Re-run cdkd refactor.", "REFACTOR_STATE_CHANGED");
22409
+ if (!stateData || stateData.etag !== plan.etag) throw new CdkdError(safeMsg`The state of stack ${plan.stackName} (${plan.region}) changed after cdkd ` + `refactor planned it, so nothing was written. Re-run ${cdkdRemedy("cdkd refactor")}.`, "REFACTOR_STATE_CHANGED");
22235
22410
  refuseReadForWrite(stateData.state, plan.stackName, plan.region, recovery);
22236
- if (await stateBackend.loadRollbackJournal(plan.stackName, plan.region) !== null) throw new CdkdError(safeMsg`cdkd refactor refused stack ${plan.stackName} (${plan.region}): an earlier ` + safeMsg`deploy left a rollback journal, so nothing was written. Run 'cdkd rollback ` + safeMsg`${plan.stackName}' or a successful 'cdkd deploy' first.`, "REFACTOR_REFUSED");
22411
+ if (await stateBackend.loadRollbackJournal(plan.stackName, plan.region) !== null) throw new CdkdError(safeMsg`cdkd refactor refused stack ${plan.stackName} (${plan.region}): an earlier ` + safeMsg`deploy left a rollback journal, so nothing was written. Run ${proseQuoted(pasteableCommand("cdkd rollback", [stackArg(plan.stackName)]).command)} ` + safeMsg`or a successful ${proseQuoted(cdkdRemedy("cdkd deploy"))} first.`, "REFACTOR_REFUSED");
22237
22412
  loaded.set(plan, {
22238
22413
  state: stateData.state,
22239
22414
  ...stateData.migrationPending && { migrationPending: true }
@@ -22251,7 +22426,7 @@ async function applyMoveGroup(input) {
22251
22426
  const written = [];
22252
22427
  const fail = (plan, error) => {
22253
22428
  const sources = plans.filter((p) => p.movesOut.length > 0).map((p) => p.stackName);
22254
- return new CdkdError(safeMsg`cdkd refactor could not save stack ${plan.stackName} (${plan.region}): ` + safeMsg`${error.message}.\n` + (written.length > 0 ? safeMsg`Written before the failure: ${written.join(", ")}.\n` : "") + safeMsg`Any move that started is recorded in its source stack (${sources.join(", ")}), ` + "whose 'cdkd deploy' and 'cdkd destroy' refuse until it is finished. Re-run " + safeMsg`'cdkd refactor ${sources.join(" ")}' to finish it.`, "REFACTOR_PARTIAL");
22429
+ return new CdkdError(safeMsg`cdkd refactor could not save stack ${plan.stackName} (${plan.region}): ` + safeMsg`${error.message}.\n` + (written.length > 0 ? safeMsg`Written before the failure: ${written.join(", ")}.\n` : "") + safeMsg`Any move that started is recorded in its source stack (${sources.join(", ")}), ` + "whose 'cdkd deploy' and 'cdkd destroy' refuse until it is finished. Re-run " + safeMsg`${proseQuoted(pasteableCommand("cdkd refactor", sources.map(stackArg)).command)} to finish it.`, "REFACTOR_PARTIAL");
22255
22430
  };
22256
22431
  const save = async (plan, state, expectedEtag) => {
22257
22432
  try {
@@ -22300,7 +22475,7 @@ async function applyMoveGroup(input) {
22300
22475
  if (markerMoves.length > 0) try {
22301
22476
  await updateRefactorMarker(stateBackend, (moves) => moves.filter((m) => !markerMoves.some((n) => sameMove(m, n))));
22302
22477
  } catch (error) {
22303
- throw new CdkdError(safeMsg`Every record of the refactor was written, but the refactor marker could not ` + safeMsg`be cleared: ${error.message}. Until it is, deploy and destroy of ` + "the moved stacks refuse; re-run cdkd refactor to clear it.", "REFACTOR_PARTIAL");
22478
+ throw new CdkdError(safeMsg`Every record of the refactor was written, but the refactor marker could not ` + safeMsg`be cleared: ${error.message}. Until it is, deploy and destroy of ` + `the moved stacks refuse; re-run ${cdkdRemedy("cdkd refactor")} to clear it.`, "REFACTOR_PARTIAL");
22304
22479
  }
22305
22480
  });
22306
22481
  }
@@ -22344,12 +22519,12 @@ async function finishPendingMoves(input) {
22344
22519
  if (dest !== null && Object.hasOwn(dest.state.resources, m.to)) finished.push(finishedOf(m));
22345
22520
  else stuck.push(safeMsg`${stackName}.${m.from} -> ${m.toStack}.${m.to}`);
22346
22521
  }
22347
- if (stuck.length > 0) throw new CdkdError(safeMsg`cdkd refactor cannot finish ${stuck.join(", ")}: ${stackName} (${region}) has ` + "no cdkd state any more and the destination does not record the resource. If the resource is still in AWS, adopt it into the destination with cdkd import; then remove the move from the refactor marker in the state bucket.", "REFACTOR_REFUSED");
22522
+ if (stuck.length > 0) throw new CdkdError(safeMsg`cdkd refactor cannot finish ${stuck.join(", ")}: ${stackName} (${region}) has ` + `no cdkd state any more and the destination does not record the resource. If the resource is still in AWS, adopt it into the destination with ${cdkdRemedy("cdkd import")}; then remove the move from the refactor marker in the state bucket.`, "REFACTOR_REFUSED");
22348
22523
  return { finished };
22349
22524
  }
22350
22525
  const { moves: marked, malformed } = pendingMovesOutOf(first.state);
22351
22526
  const moves = [...marked, ...(input.markerMoves ?? []).filter((m) => !marked.some((n) => n.from === m.from))];
22352
- if (malformed) throw new CdkdError(safeMsg`Stack ${stackName} (${region}) records an unfinished cdkd refactor move this ` + "binary cannot read (its pendingMovesOut field is malformed), so nothing was written. Inspect the record with cdkd state show and repair it by hand.", "REFACTOR_REFUSED");
22527
+ if (malformed) throw new CdkdError(safeMsg`Stack ${stackName} (${region}) records an unfinished cdkd refactor move this ` + `binary cannot read (its pendingMovesOut field is malformed), so nothing was written. Inspect the record with ${cdkdRemedy("cdkd state show")} and repair it by hand.`, "REFACTOR_REFUSED");
22353
22528
  if (moves.length === 0) return { finished: [] };
22354
22529
  const keyOf = (s) => producerRecordKey(s.stackName, s.region);
22355
22530
  const stacks = /* @__PURE__ */ new Map();
@@ -22402,7 +22577,7 @@ async function finishPendingMoves(input) {
22402
22577
  const describe = safeMsg`${stackName}.${m.from} -> ${m.toStack}.${m.to}`;
22403
22578
  if (dest === void 0) refusals.push(safeMsg`${describe}: ${m.toStack} (${m.toRegion}) has no cdkd state`);
22404
22579
  else if (record === void 0) {
22405
- if (held === void 0) refusals.push(safeMsg`${describe}: neither stack records the resource; adopt it into ${m.toStack} with cdkd import`);
22580
+ if (held === void 0) refusals.push(safeMsg`${describe}: neither stack records the resource; adopt it into ${m.toStack} with ${cdkdRemedy("cdkd import")}`);
22406
22581
  else finished.push(finishedOf(m));
22407
22582
  } else if (held === void 0 && !input.declaresInDestination(m.toStack, m.toRegion, m.to, record.resourceType)) refusals.push(safeMsg`${describe}: ${m.toStack}'s template does not declare ${m.to} as a ` + safeMsg`${record.resourceType}, so the record is not moved there. Check the move, ` + "and the CDK app the run synthesized");
22408
22583
  else if (held === void 0) {
@@ -22418,7 +22593,7 @@ async function finishPendingMoves(input) {
22418
22593
  });
22419
22594
  additions.set(destKey, list);
22420
22595
  finished.push(finishedOf(m));
22421
- } else if (held.physicalId !== record.physicalId) refusals.push(safeMsg`${describe}: ${m.toStack} already holds a different resource under ${m.to} ` + "(created by a deploy before the move finished). Delete or orphan that resource in " + safeMsg`${m.toStack}, then re-run cdkd refactor`);
22596
+ } else if (held.physicalId !== record.physicalId) refusals.push(safeMsg`${describe}: ${m.toStack} already holds a different resource under ${m.to} ` + "(created by a deploy before the move finished). Delete or orphan that resource in " + safeMsg`${m.toStack}, then re-run ${cdkdRemedy("cdkd refactor")}`);
22422
22597
  else finished.push(finishedOf(m));
22423
22598
  }
22424
22599
  for (const [destKey, list] of additions) {
@@ -22542,7 +22717,11 @@ async function planStackRefactor(input) {
22542
22717
  refuseMalformedOrphans(state, stackName, region, recovery);
22543
22718
  refuseMalformedOrphanRecords(state, stackName, region, recovery);
22544
22719
  const base = await diff(state);
22545
- if (base.blocking.length > 0) throw new CdkdError(safeMsg`cdkd refactor refused stack ${stackName} (${region}): ` + `'cdkd diff' reports a condition 'cdkd deploy' refuses to start on. Resolve what 'cdkd diff ${stackName}' reports, then re-run cdkd refactor.`, "REFACTOR_REFUSED");
22720
+ if (base.blocking.length > 0) throw new CdkdError(safeMsg`cdkd refactor refused stack ${stackName} (${region}): ` + `'cdkd diff' reports a condition 'cdkd deploy' refuses to start on. Resolve what ${proseQuoted(pasteableCommand("cdkd diff", [{
22721
+ value: stackName,
22722
+ hole: "stack",
22723
+ opts: { patternMatched: true }
22724
+ }]).command)} reports, then re-run ${cdkdRemedy("cdkd refactor")}.`, "REFACTOR_REFUSED");
22546
22725
  const orphanIds = new Set((Array.isArray(state.orphans) ? state.orphans : []).map((o) => o !== null && typeof o === "object" ? o.logicalId : void 0).filter((id) => typeof id === "string"));
22547
22726
  const creates = [];
22548
22727
  const deletes = [];
@@ -22565,7 +22744,7 @@ async function planStackRefactor(input) {
22565
22744
  const skipped = [];
22566
22745
  const candidates = proposal.renames.filter((r) => {
22567
22746
  if (!orphanIds.has(r.from)) return true;
22568
- const reason = `a rollback-orphan record also names ${r.from}; run 'cdkd deploy' first to settle it`;
22747
+ const reason = `a rollback-orphan record also names ${r.from}; run ${proseQuoted(cdkdRemedy("cdkd deploy"))} first to settle it`;
22569
22748
  if (r.source === "override") refusedOverrides.push({
22570
22749
  from: r.from,
22571
22750
  to: r.to,
@@ -22728,7 +22907,7 @@ async function applyStackRefactor(input) {
22728
22907
  if (!await lockManager.acquireLock(plan.stackName, plan.region, owner, "refactor")) throw new Error(await contentionMessage());
22729
22908
  try {
22730
22909
  const stateData = await stateBackend.getState(plan.stackName, plan.region);
22731
- if (!stateData || stateData.etag !== plan.etag) throw new CdkdError(safeMsg`The state of stack ${plan.stackName} (${plan.region}) changed after cdkd ` + `refactor planned it, so nothing was written for this stack. Re-run cdkd refactor.`, "REFACTOR_STATE_CHANGED");
22910
+ if (!stateData || stateData.etag !== plan.etag) throw new CdkdError(safeMsg`The state of stack ${plan.stackName} (${plan.region}) changed after cdkd ` + `refactor planned it, so nothing was written for this stack. Re-run ${cdkdRemedy("cdkd refactor")}.`, "REFACTOR_STATE_CHANGED");
22732
22911
  refuseMalformedState(stateData.state, plan.stackName, plan.region, input.recovery);
22733
22912
  refuseMalformedOrphans(stateData.state, plan.stackName, plan.region, input.recovery);
22734
22913
  refuseMalformedOrphanRecords(stateData.state, plan.stackName, plan.region, input.recovery);
@@ -22746,7 +22925,11 @@ async function applyStackRefactor(input) {
22746
22925
  }
22747
22926
  }
22748
22927
  function rollbackJournalRefusal(stackName, region) {
22749
- return new CdkdError(safeMsg`cdkd refactor refused stack ${stackName} (${region}): an earlier deploy left a ` + safeMsg`rollback journal, so nothing was written for this stack. Run 'cdkd rollback ${stackName}' ` + `or a successful 'cdkd deploy' first.`, "REFACTOR_REFUSED");
22928
+ return new CdkdError(safeMsg`cdkd refactor refused stack ${stackName} (${region}): an earlier deploy left a ` + safeMsg`rollback journal, so nothing was written for this stack. Run ${proseQuoted(pasteableCommand("cdkd rollback", [{
22929
+ value: stackName,
22930
+ hole: "stack",
22931
+ opts: { patternMatched: true }
22932
+ }]).command)} ` + `or a successful ${proseQuoted(cdkdRemedy("cdkd deploy"))} first.`, "REFACTOR_REFUSED");
22750
22933
  }
22751
22934
  function renderRefactorPlan(plan) {
22752
22935
  const lines = [safeMsg`Stack ${plan.stackName} (${plan.region})`];
@@ -23038,7 +23221,7 @@ async function refactorCommand(stacks, options) {
23038
23221
  throw new CdkdError("cdkd refactor found resources it cannot pair on its own; nothing was written. Name each ambiguous pair in a mapping file and re-run with --override-file.", "REFACTOR_AMBIGUOUS");
23039
23222
  }
23040
23223
  const refused = [...plans.flatMap((p) => p.refusedOverrides), ...movePlan.refused];
23041
- if (refused.length > 0) throw new CdkdError(`cdkd refactor refused ${refused.length} pair(s) the mapping file names; nothing was written. Fix or remove each refused pair in the mapping file (the reasons are above), then re-run cdkd refactor.`, "REFACTOR_REFUSED");
23224
+ if (refused.length > 0) throw new CdkdError(`cdkd refactor refused ${refused.length} pair(s) the mapping file names; nothing was written. Fix or remove each refused pair in the mapping file (the reasons are above), then re-run ${cdkdRemedy("cdkd refactor")}.`, "REFACTOR_REFUSED");
23042
23225
  const toApply = plans.filter((p) => p.renames.length > 0 || p.movesOut.length > 0 || p.movesIn.length > 0);
23043
23226
  if (toApply.length === 0) {
23044
23227
  logger.info("\nNothing to refactor.");
@@ -23069,7 +23252,7 @@ async function refactorCommand(stacks, options) {
23069
23252
  })
23070
23253
  }), holdNotice);
23071
23254
  logger.info(safeMsg`Refactored ${count} resource(s) across ${toApply.length} stack(s): ` + safeMsg`${toApply.map((p) => `${p.stackName} (${p.region})`).join(", ")}.`);
23072
- logger.info("\nAWS resources were not touched. Run 'cdkd diff' to confirm the refactored resources show no change, and deploy the destination stacks before the stacks that import from them.");
23255
+ logger.info(safeMsg`\nAWS resources were not touched. Run ${proseQuoted(cdkdRemedy("cdkd diff"))} to confirm the refactored resources ` + "show no change, and deploy the destination stacks before the stacks that import from them.");
23073
23256
  return;
23074
23257
  }
23075
23258
  const done = [];
@@ -23094,7 +23277,7 @@ async function refactorCommand(stacks, options) {
23094
23277
  done.push(`${plan.stackName} (${plan.region})`);
23095
23278
  logger.info(safeMsg`Refactored ${plan.renames.length} resource(s) in stack ${plan.stackName} (${plan.region}).`);
23096
23279
  }
23097
- logger.info("\nAWS resources were not touched. Run 'cdkd diff' to confirm the renamed resources show no change.");
23280
+ logger.info(safeMsg`\nAWS resources were not touched. Run ${proseQuoted(cdkdRemedy("cdkd diff"))} to confirm the renamed resources show no change.`);
23098
23281
  } finally {
23099
23282
  awsClients.destroy();
23100
23283
  }
@@ -23184,7 +23367,7 @@ async function publishAssetsCommand(stacks, options) {
23184
23367
  try {
23185
23368
  bucket = await resolveStateBucketWithDefault(options.stateBucket, baseRegion, legacyStateBucketFallbackRegion(effectiveRegion));
23186
23369
  } catch {
23187
- logger.info("No cdkd state bucket found — publishing to the asset-manifest destinations (CDK bootstrap storage) verbatim. Run 'cdkd bootstrap' to opt into cdkd-owned asset storage that 'cdk gc' never touches.");
23370
+ logger.info("No cdkd state bucket found — publishing to the asset-manifest destinations " + safeMsg`(CDK bootstrap storage) verbatim. Run ${proseQuoted(cdkdRemedy("cdkd bootstrap"))} to opt into cdkd-owned ` + "asset storage that 'cdk gc' never touches.");
23188
23371
  markerAccess = null;
23189
23372
  return null;
23190
23373
  }
@@ -23321,7 +23504,7 @@ async function publishAssetsCommand(stacks, options) {
23321
23504
  logger.info(`\n${green("✓")} ${bold("Asset publishing complete")} (${totalAssets} asset(s))`);
23322
23505
  }
23323
23506
  function createPublishAssetsCommand() {
23324
- const cmd = new Command("publish-assets").description("Synthesize the CDK app and publish assets to S3/ECR for the selected stack(s) without deploying").argument("[stacks...]", "Stack name(s) to publish assets for. Accepts physical CloudFormation names (e.g. 'MyStage-Api') or CDK display paths (e.g. 'MyStage/Api'). Supports wildcards.").option("--all", "Publish assets for all stacks", false).addOption(new Option("--asset-publish-concurrency <number>", "Maximum concurrent asset publish operations").default(8).argParser((value) => parseInt(value, 10))).addOption(new Option("--image-build-concurrency <number>", "Maximum concurrent Docker image builds").default(4).argParser((value) => parseInt(value, 10))).addOption(useCdkBootstrapAssetsOption).action(withErrorHandling(publishAssetsCommand));
23507
+ const cmd = new Command("publish-assets").description("Synthesize the CDK app and publish assets to S3/ECR for the selected stack(s) without deploying").argument("[stacks...]", "Stack name(s) to publish assets for. Accepts physical CloudFormation names (e.g. 'MyStage-Api') or CDK display paths (e.g. 'MyStage/Api'). Supports wildcards.").option("--all", "Publish assets for all stacks", false).addOption(new Option("--asset-publish-concurrency <number>", "Maximum concurrent asset publish operations").default(8).argParser(parsePositiveIntegerOption)).addOption(new Option("--image-build-concurrency <number>", "Maximum concurrent Docker image builds").default(4).argParser(parsePositiveIntegerOption)).addOption(useCdkBootstrapAssetsOption).action(withErrorHandling(publishAssetsCommand));
23325
23508
  [
23326
23509
  ...commonOptions,
23327
23510
  ...appOptions,
@@ -24140,7 +24323,7 @@ async function resolveImportedProperties(stackState, template, region, stateBack
24140
24323
  attributes: resource.attributes
24141
24324
  });
24142
24325
  } catch (err) {
24143
- logger.warn(`Failed to resolve intrinsics in Properties for imported resource ${logicalIdShown(logicalId)} (${resourceTypeShown(resource.resourceType)}): ${maskSecretsInText(describeAwsFailure(err).detail, recordedSecretValues)}.\nState will be written with the raw intrinsic shape, which may cause 'cdkd destroy' to fail on this resource — re-import once every referenced sibling is in state, or remove this resource from state with 'cdkd orphan <StackPath>/<Path/To/Resource>'.` + (unboundParameterNames.length > 0 ? ` This template also declares parameter(s) with no 'Default' that an import cannot bind (${unboundParameterNames.map((name) => plainOrDescribed(name, "parameter name")).join(", ")}), and 'cdkd import' accepts no parameter values — if this property was built from one of those, re-importing a sibling will not change it: give the parameter a 'Default' in the template and re-import, or correct the recorded properties before the next 'cdkd deploy'.` : ""));
24326
+ logger.warn(`Failed to resolve intrinsics in Properties for imported resource ${logicalIdShown(logicalId)} (${resourceTypeShown(resource.resourceType)}): ${maskSecretsInText(describeAwsFailure(err).detail, recordedSecretValues)}.\nState will be written with the raw intrinsic shape, which may cause 'cdkd destroy' to fail on this resource — re-import once every referenced sibling is in state, or remove this resource from state with ${pasteableCommand("cdkd orphan", [{ hole: "StackPath/Path/To/Resource" }]).command}.` + (unboundParameterNames.length > 0 ? ` This template also declares parameter(s) with no 'Default' that an import cannot bind (${unboundParameterNames.map((name) => plainOrDescribed(name, "parameter name")).join(", ")}), and 'cdkd import' accepts no parameter values — if this property was built from one of those, re-importing a sibling will not change it: give the parameter a 'Default' in the template and re-import, or correct the recorded properties before the next ${proseQuoted(cdkdRemedy("cdkd deploy"))}.` : ""));
24144
24327
  threw = true;
24145
24328
  }
24146
24329
  if (recordedSecretValues.size > 0 && resource.attributes !== void 0) resource.attributes = redactForState(resource.attributes, {
@@ -24170,7 +24353,7 @@ async function resolveImportedProperties(stackState, template, region, stateBack
24170
24353
  const unreadable = refusedHere.filter((id) => parameterTaint.unclassifiable.has(id));
24171
24354
  if (refusedHere.length > 0) {
24172
24355
  const named = [...parameterTaint.parametersHit].sort().map((name) => displayIdent(name));
24173
- logger.warn(`${refusedHere.length} resource(s) in ${displayStackName(stackState.stackName)} depend, directly or through another resource's attributes, on template parameter(s) whose deployed CloudFormation value could not be proven equal to the template 'Default' 'cdkd import' binds` + (named.length > 0 ? ` (${named.join(", ")})` : "") + (unreadable.length > 0 ? ` — ${unreadable.length} of them because their properties could not be checked for such a dependence` : "") + ". Their recorded properties hold the 'Default', NOT the deployed value, and no observed drift baseline was captured for them by this import (the live value may be a secret this import cannot position a redaction for). Review 'cdkd diff' before the next 'cdkd deploy'.");
24356
+ logger.warn(`${refusedHere.length} resource(s) in ${displayStackName(stackState.stackName)} depend, directly or through another resource's attributes, on template parameter(s) whose deployed CloudFormation value could not be proven equal to the template 'Default' 'cdkd import' binds` + (named.length > 0 ? ` (${named.join(", ")})` : "") + (unreadable.length > 0 ? ` — ${unreadable.length} of them because their properties could not be checked for such a dependence` : "") + `. Their recorded properties hold the 'Default', NOT the deployed value, and no observed drift baseline was captured for them by this import (the live value may be a secret this import cannot position a redaction for). Review ${proseQuoted(cdkdRemedy("cdkd diff"))} before the next ${proseQuoted(cdkdRemedy("cdkd deploy"))}.`);
24174
24357
  }
24175
24358
  }
24176
24359
  positionImportedNoEcho(stackState, noEchoInputs, template, conditions, unsafeObservedBaselineLogicalIds, logger);
@@ -24184,7 +24367,7 @@ async function claimRegistryMarkerAfterImport(backend, stackName, region, logger
24184
24367
  switch (answer.kind) {
24185
24368
  case "clear": return;
24186
24369
  case "found":
24187
- logger.warn(safeMsg`The state bucket also records ${displayStackName(stackName)} (${regionShown}) under another state prefix ` + safeMsg`(${answer.prefixes.map((p) => displayIdent(p)).join(", ")}). One stack name per ` + "account and region is supported: drop one of the records with 'cdkd state orphan' before deploying or destroying either.");
24370
+ logger.warn(safeMsg`The state bucket also records ${displayStackName(stackName)} (${regionShown}) under another state prefix ` + safeMsg`(${answer.prefixes.map((p) => displayIdent(p)).join(", ")}). One stack name per ` + safeMsg`account and region is supported: drop one of the records with ${proseQuoted(cdkdRemedy("cdkd state orphan"))} ` + `before deploying or destroying either.`);
24188
24371
  return;
24189
24372
  case "in-progress":
24190
24373
  logger.warn(safeMsg`A deploy of ${displayStackName(stackName)} (${regionShown}) holds a lock under another state prefix ` + safeMsg`(${displayIdent(answer.prefix)}). One stack name per account and region is ` + `supported: keep one of the two before deploying or destroying either.`);
@@ -24642,7 +24825,7 @@ async function runLockedImport(ctx) {
24642
24825
  await stateBackend.saveState(stackInfo.stackName, targetRegion, stackState, saveOptions);
24643
24826
  logger.info(`✓ State written: ${stackInfo.stackName} (${targetRegion})`);
24644
24827
  await claimRegistryMarkerAfterImport(stateBackend, stackInfo.stackName, targetRegion, logger);
24645
- logger.info(` ${importedRows.length} resource(s) imported. Run 'cdkd diff' to see how the imported state lines up with the template.`);
24828
+ logger.info(safeMsg` ${importedRows.length} resource(s) imported. ` + safeMsg`See how the imported state lines up with the template with: ${cdkdRemedy("cdkd diff")}`);
24646
24829
  if (migrationCfnStackName && migrationTree && accountIdForNestedSynth) await importNestedStackChildrenRecursive({
24647
24830
  lockRecovery,
24648
24831
  parentStackName: stackInfo.stackName,
@@ -24774,7 +24957,7 @@ async function importCommand(stackArg, options) {
24774
24957
  const overrides = parseResourceOverrides(options.resource, options.resourceMapping, options.resourceMappingInline);
24775
24958
  if (overrides.size > 0) logger.debug(`User-supplied physical IDs: ${[...overrides.keys()].join(", ")}`);
24776
24959
  const migrationCfnStackName = options.migrateFromCloudformation ? typeof options.migrateFromCloudformation === "string" && options.migrateFromCloudformation.length > 0 ? options.migrateFromCloudformation : stackInfo.stackName : void 0;
24777
- if (options.migrateFromCloudformation && options.dryRun) throw new Error("--migrate-from-cloudformation is not compatible with --dry-run: the post-state-write retirement (UpdateStack + DeleteStack) issues real AWS calls. Use plain `cdkd import --dry-run` to preview the import in isolation.");
24960
+ if (options.migrateFromCloudformation && options.dryRun) throw new Error(`--migrate-from-cloudformation is not compatible with --dry-run: the post-state-write retirement (UpdateStack + DeleteStack) issues real AWS calls. Use plain ${proseQuoted(cdkdRemedy("cdkd import", "--dry-run"), "`")} to preview the import in isolation.`);
24778
24961
  const template = stackInfo.template;
24779
24962
  const templateParser = new TemplateParser();
24780
24963
  const resources = collectImportableResources(template);
@@ -26529,6 +26712,80 @@ function warnIamRoutes(routesWithAuth) {
26529
26712
  return true;
26530
26713
  }
26531
26714
 
26715
+ // src/cli/commands/local-invoke/execution-role.ts
26716
+ function suggestAssumeRoleFromState(state, logicalId) {
26717
+ const logger = getLogger();
26718
+ const roleArn = resolveExecutionRoleArnFromState(state, logicalId);
26719
+ if (roleArn) logger.info(`Hint: the deployed function uses execution role ${displayIdent(roleArn, { maxCodePoints: 613 })}. Re-run with --assume-role to invoke under the deployed function's narrow permissions.`);
26720
+ }
26721
+ function maybeSuggestAssumeRole(options, state, logicalId) {
26722
+ if (options.assumeRole !== void 0) return false;
26723
+ if (!options.fromState || !state) return false;
26724
+ if (stateRoleRecordIsEmulatorSide()) return false;
26725
+ suggestAssumeRoleFromState(state, logicalId);
26726
+ return true;
26727
+ }
26728
+ function resolveExecutionRoleArnFromState(state, logicalId, roleProperty = "Role") {
26729
+ const found = classifyExecutionRoleArnFromState(state, logicalId, roleProperty);
26730
+ if (found.kind === "ok") return found.arn;
26731
+ if (found.kind === "malformed") getLogger().warn(`${found.description}. Ignoring it.`);
26732
+ }
26733
+ function mixedModeEmulatorRoleWarning(pin) {
26734
+ return `--assume-role: in AWS Emulator mixed mode the execution role is assumed in real AWS, but the state record's IAM roles are the emulator's, so cdkd does not read the role from it. Mark IAM as a "real-aws" exception under Parameters (AWS_ENDPOINT_URL_IAM), or pass the ARN explicitly: ${pin}. Falling back to the developer's shell credentials.`;
26735
+ }
26736
+ function resolveBareAssumeRoleFromState(state, logicalId) {
26737
+ const logger = getLogger();
26738
+ if (stateRoleRecordIsEmulatorSide()) {
26739
+ logger.warn(mixedModeEmulatorRoleWarning("--assume-role '<arn>'"));
26740
+ return;
26741
+ }
26742
+ const arn = resolveExecutionRoleArnFromState(state, logicalId);
26743
+ if (arn) {
26744
+ logger.info(safeMsg`--assume-role: auto-resolved execution role from cdkd state: ${shellBoundedDisplay(displayIdent(arn, { maxCodePoints: 613 }))}`);
26745
+ return arn;
26746
+ }
26747
+ logger.warn(safeMsg`--assume-role: could not resolve the execution role ARN from cdkd state for ${quotedOrDescribed(logicalId, "logical id")}. ` + "Pass the ARN explicitly: --assume-role '<arn>'. Falling back to the developer's shell credentials.");
26748
+ }
26749
+ function classifyExecutionRoleArnFromState(state, logicalId, roleProperty = "Role") {
26750
+ const lambda = state.resources[logicalId];
26751
+ if (!lambda) return { kind: "miss" };
26752
+ const roleRef = lambda.properties?.[roleProperty] ?? lambda.observedProperties?.[roleProperty];
26753
+ if (typeof roleRef === "string") {
26754
+ if (isIamRoleArn(roleRef)) return {
26755
+ kind: "ok",
26756
+ arn: roleRef
26757
+ };
26758
+ if (roleRef.startsWith("arn:")) return {
26759
+ kind: "malformed",
26760
+ description: `Deployed state for ${quotedOrDescribed(logicalId, "logical id")} carries a ${displayIdent(roleProperty)} that is not a well-formed IAM role ARN: ${shellBoundedDisplay(displayIdent(roleRef, { maxCodePoints: 613 }))}`
26761
+ };
26762
+ return { kind: "miss" };
26763
+ }
26764
+ if (typeof roleRef === "object" && roleRef !== null) {
26765
+ const refLogicalId = pickReferencedLogicalId(roleRef);
26766
+ if (refLogicalId) {
26767
+ const cached = state.resources[refLogicalId]?.attributes?.["Arn"];
26768
+ if (typeof cached === "string" && isIamRoleArn(cached)) return {
26769
+ kind: "ok",
26770
+ arn: cached
26771
+ };
26772
+ if (typeof cached === "string" && cached.startsWith("arn:")) return {
26773
+ kind: "malformed",
26774
+ description: `The cached Arn attribute of ${quotedOrDescribed(refLogicalId, "logical id")} is not a well-formed IAM role ARN: ${shellBoundedDisplay(displayIdent(cached, { maxCodePoints: 613 }))}`
26775
+ };
26776
+ }
26777
+ }
26778
+ return { kind: "miss" };
26779
+ }
26780
+ function pickReferencedLogicalId(intrinsic) {
26781
+ if ("Ref" in intrinsic && typeof intrinsic["Ref"] === "string") return intrinsic["Ref"];
26782
+ if ("Fn::GetAtt" in intrinsic) {
26783
+ const arg = intrinsic["Fn::GetAtt"];
26784
+ if (Array.isArray(arg) && typeof arg[0] === "string") return arg[0];
26785
+ if (typeof arg === "string") return arg.split(".")[0];
26786
+ }
26787
+ }
26788
+
26532
26789
  // src/cli/commands/local-start-api/assume-role.ts
26533
26790
  function resolveStartApiAssumeRoleArn(args) {
26534
26791
  const { logicalId, assumeRole, lambdaResource, stateBundle } = args;
@@ -26539,6 +26796,10 @@ function resolveStartApiAssumeRoleArn(args) {
26539
26796
  const roleProp = (lambdaResource.Properties ?? {})["Role"];
26540
26797
  if (typeof roleProp === "string" && isIamRoleArn(roleProp)) return roleProp;
26541
26798
  if (typeof roleProp === "string" && roleProp.startsWith("arn:")) throw malformedAutoRoleError(logicalId, `the template Role for ${quotedOrDescribed(logicalId, "logical id")} is not a well-formed IAM role ARN: ` + shellBoundedDisplay(displayIdent(roleProp, { maxCodePoints: 613 })));
26799
+ if (stateBundle && stateRoleRecordIsEmulatorSide()) {
26800
+ getLogger().warn(mixedModeEmulatorRoleWarning(assumeRolePin(logicalId)));
26801
+ return;
26802
+ }
26542
26803
  if (stateBundle) {
26543
26804
  const fromState = classifyExecutionRoleArnFromState(stateBundle.state, logicalId);
26544
26805
  if (fromState.kind === "malformed") throw malformedAutoRoleError(logicalId, fromState.description);
@@ -27211,6 +27472,7 @@ async function emulate(args) {
27211
27472
  failedRoles.add(args.roleArn);
27212
27473
  logger.warn(safeMsg`${args.flag}: AssumeRole(${shownRole}) was refused, and cdkd cannot emulate the role's permissions instead: ${reason}.`);
27213
27474
  };
27475
+ if (args.emulateRoleVia === void 0 && !args.realAws && mixedModeEmulatorOverride() !== void 0) return cannot("in AWS Emulator a sts:GetFederationToken session is allowed nothing (the emulator's own user has no IAM policies). Let the role's trust policy allow the emulator's identity, for example the account root (arn:aws:iam::000000000000:root), and redeploy, or pass --emulate-role-via <arn> naming an emulator role you can assume");
27214
27476
  const { STSClient, GetCallerIdentityCommand, GetFederationTokenCommand } = await import("@aws-sdk/client-sts");
27215
27477
  const sts = new STSClient({
27216
27478
  ...awsClientDefaults({
@@ -27392,11 +27654,11 @@ async function assumeLambdaExecutionRole$1(roleArn, region, emulateRoleVia) {
27392
27654
  DurationSeconds: 3600
27393
27655
  }))).Credentials;
27394
27656
  if (!creds?.AccessKeyId || !creds.SecretAccessKey || !creds.SessionToken) throw new CdkdError(`AssumeRole(${displayIdent(roleArn, { maxCodePoints: 613 })}) returned no usable credentials.`, "LOCAL_START_API_ASSUMEROLE_NO_CREDS");
27395
- return {
27657
+ return keepEmulatorIssuedCredentials({
27396
27658
  accessKeyId: creds.AccessKeyId,
27397
27659
  secretAccessKey: creds.SecretAccessKey,
27398
27660
  sessionToken: creds.SessionToken
27399
- };
27661
+ });
27400
27662
  } catch (err) {
27401
27663
  if (err instanceof CdkdError) throw err;
27402
27664
  const emulated = await emulateRoleAfterDeniedAssume(err, {
@@ -27407,7 +27669,7 @@ async function assumeLambdaExecutionRole$1(roleArn, region, emulateRoleVia) {
27407
27669
  flag: "--assume-role",
27408
27670
  sessionNamePrefix: "cdkd-local-start-api"
27409
27671
  });
27410
- if (emulated) return emulated;
27672
+ if (emulated) return keepEmulatorIssuedCredentials(emulated);
27411
27673
  const rendered = describeLocalAwsFailureForWarn(err, "STS AssumeRole");
27412
27674
  throw new CdkdError(`--assume-role: STS AssumeRole(${displayIdent(roleArn, { maxCodePoints: 613 })}) failed: ${rendered}.`, "LOCAL_START_API_ASSUMEROLE_FAILED", redactedAwsCause(err, "STS AssumeRole failed"));
27413
27675
  } finally {
@@ -28091,7 +28353,7 @@ function resolveEcsTaskTarget(target, stacks, context) {
28091
28353
  logicalId = parsed.pathOrId;
28092
28354
  }
28093
28355
  if (!logicalId || !resource) throw notFoundError(target, stack, resources);
28094
- if (resource.Type === "AWS::Lambda::Function") throw new EcsTaskResolutionError(`Resource '${logicalId}' in ${stack.stackName} is a Lambda function, not an ECS task definition. Use \`cdkd local invoke\` for Lambda; \`cdkd local run-task\` is ECS only.`);
28356
+ if (resource.Type === "AWS::Lambda::Function") throw new EcsTaskResolutionError(`Resource '${logicalId}' in ${stack.stackName} is a Lambda function, not an ECS task definition. Use ${proseQuoted(cdkdRemedy("cdkd local invoke"), "`")} for Lambda; \`cdkd local run-task\` is ECS only.`);
28095
28357
  if (resource.Type !== "AWS::ECS::TaskDefinition") throw new EcsTaskResolutionError(`Resource '${logicalId}' in ${stack.stackName} is ${resource.Type}, not an AWS::ECS::TaskDefinition.`);
28096
28358
  return extractTaskDefinitionProperties(stack, logicalId, resource, context);
28097
28359
  }
@@ -28668,7 +28930,7 @@ async function localStartApiCommand(target, options) {
28668
28930
  let apiFilter = target;
28669
28931
  if (options.api !== void 0) {
28670
28932
  if (target !== void 0) throw new Error(`Cannot specify both positional target ('${target}') and --api flag ('${options.api}'). Use one or the other. The positional form is preferred — '--api' is a deprecated alias.`);
28671
- logger.warn("[deprecated] --api '<id>' will be removed in a future major release. Use the positional argument instead: 'cdkd local start-api <id>'.");
28933
+ logger.warn(safeMsg`[deprecated] --api '<id>' will be removed in a future major release. Use the positional argument instead: ${proseQuoted(pasteableCommand("cdkd local start-api", [{ hole: "id" }]).command)}.`);
28672
28934
  apiFilter = options.api;
28673
28935
  }
28674
28936
  warnIfDeprecatedRegion(options);
@@ -28952,7 +29214,7 @@ async function localStartApiCommand(target, options) {
28952
29214
 
28953
29215
  // src/cli/commands/local-start-api.ts
28954
29216
  function createLocalStartApiCommand() {
28955
- const startApi = new Command("start-api").description("Run a long-running local HTTP server that maps API Gateway routes (REST v1, HTTP API, Function URL) to Lambda invocations against the AWS Lambda Runtime Interface Emulator (Docker required). Supports Lambda TOKEN/REQUEST authorizers, Cognito User Pool / HTTP v2 JWT authorizers, and AWS_IAM auth (REST v1 `AuthorizationType: AWS_IAM` and Function URL `AuthType: AWS_IAM` — SigV4 signature verification only; IAM policy evaluation is NOT emulated; see https://cdkd.dev/local-start-api/#aws-iam-authorization). When JWKS is unreachable, JWT authorizers fall back to pass-through (every token accepted) with a warn line — local dev fallback. VPC-config Lambdas run locally and surface a warn line at startup; their containers do NOT get attached to the deployed VPC subnets, so calls to private RDS / ElastiCache will fail.").argument("[target]", "Optional API filter. Accepts the bare CDK logical id ('MyHttpApi'; single-stack apps only), stack-qualified logical id ('MyStack:MyHttpApi'), full CDK Construct path ('MyStack/MyHttpApi/Resource'), or an ancestor Construct path that prefix-matches ('MyStack/MyHttpApi'). When omitted, every discovered API gets its own server. Mirrors `cdkd local invoke` / `cdkd local run-task` target syntax.").addOption(new Option("--port <port>", "HTTP server port (default: auto-allocate)").default("0")).addOption(new Option("--host <host>", "Bind address").default("127.0.0.1")).addOption(new Option("--stack <name>", "Stack to start (single-stack apps auto-detect)")).addOption(new Option("--warm", "Pre-start one container per Lambda at server boot").default(false)).addOption(new Option("--per-lambda-concurrency <n>", "Pool size cap per Lambda (default 2, max 4)").default("2")).addOption(new Option("--no-pull", "Skip docker pull (cached image)")).addOption(new Option("--container-host <host>", "IP the host uses to bind/probe the RIE port (must be a numeric IP — `docker run -p <ip>:<port>:8080` rejects hostnames). Defaults to 127.0.0.1.").default("127.0.0.1")).addOption(new Option("--debug-port-base <port>", "Reserve a contiguous --debug-port range (one per Lambda)")).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}, \"Parameters\": {...}})")).addOption(new Option("--assume-role <arn-or-pair>", "Assume the Lambda's execution role and forward STS-issued temp creds. Two forms: (1) `--assume-role <arn>` sets a single global default ARN used for every routed Lambda; (2) `--assume-role <LogicalId>=<arn>` (repeatable) is a per-Lambda override (wins over the global default and over --assume-role-auto for the named Lambda). Pair with --assume-role-auto to auto-resolve every other Lambda. Precedence: per-Lambda > (--assume-role-auto OR global default) > unset (developer creds passed through).").argParser((raw, prev) => parseAssumeRoleToken(raw, prev))).addOption(new Option("--assume-role-auto", "Auto-resolve EACH routed Lambda's own execution role per-Lambda (literal ARN / Fn::GetAtt against template / --from-cfn-stack state). Slower boot — one STS call per Lambda — but the right shape when each Lambda's deployed role differs. Mutually exclusive with `--assume-role <arn>` (global default); errors at boot. Compatible with `--assume-role <LogicalId>=<arn>` per-Lambda overrides — the map wins for named Lambdas, auto-resolve handles the rest.").default(false)).addOption(emulateRoleViaOption("--assume-role")).addOption(new Option("--watch", "Hot-reload: watch the CDK app source tree and re-synth + re-discover routes on a source edit (cdk.out / node_modules / .git excluded; honors cdk.json watch.include / watch.exclude). Off by default; the server keeps the previous version serving when synth fails mid-reload.").default(false)).addOption(new Option("--stage <name>", "Select an API Gateway Stage by its 'StageName'. Default: the first Stage attached to each API. Drives BOTH event.stageVariables and requestContext.stage, for REST v1 and HTTP API v2 alike: when a route's API has a matching templated Stage, the selected StageName is threaded into requestContext.stage. An HTTP API v2 route reports '$default' only when its API carries no AWS::ApiGatewayV2::Stage in the template — that is v2's auto-deployed stage, not a limit on what this flag can select (AWS's CreateStage accepts named stages on v2 too). An API with no Stage matching the selected name is warned about at start-up and its routes get stageVariables: null.")).addOption(new Option("--api <id>", "DEPRECATED — use the positional <target> argument instead. Same accepted forms (bare logical id, stack-qualified, Construct path, ancestor prefix). Will be removed in a future major release.")).addOption(new Option("--layer-role-arn <arn>", "Role to sts:AssumeRole before calling lambda:GetLayerVersion on every literal-ARN entry in Properties.Layers. Use only when the dev credentials cannot read the layer — typically cross-account layers. AWS-published public layers (e.g. Lambda Powertools) are readable from every account and need no role.")).addOption(new Option("--from-state", "Read cdkd S3 state for every routed stack and substitute Ref / Fn::GetAtt / Fn::Sub / Fn::Join (and AWS pseudo parameters) in Lambda env vars with the deployed physical IDs / attributes. Off by default — pre-PR warn-and-drop semantics are preserved. Turn on for stacks already deployed via cdkd deploy. Mirrors `cdkd local invoke --from-state` / `cdkd local run-task --from-state`. Re-runs against fresh state on every hot-reload firing (--watch).").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in Lambda env vars with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name per routed stack; pass an explicit value when a single CFn stack should serve every routed stack. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).addOption(new Option("--mtls-truststore <path>", "PEM-encoded CA bundle for client-certificate verification (mutual TLS). When set, the local server switches from HTTP to HTTPS and the TLS handshake rejects clients whose certificate doesn't chain to one of these CAs. Verified certs are surfaced on the Lambda event under requestContext.identity.clientCert (REST v1) / requestContext.authentication.clientCert (HTTP API v2). Must be set together with --mtls-cert + --mtls-key; partial flag sets are rejected. Generate a CA + server + client cert for local dev: openssl req -x509 -newkey rsa:2048 -nodes -keyout ca-key.pem -out ca.pem -subj \"/CN=cdkd-local-ca\" -days 365; openssl req -newkey rsa:2048 -nodes -keyout server-key.pem -out server-csr.pem -subj \"/CN=localhost\"; openssl x509 -req -in server-csr.pem -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -days 365; openssl req -newkey rsa:2048 -nodes -keyout client-key.pem -out client-csr.pem -subj \"/CN=client\"; openssl x509 -req -in client-csr.pem -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out client-cert.pem -days 365; curl --cacert ca.pem --cert client-cert.pem --key client-key.pem https://localhost:<port>/...")).addOption(new Option("--mtls-cert <path>", "PEM-encoded server certificate for mutual TLS. Self-signed is fine for local dev. Must be set together with --mtls-truststore + --mtls-key.")).addOption(new Option("--mtls-key <path>", "PEM-encoded server private key matching --mtls-cert. Must be set together with --mtls-truststore + --mtls-cert.")).addOption(new Option("--strict-sigv4", "Opt-in: enforce strict AWS_IAM SigV4 verification. When set, requests whose signature cannot be cryptographically verified (foreign access-key-id, OR no local AWS credentials configured) are denied. DEFAULT off — warn-and-pass with a placeholder principalId, matching cdk-local's `cdkl start-api`. Enable this when you want local parity with the deployed API Gateway's signature enforcement.").default(false)).action(withErrorHandling(localStartApiCommand));
29217
+ const startApi = new Command("start-api").description("Run a long-running local HTTP server that maps API Gateway routes (REST v1, HTTP API, Function URL) to Lambda invocations against the AWS Lambda Runtime Interface Emulator (Docker required). Supports Lambda TOKEN/REQUEST authorizers, Cognito User Pool / HTTP v2 JWT authorizers, and AWS_IAM auth (REST v1 `AuthorizationType: AWS_IAM` and Function URL `AuthType: AWS_IAM` — SigV4 signature verification only; IAM policy evaluation is NOT emulated; see https://cdkd.dev/local-start-api/#aws-iam-authorization). When JWKS is unreachable, JWT authorizers fall back to pass-through (every token accepted) with a warn line — local dev fallback. VPC-config Lambdas run locally and surface a warn line at startup; their containers do NOT get attached to the deployed VPC subnets, so calls to private RDS / ElastiCache will fail.").argument("[target]", "Optional API filter. Accepts the bare CDK logical id ('MyHttpApi'; single-stack apps only), stack-qualified logical id ('MyStack:MyHttpApi'), full CDK Construct path ('MyStack/MyHttpApi/Resource'), or an ancestor Construct path that prefix-matches ('MyStack/MyHttpApi'). When omitted, every discovered API gets its own server. Mirrors `cdkd local invoke` / `cdkd local run-task` target syntax.").addOption(new Option("--port <port>", "HTTP server port (default: auto-allocate)").default("0")).addOption(new Option("--host <host>", "Bind address").default("127.0.0.1")).addOption(new Option("--stack <name>", "Stack to start (single-stack apps auto-detect)")).addOption(new Option("--warm", "Pre-start one container per Lambda at server boot").default(false)).addOption(new Option("--per-lambda-concurrency <n>", "Pool size cap per Lambda (default 2, max 4)").default("2")).addOption(new Option("--no-pull", "Skip docker pull (cached image)")).addOption(new Option("--container-host <host>", "IP the host uses to bind/probe the RIE port (must be a numeric IP — `docker run -p <ip>:<port>:8080` rejects hostnames). Defaults to 127.0.0.1.").default("127.0.0.1")).addOption(new Option("--debug-port-base <port>", "Reserve a contiguous --debug-port range (one per Lambda)")).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}, \"Parameters\": {...}})")).addOption(new Option("--assume-role <arn-or-pair>", "Assume the Lambda's execution role and forward STS-issued temp creds. Two forms: (1) `--assume-role <arn>` sets a single global default ARN used for every routed Lambda; (2) `--assume-role <LogicalId>=<arn>` (repeatable) is a per-Lambda override (wins over the global default and over --assume-role-auto for the named Lambda). Pair with --assume-role-auto to auto-resolve every other Lambda. Precedence: per-Lambda > (--assume-role-auto OR global default) > unset (developer creds passed through).").argParser(cliArgParser((raw, prev) => parseAssumeRoleToken(raw, prev)))).addOption(new Option("--assume-role-auto", "Auto-resolve EACH routed Lambda's own execution role per-Lambda (literal ARN / Fn::GetAtt against template / --from-cfn-stack state). Slower boot — one STS call per Lambda — but the right shape when each Lambda's deployed role differs. Mutually exclusive with `--assume-role <arn>` (global default); errors at boot. Compatible with `--assume-role <LogicalId>=<arn>` per-Lambda overrides — the map wins for named Lambdas, auto-resolve handles the rest.").default(false)).addOption(emulateRoleViaOption("--assume-role")).addOption(new Option("--watch", "Hot-reload: watch the CDK app source tree and re-synth + re-discover routes on a source edit (cdk.out / node_modules / .git excluded; honors cdk.json watch.include / watch.exclude). Off by default; the server keeps the previous version serving when synth fails mid-reload.").default(false)).addOption(new Option("--stage <name>", "Select an API Gateway Stage by its 'StageName'. Default: the first Stage attached to each API. Drives BOTH event.stageVariables and requestContext.stage, for REST v1 and HTTP API v2 alike: when a route's API has a matching templated Stage, the selected StageName is threaded into requestContext.stage. An HTTP API v2 route reports '$default' only when its API carries no AWS::ApiGatewayV2::Stage in the template — that is v2's auto-deployed stage, not a limit on what this flag can select (AWS's CreateStage accepts named stages on v2 too). An API with no Stage matching the selected name is warned about at start-up and its routes get stageVariables: null.")).addOption(new Option("--api <id>", "DEPRECATED — use the positional <target> argument instead. Same accepted forms (bare logical id, stack-qualified, Construct path, ancestor prefix). Will be removed in a future major release.")).addOption(new Option("--layer-role-arn <arn>", "Role to sts:AssumeRole before calling lambda:GetLayerVersion on every literal-ARN entry in Properties.Layers. Use only when the dev credentials cannot read the layer — typically cross-account layers. AWS-published public layers (e.g. Lambda Powertools) are readable from every account and need no role.")).addOption(new Option("--from-state", "Read cdkd S3 state for every routed stack and substitute Ref / Fn::GetAtt / Fn::Sub / Fn::Join (and AWS pseudo parameters) in Lambda env vars with the deployed physical IDs / attributes. Off by default — pre-PR warn-and-drop semantics are preserved. Turn on for stacks already deployed via cdkd deploy. Mirrors `cdkd local invoke --from-state` / `cdkd local run-task --from-state`. Re-runs against fresh state on every hot-reload firing (--watch).").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in Lambda env vars with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name per routed stack; pass an explicit value when a single CFn stack should serve every routed stack. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).addOption(new Option("--mtls-truststore <path>", "PEM-encoded CA bundle for client-certificate verification (mutual TLS). When set, the local server switches from HTTP to HTTPS and the TLS handshake rejects clients whose certificate doesn't chain to one of these CAs. Verified certs are surfaced on the Lambda event under requestContext.identity.clientCert (REST v1) / requestContext.authentication.clientCert (HTTP API v2). Must be set together with --mtls-cert + --mtls-key; partial flag sets are rejected. Generate a CA + server + client cert for local dev: openssl req -x509 -newkey rsa:2048 -nodes -keyout ca-key.pem -out ca.pem -subj \"/CN=cdkd-local-ca\" -days 365; openssl req -newkey rsa:2048 -nodes -keyout server-key.pem -out server-csr.pem -subj \"/CN=localhost\"; openssl x509 -req -in server-csr.pem -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -days 365; openssl req -newkey rsa:2048 -nodes -keyout client-key.pem -out client-csr.pem -subj \"/CN=client\"; openssl x509 -req -in client-csr.pem -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out client-cert.pem -days 365; curl --cacert ca.pem --cert client-cert.pem --key client-key.pem https://localhost:<port>/...")).addOption(new Option("--mtls-cert <path>", "PEM-encoded server certificate for mutual TLS. Self-signed is fine for local dev. Must be set together with --mtls-truststore + --mtls-key.")).addOption(new Option("--mtls-key <path>", "PEM-encoded server private key matching --mtls-cert. Must be set together with --mtls-truststore + --mtls-cert.")).addOption(new Option("--strict-sigv4", "Opt-in: enforce strict AWS_IAM SigV4 verification. When set, requests whose signature cannot be cryptographically verified (foreign access-key-id, OR no local AWS credentials configured) are denied. DEFAULT off — warn-and-pass with a placeholder principalId, matching cdk-local's `cdkl start-api`. Enable this when you want local parity with the deployed API Gateway's signature enforcement.").default(false)).action(withErrorHandling(localStartApiCommand));
28956
29218
  [
28957
29219
  ...commonOptions,
28958
29220
  ...appOptions,
@@ -29652,6 +29914,11 @@ function buildDockerRunArgs(opts) {
29652
29914
  ...wiring,
29653
29915
  env: {}
29654
29916
  });
29917
+ for (const h of awsEmulatorSqsHostBlocks(finalEnv, wiring)) {
29918
+ const mapping = `${h.host}:${h.ip}`;
29919
+ args.push("--add-host", mapping);
29920
+ ownerAddHosts.push(mapping);
29921
+ }
29655
29922
  }
29656
29923
  const sensitiveKeys = /* @__PURE__ */ new Set([
29657
29924
  ...SENSITIVE_ENV_KEYS,
@@ -30331,7 +30598,7 @@ async function buildEcsImageResolutionContext$1(candidate, stateProvider, option
30331
30598
  };
30332
30599
  }
30333
30600
  function taskRoleRecordIsEmulatorSide() {
30334
- return getActiveWorkloadAwsWiring$1()?.mixed !== void 0 && !realAwsException("IAM");
30601
+ return stateRoleRecordIsEmulatorSide();
30335
30602
  }
30336
30603
  function pickCandidateStack(parsed, target, stacks) {
30337
30604
  const byPrefix = stackForPathFormTarget(parsed, target, stacks);
@@ -30868,7 +31135,7 @@ async function runAgentCoreWatchLoop(args) {
30868
31135
  currentAbort?.abort();
30869
31136
  return;
30870
31137
  }
30871
- logger.error(`Reload failed: ${describeAwsFailure(err).detail}. The previous container may already be torn down; exiting --watch loop. Re-run cdkd local invoke-agentcore --watch to recover.`);
31138
+ logger.error(`Reload failed: ${describeAwsFailure(err).detail}. The previous container may already be torn down; exiting --watch loop. Re-run ${cdkdRemedy("cdkd local invoke-agentcore", "--watch")} to recover.`);
30872
31139
  reloadFailed = true;
30873
31140
  currentAbort?.abort();
30874
31141
  }
@@ -31239,6 +31506,10 @@ function resolveAssumeRoleArnUncached(options, resolved, loaded) {
31239
31506
  if (options.assumeRole === true) {
31240
31507
  if (resolved.roleArn !== void 0 && isIamRoleArn(resolved.roleArn)) return resolved.roleArn;
31241
31508
  if (resolved.roleArn?.startsWith("arn:")) getLogger().warn(safeMsg`--assume-role: the template RoleArn for ${quotedOrDescribed(resolved.logicalId, "logical id")} is not a well-formed IAM role ARN: ` + safeMsg`${shellBoundedDisplay(displayIdent(resolved.roleArn, { maxCodePoints: 613 }))}. Ignoring it.`);
31509
+ if (loaded && stateRoleRecordIsEmulatorSide()) {
31510
+ getLogger().warn(mixedModeEmulatorRoleWarning("--assume-role '<arn>'"));
31511
+ return;
31512
+ }
31242
31513
  if (loaded) {
31243
31514
  const fromState = resolveExecutionRoleArnFromState(loaded, resolved.logicalId, "RoleArn");
31244
31515
  if (fromState) {
@@ -31290,16 +31561,16 @@ async function assumeAgentCoreExecutionRole(roleArn, region, emulateRoleVia) {
31290
31561
  flag: "--assume-role",
31291
31562
  sessionNamePrefix: `${getEmbedConfig().resourceNamePrefix}-invoke-agentcore`
31292
31563
  });
31293
- if (emulated) return emulated;
31564
+ if (emulated) return keepEmulatorIssuedCredentials(emulated);
31294
31565
  throw err;
31295
31566
  }
31296
31567
  const creds = response.Credentials;
31297
31568
  if (!creds?.AccessKeyId || !creds.SecretAccessKey || !creds.SessionToken) throw new CdkdError(`AssumeRole(${displayIdent(roleArn, { maxCodePoints: 613 })}) returned no usable credentials.`, "LOCAL_INVOKE_AGENTCORE_ASSUMEROLE_NO_CREDS");
31298
- return {
31569
+ return keepEmulatorIssuedCredentials({
31299
31570
  accessKeyId: creds.AccessKeyId,
31300
31571
  secretAccessKey: creds.SecretAccessKey,
31301
31572
  sessionToken: creds.SessionToken
31302
- };
31573
+ });
31303
31574
  } finally {
31304
31575
  sts.destroy();
31305
31576
  }
@@ -31815,7 +32086,10 @@ async function localInvokeAgentCoreCommand(target, options) {
31815
32086
  roleFlag: "--assume-role",
31816
32087
  roleRequested: options.assumeRole === true || typeof options.assumeRole === "string"
31817
32088
  });
31818
- await activateLocalAwsAndRoleArn(options);
32089
+ await activateLocalAwsAndRoleArn({
32090
+ ...options,
32091
+ singleWorkload: true
32092
+ });
31819
32093
  await ensureDockerAvailable();
31820
32094
  const profileCredentials = await profileCredentialsForWorkload(options.profile, resolveProfileCredentials);
31821
32095
  if (options.profile && profileCredentials) profileCredsFile = await writeProfileCredentialsFile(options.profile, profileCredentials);
@@ -31848,6 +32122,10 @@ async function localInvokeAgentCoreCommand(target, options) {
31848
32122
  };
31849
32123
  const resolved = resolveAgentCoreTarget(resolvedTarget, stacks, imageContext);
31850
32124
  logger.info(`Target: ${resolved.stack.stackName}/${resolved.logicalId} (${resolved.protocol})`);
32125
+ logMixedModeForWorkload({
32126
+ logicalId: resolved.logicalId,
32127
+ cdkPath: readCdkPathOrUndefined(resolved.resource)
32128
+ }, `AgentCore runtime ${resolved.stack.stackName}/${resolved.logicalId}`);
31851
32129
  const isMcp = resolved.protocol === AGENTCORE_MCP_PROTOCOL;
31852
32130
  const isA2a = resolved.protocol === AGENTCORE_A2A_PROTOCOL;
31853
32131
  if (resolved.protocol === AGENTCORE_AGUI_PROTOCOL) logger.info("AGUI runtime: routing through the HTTP /invocations + /ws path (AG-UI wire is SSE / WebSocket on port 8080).");
@@ -32056,7 +32334,7 @@ function parseTimeoutMs(raw) {
32056
32334
  return parsed;
32057
32335
  }
32058
32336
  function createLocalInvokeAgentCoreCommand() {
32059
- const cmd = new Command("invoke-agentcore").description("Run a Bedrock AgentCore Runtime container locally and invoke it once over its protocol contract: HTTP (POST /invocations + GET /ping on 8080) or MCP (POST /mcp Streamable HTTP on 8000). Resolves the AWS::BedrockAgentCore::Runtime, pulls/builds its container, injects env vars + AWS credentials, and prints the response. For an MCP runtime, runs the session handshake then sends one JSON-RPC request (tools/list by default, or the method/params from --event). Target accepts a CDK display path (MyStack/MyAgent) or stack-qualified logical ID (MyStack:MyAgentRuntime1234). Single-stack apps may omit the stack prefix. Omit <target> in an interactive terminal to pick from a list. Supports the container artifact and the CodeConfiguration managed-runtime artifact (fromCodeAsset, built from source) on the HTTP + MCP protocols; the agent calls real AWS for managed services.").argument("[target]", "CDK display path or stack-qualified logical ID of the AgentCore Runtime to invoke (omit to pick interactively in a TTY)").addOption(new Option("-e, --event <file>", "JSON event payload file (default: {})")).addOption(new Option("--event-stdin", "Read event JSON from stdin").default(false)).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}})")).addOption(new Option("--session-id <id>", "AgentCore runtime session id header value (default: a random UUID)")).addOption(new Option("--ws", "Stream over the HTTP-protocol agent's bidirectional /ws WebSocket endpoint (on 8080) instead of POST /invocations: send --event as the first frame and print every received frame to stdout until the agent closes. When stdin is a TTY, auto-enters a REPL — each typed line is sent as a follow-up text frame until Ctrl-D / agent close; pipe from /dev/null to force one-shot in a TTY. Ignored for an MCP runtime.").default(false)).addOption(new Option("--watch", "Re-synth and reload the agent container on CDK source changes. Supported on the HTTP / AGUI protocols, both the --ws session AND the default one-shot POST /invocations (the reload re-runs the single shot). An interpreted-language source edit inside a CodeConfiguration source tree takes a soft-reload fast path (docker cp + docker restart, no rebuild); Dockerfile / compiled-source / asset-hash-changed / ambiguous edits force a full rebuild. For MCP / A2A runtimes --watch is a no-op WARN and the single shot proceeds.").default(false)).addOption(new Option("--bearer-token <jwt>", "Bearer JWT to present when the runtime declares a customJwtAuthorizer. Verified against the runtime OIDC discovery URL (signature / issuer / expiry / audience) before the container starts, then forwarded to /invocations as Authorization: Bearer <jwt>.")).addOption(new Option("--no-verify-auth", "Skip inbound JWT verification even when the runtime declares a customJwtAuthorizer (local-dev escape hatch). A --bearer-token, if given, is still forwarded.")).addOption(new Option("--sigv4", "Sign the /invocations POST with AWS SigV4 (service bedrock-agentcore) using the resolved credentials, matching the cloud default when the runtime declares no customJwtAuthorizer. Opt-in: default unsigned. Mutually exclusive with --bearer-token; ignored on a JWT-protected runtime.").default(false)).addOption(new Option("--platform <platform>", "docker --platform for the agent container (linux/amd64 or linux/arm64)").choices(["linux/amd64", "linux/arm64"]).default("linux/arm64")).addOption(new Option("--no-pull", "Skip docker pull (use cached image) — no-op for the local-build path")).addOption(new Option("--no-build", "Skip docker build on the local-asset path (use the previously-built tag). No-op for the ECR / registry pull paths.")).addOption(new Option("--container-host <host>", "Host to bind the agent port to").default("127.0.0.1")).addOption(new Option("--timeout <ms>", "Per-request timeout in milliseconds. Applied to POST /invocations, POST /mcp, and the /ws open-to-close window. Raise this for long-running agent calls that exceed the default.").default(12e4).argParser(parseTimeoutMs)).addOption(new Option("--assume-role [arn]", "Assume the runtime's execution role and forward STS-issued temp credentials to the container so the agent runs with the deployed role. Three forms: (1) `--assume-role <arn>` assumes the explicit ARN; (2) `--assume-role` (bare) uses the runtime's RoleArn when it is a literal ARN; (3) `--no-assume-role` opts out. Off by default — the developer's shell credentials are forwarded unchanged.")).addOption(new Option("--no-assume-role", "Explicitly opt out of assuming the runtime's execution role: forward your ambient AWS credentials (or the --profile overlay) unchanged even when --from-state / --from-cfn-stack is set.")).addOption(emulateRoleViaOption("--assume-role")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--from-state", "Load cdkd's S3 state for the target stack and substitute Ref / Fn::GetAtt / Fn::Sub / Fn::ImportValue in env vars with the deployed physical IDs / cross-stack exports. Mutually exclusive with --from-cfn-stack.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in env vars with the deployed physical IDs / exports. For CDK apps deployed via the upstream CDK CLI. Bare form uses the resolved stack name; pass an explicit value when the CFn stack name differs. Mutually exclusive with --from-state.")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-cfn-stack as the CFn client region.").argParser(parseStackRegion)).action(withErrorHandling(async (target, options) => {
32337
+ const cmd = new Command("invoke-agentcore").description("Run a Bedrock AgentCore Runtime container locally and invoke it once over its protocol contract: HTTP (POST /invocations + GET /ping on 8080) or MCP (POST /mcp Streamable HTTP on 8000). Resolves the AWS::BedrockAgentCore::Runtime, pulls/builds its container, injects env vars + AWS credentials, and prints the response. For an MCP runtime, runs the session handshake then sends one JSON-RPC request (tools/list by default, or the method/params from --event). Target accepts a CDK display path (MyStack/MyAgent) or stack-qualified logical ID (MyStack:MyAgentRuntime1234). Single-stack apps may omit the stack prefix. Omit <target> in an interactive terminal to pick from a list. Supports the container artifact and the CodeConfiguration managed-runtime artifact (fromCodeAsset, built from source) on the HTTP + MCP protocols; the agent calls real AWS for managed services.").argument("[target]", "CDK display path or stack-qualified logical ID of the AgentCore Runtime to invoke (omit to pick interactively in a TTY)").addOption(new Option("-e, --event <file>", "JSON event payload file (default: {})")).addOption(new Option("--event-stdin", "Read event JSON from stdin").default(false)).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}})")).addOption(new Option("--session-id <id>", "AgentCore runtime session id header value (default: a random UUID)")).addOption(new Option("--ws", "Stream over the HTTP-protocol agent's bidirectional /ws WebSocket endpoint (on 8080) instead of POST /invocations: send --event as the first frame and print every received frame to stdout until the agent closes. When stdin is a TTY, auto-enters a REPL — each typed line is sent as a follow-up text frame until Ctrl-D / agent close; pipe from /dev/null to force one-shot in a TTY. Ignored for an MCP runtime.").default(false)).addOption(new Option("--watch", "Re-synth and reload the agent container on CDK source changes. Supported on the HTTP / AGUI protocols, both the --ws session AND the default one-shot POST /invocations (the reload re-runs the single shot). An interpreted-language source edit inside a CodeConfiguration source tree takes a soft-reload fast path (docker cp + docker restart, no rebuild); Dockerfile / compiled-source / asset-hash-changed / ambiguous edits force a full rebuild. For MCP / A2A runtimes --watch is a no-op WARN and the single shot proceeds.").default(false)).addOption(new Option("--bearer-token <jwt>", "Bearer JWT to present when the runtime declares a customJwtAuthorizer. Verified against the runtime OIDC discovery URL (signature / issuer / expiry / audience) before the container starts, then forwarded to /invocations as Authorization: Bearer <jwt>.")).addOption(new Option("--no-verify-auth", "Skip inbound JWT verification even when the runtime declares a customJwtAuthorizer (local-dev escape hatch). A --bearer-token, if given, is still forwarded.")).addOption(new Option("--sigv4", "Sign the /invocations POST with AWS SigV4 (service bedrock-agentcore) using the resolved credentials, matching the cloud default when the runtime declares no customJwtAuthorizer. Opt-in: default unsigned. Mutually exclusive with --bearer-token; ignored on a JWT-protected runtime.").default(false)).addOption(new Option("--platform <platform>", "docker --platform for the agent container (linux/amd64 or linux/arm64)").choices(["linux/amd64", "linux/arm64"]).default("linux/arm64")).addOption(new Option("--no-pull", "Skip docker pull (use cached image) — no-op for the local-build path")).addOption(new Option("--no-build", "Skip docker build on the local-asset path (use the previously-built tag). No-op for the ECR / registry pull paths.")).addOption(new Option("--container-host <host>", "Host to bind the agent port to").default("127.0.0.1")).addOption(new Option("--timeout <ms>", "Per-request timeout in milliseconds. Applied to POST /invocations, POST /mcp, and the /ws open-to-close window. Raise this for long-running agent calls that exceed the default.").default(12e4).argParser(cliArgParser(parseTimeoutMs))).addOption(new Option("--assume-role [arn]", "Assume the runtime's execution role and forward STS-issued temp credentials to the container so the agent runs with the deployed role. Three forms: (1) `--assume-role <arn>` assumes the explicit ARN; (2) `--assume-role` (bare) uses the runtime's RoleArn when it is a literal ARN; (3) `--no-assume-role` opts out. Off by default — the developer's shell credentials are forwarded unchanged.")).addOption(new Option("--no-assume-role", "Explicitly opt out of assuming the runtime's execution role: forward your ambient AWS credentials (or the --profile overlay) unchanged even when --from-state / --from-cfn-stack is set.")).addOption(emulateRoleViaOption("--assume-role")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--from-state", "Load cdkd's S3 state for the target stack and substitute Ref / Fn::GetAtt / Fn::Sub / Fn::ImportValue in env vars with the deployed physical IDs / cross-stack exports. Mutually exclusive with --from-cfn-stack.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in env vars with the deployed physical IDs / exports. For CDK apps deployed via the upstream CDK CLI. Bare form uses the resolved stack name; pass an explicit value when the CFn stack name differs. Mutually exclusive with --from-state.")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-cfn-stack as the CFn client region.").argParser(parseStackRegion)).action(withErrorHandling(async (target, options) => {
32060
32338
  await localInvokeAgentCoreCommand(target, options);
32061
32339
  }));
32062
32340
  [
@@ -32152,7 +32430,7 @@ async function applyLambdaCredentialEnv(dockerEnv, args) {
32152
32430
  setContainerRegion(dockerEnv, containerRegion);
32153
32431
  assumeSucceeded = true;
32154
32432
  } catch (err) {
32155
- logger.warn(`--assume-role: STS AssumeRole(${displayIdent(args.assumeRoleArn, { maxCodePoints: 613 })}) failed: ${describeLocalAwsFailureForWarn(err, "STS AssumeRole")}. Falling back to the developer's shell credentials.`);
32433
+ logger.warn(`--assume-role: STS AssumeRole(${displayIdent(args.assumeRoleArn, { maxCodePoints: 613 })}) failed: ${describeLocalAwsFailureForWarn(err, "STS AssumeRole")}. ` + (localAwsEmulatorActive() ? "The function runs with the emulator's own keys." : "Falling back to the developer's shell credentials."));
32156
32434
  }
32157
32435
  if (!assumeSucceeded) {
32158
32436
  forwardAwsEnv(dockerEnv);
@@ -32191,16 +32469,16 @@ async function assumeLambdaExecutionRole(roleArn, region, emulateRoleVia) {
32191
32469
  flag: "--assume-role",
32192
32470
  sessionNamePrefix: "cdkd-local-invoke"
32193
32471
  });
32194
- if (emulated) return emulated;
32472
+ if (emulated) return keepEmulatorIssuedCredentials(emulated);
32195
32473
  throw err;
32196
32474
  }
32197
32475
  const creds = response.Credentials;
32198
32476
  if (!creds?.AccessKeyId || !creds.SecretAccessKey || !creds.SessionToken) throw new CdkdError(`AssumeRole(${displayIdent(roleArn, { maxCodePoints: 613 })}) returned no usable credentials.`, "LOCAL_INVOKE_ASSUMEROLE_NO_CREDS");
32199
- return {
32477
+ return keepEmulatorIssuedCredentials({
32200
32478
  accessKeyId: creds.AccessKeyId,
32201
32479
  secretAccessKey: creds.SecretAccessKey,
32202
32480
  sessionToken: creds.SessionToken
32203
- };
32481
+ });
32204
32482
  } finally {
32205
32483
  sts.destroy();
32206
32484
  }
@@ -32249,72 +32527,6 @@ async function readStdin() {
32249
32527
  return Buffer.concat(chunks).toString("utf-8");
32250
32528
  }
32251
32529
 
32252
- // src/cli/commands/local-invoke/execution-role.ts
32253
- function suggestAssumeRoleFromState(state, logicalId) {
32254
- const logger = getLogger();
32255
- const roleArn = resolveExecutionRoleArnFromState(state, logicalId);
32256
- if (roleArn) logger.info(`Hint: the deployed function uses execution role ${displayIdent(roleArn, { maxCodePoints: 613 })}. Re-run with --assume-role to invoke under the deployed function's narrow permissions.`);
32257
- }
32258
- function maybeSuggestAssumeRole(options, state, logicalId) {
32259
- if (options.assumeRole !== void 0) return false;
32260
- if (!options.fromState || !state) return false;
32261
- suggestAssumeRoleFromState(state, logicalId);
32262
- return true;
32263
- }
32264
- function resolveExecutionRoleArnFromState(state, logicalId, roleProperty = "Role") {
32265
- const found = classifyExecutionRoleArnFromState(state, logicalId, roleProperty);
32266
- if (found.kind === "ok") return found.arn;
32267
- if (found.kind === "malformed") getLogger().warn(`${found.description}. Ignoring it.`);
32268
- }
32269
- function resolveBareAssumeRoleFromState(state, logicalId) {
32270
- const logger = getLogger();
32271
- const arn = resolveExecutionRoleArnFromState(state, logicalId);
32272
- if (arn) {
32273
- logger.info(safeMsg`--assume-role: auto-resolved execution role from cdkd state: ${shellBoundedDisplay(displayIdent(arn, { maxCodePoints: 613 }))}`);
32274
- return arn;
32275
- }
32276
- logger.warn(safeMsg`--assume-role: could not resolve the execution role ARN from cdkd state for ${quotedOrDescribed(logicalId, "logical id")}. ` + "Pass the ARN explicitly: --assume-role '<arn>'. Falling back to the developer's shell credentials.");
32277
- }
32278
- function classifyExecutionRoleArnFromState(state, logicalId, roleProperty = "Role") {
32279
- const lambda = state.resources[logicalId];
32280
- if (!lambda) return { kind: "miss" };
32281
- const roleRef = lambda.properties?.[roleProperty] ?? lambda.observedProperties?.[roleProperty];
32282
- if (typeof roleRef === "string") {
32283
- if (isIamRoleArn(roleRef)) return {
32284
- kind: "ok",
32285
- arn: roleRef
32286
- };
32287
- if (roleRef.startsWith("arn:")) return {
32288
- kind: "malformed",
32289
- description: `Deployed state for ${quotedOrDescribed(logicalId, "logical id")} carries a ${displayIdent(roleProperty)} that is not a well-formed IAM role ARN: ${shellBoundedDisplay(displayIdent(roleRef, { maxCodePoints: 613 }))}`
32290
- };
32291
- return { kind: "miss" };
32292
- }
32293
- if (typeof roleRef === "object" && roleRef !== null) {
32294
- const refLogicalId = pickReferencedLogicalId(roleRef);
32295
- if (refLogicalId) {
32296
- const cached = state.resources[refLogicalId]?.attributes?.["Arn"];
32297
- if (typeof cached === "string" && isIamRoleArn(cached)) return {
32298
- kind: "ok",
32299
- arn: cached
32300
- };
32301
- if (typeof cached === "string" && cached.startsWith("arn:")) return {
32302
- kind: "malformed",
32303
- description: `The cached Arn attribute of ${quotedOrDescribed(refLogicalId, "logical id")} is not a well-formed IAM role ARN: ${shellBoundedDisplay(displayIdent(cached, { maxCodePoints: 613 }))}`
32304
- };
32305
- }
32306
- }
32307
- return { kind: "miss" };
32308
- }
32309
- function pickReferencedLogicalId(intrinsic) {
32310
- if ("Ref" in intrinsic && typeof intrinsic["Ref"] === "string") return intrinsic["Ref"];
32311
- if ("Fn::GetAtt" in intrinsic) {
32312
- const arg = intrinsic["Fn::GetAtt"];
32313
- if (Array.isArray(arg) && typeof arg[0] === "string") return arg[0];
32314
- if (typeof arg === "string") return arg.split(".")[0];
32315
- }
32316
- }
32317
-
32318
32530
  // src/cli/commands/local-invoke/template-env.ts
32319
32531
  function envHasIntrinsicValue(templateEnv) {
32320
32532
  if (!templateEnv) return false;
@@ -32476,7 +32688,10 @@ async function localInvokeCommand(target, options) {
32476
32688
  roleFlag: "--assume-role",
32477
32689
  roleRequested: options.assumeRole === true || typeof options.assumeRole === "string"
32478
32690
  });
32479
- await activateLocalAwsAndRoleArn(options);
32691
+ await activateLocalAwsAndRoleArn({
32692
+ ...options,
32693
+ singleWorkload: true
32694
+ });
32480
32695
  await ensureDockerAvailable();
32481
32696
  const profileCredentials = await profileCredentialsForWorkload(options.profile, resolveProfileCredentials);
32482
32697
  if (options.profile && profileCredentials) profileCredsFile = await writeProfileCredentialsFile(options.profile, profileCredentials);
@@ -32500,6 +32715,10 @@ async function localInvokeCommand(target, options) {
32500
32715
  refuseFailedLookups([lambda.stack], stacks, failedLookups);
32501
32716
  const targetLabel = lambda.kind === "zip" ? lambda.runtime : "container image";
32502
32717
  logger.info(`Target: ${lambda.stack.stackName}/${lambda.logicalId} (${targetLabel})`);
32718
+ logMixedModeForWorkload({
32719
+ logicalId: lambda.logicalId,
32720
+ cdkPath: readCdkPathOrUndefined(lambda.resource)
32721
+ }, `Lambda ${lambda.stack.stackName}/${lambda.logicalId}`);
32503
32722
  imagePlan = await resolveImagePlan(lambda, options);
32504
32723
  const { env: templateEnvResolved, sensitiveEnvKeys, stateForRoleHint, stateRegion } = await resolveInvokeTemplateEnv(lambda, options);
32505
32724
  let resolvedAssumeRoleArn;
@@ -32849,4 +33068,4 @@ function collectVerbFlags(program) {
32849
33068
  }
32850
33069
 
32851
33070
  export { resolveSecretDerivedPrincipals as a, buildProgram, isResolvableSecretPrincipalList as i, runDestroyForStack as n, canonicalizeIpProtocolValue as o, holdsUnprovenSecretPrincipalToken as r, canonicalizeIpv4Cidr as t };
32852
- //# sourceMappingURL=program-C7rUgzkB.js.map
33071
+ //# sourceMappingURL=program-DJWAG98-.js.map