@cdkd/cli 0.350.1 → 0.350.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/{ambient-client-defaults-7acjxfyN.js → ambient-client-defaults-CqrM5nDS.js} +12 -167
  2. package/dist/ambient-client-defaults-CqrM5nDS.js.map +1 -0
  3. package/dist/{asg-provider-Dvy_jqxt.js → asg-provider-hZ4nyheM.js} +9 -8
  4. package/dist/asg-provider-hZ4nyheM.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-CRy-dCjZ.js → custom-resource-runtime-CcClWTa-.js} +96 -15
  8. package/dist/custom-resource-runtime-CcClWTa-.js.map +1 -0
  9. package/dist/{db-instance-modify-retry-pFWx2ED5.js → db-instance-modify-retry-CsIlFgIJ.js} +4 -4
  10. package/dist/{db-instance-modify-retry-pFWx2ED5.js.map → db-instance-modify-retry-CsIlFgIJ.js.map} +1 -1
  11. package/dist/{delete-started-Co5Gt1jH.js → delete-started-C0g7PYI-.js} +24 -2
  12. package/dist/delete-started-C0g7PYI-.js.map +1 -0
  13. package/dist/{deploy-engine-BwlO3Jv_.js → deploy-engine-Sw2eta-t.js} +1240 -551
  14. package/dist/deploy-engine-Sw2eta-t.js.map +1 -0
  15. package/dist/{diff-calculator-CbibK_C3.js → diff-calculator-BvN5rnLe.js} +21 -29
  16. package/dist/diff-calculator-BvN5rnLe.js.map +1 -0
  17. package/dist/{ec2-termination-protection-BM1Zt3Fn.js → ec2-termination-protection-BIIHrzUa.js} +26 -8
  18. package/dist/ec2-termination-protection-BIIHrzUa.js.map +1 -0
  19. package/dist/{ecr-uri-C3_6QVgR.js → ecr-uri-CQ_BCOjX.js} +2 -2
  20. package/dist/{ecr-uri-C3_6QVgR.js.map → ecr-uri-CQ_BCOjX.js.map} +1 -1
  21. package/dist/{expected-bucket-owner-CGoY_YS8.js → expected-bucket-owner-DR9qK772.js} +2 -2
  22. package/dist/{expected-bucket-owner-CGoY_YS8.js.map → expected-bucket-owner-DR9qK772.js.map} +1 -1
  23. package/dist/{iam-role-provider-BaN9MMWs.js → iam-role-provider-i52A7e_4.js} +7 -6
  24. package/dist/iam-role-provider-i52A7e_4.js.map +1 -0
  25. package/dist/{image-plan-C9qclqRY.js → image-plan-DOnhBOIa.js} +102 -29
  26. package/dist/image-plan-DOnhBOIa.js.map +1 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +5 -5
  29. package/dist/{logger-DmQRya0S.js → logger-Ce9kvuBB.js} +4 -124
  30. package/dist/{logger-DmQRya0S.js.map → logger-Ce9kvuBB.js.map} +1 -1
  31. package/dist/{neptune-provider-BYgFNrtZ.js → neptune-provider-Bir1AdqM.js} +8 -7
  32. package/dist/neptune-provider-Bir1AdqM.js.map +1 -0
  33. package/dist/{program-CDu5N31o.js → program-DAAu8qUr.js} +751 -303
  34. package/dist/program-DAAu8qUr.js.map +1 -0
  35. package/dist/{provider-classes-Diwm8MK7.js → provider-classes-CM8Txuvb.js} +250 -129
  36. package/dist/provider-classes-CM8Txuvb.js.map +1 -0
  37. package/dist/{rds-provider-DKZjtd50.js → rds-provider-DmVAU_Mv.js} +23 -34
  38. package/dist/rds-provider-DmVAU_Mv.js.map +1 -0
  39. package/dist/{read-replica-C5e4xpYi.js → read-replica-Bmq3NTlC.js} +3 -3
  40. package/dist/{read-replica-C5e4xpYi.js.map → read-replica-Bmq3NTlC.js.map} +1 -1
  41. package/dist/{replacement-rules-01_01yDU.js → replacement-rules-lOM1aGPr.js} +3 -2
  42. package/dist/replacement-rules-lOM1aGPr.js.map +1 -0
  43. package/dist/{resource-deadline-TfDpwRQ_.js → resource-deadline-1VcUPyH4.js} +19 -19
  44. package/dist/{resource-deadline-TfDpwRQ_.js.map → resource-deadline-1VcUPyH4.js.map} +1 -1
  45. package/dist/run-cli-BlVizMfM.js +34 -0
  46. package/dist/run-cli-BlVizMfM.js.map +1 -0
  47. package/dist/{update-removal-D-FspP88.js → update-removal-BOue-bJm.js} +30 -8
  48. package/dist/update-removal-BOue-bJm.js.map +1 -0
  49. package/dist/version-DINEmsQH.js +300 -0
  50. package/dist/version-DINEmsQH.js.map +1 -0
  51. package/package.json +2 -2
  52. package/dist/ambient-client-defaults-7acjxfyN.js.map +0 -1
  53. package/dist/asg-provider-Dvy_jqxt.js.map +0 -1
  54. package/dist/custom-resource-runtime-CRy-dCjZ.js.map +0 -1
  55. package/dist/delete-started-Co5Gt1jH.js.map +0 -1
  56. package/dist/deploy-engine-BwlO3Jv_.js.map +0 -1
  57. package/dist/diff-calculator-CbibK_C3.js.map +0 -1
  58. package/dist/ec2-termination-protection-BM1Zt3Fn.js.map +0 -1
  59. package/dist/iam-role-provider-BaN9MMWs.js.map +0 -1
  60. package/dist/image-plan-C9qclqRY.js.map +0 -1
  61. package/dist/neptune-provider-BYgFNrtZ.js.map +0 -1
  62. package/dist/program-CDu5N31o.js.map +0 -1
  63. package/dist/provider-classes-Diwm8MK7.js.map +0 -1
  64. package/dist/rds-provider-DKZjtd50.js.map +0 -1
  65. package/dist/replacement-rules-01_01yDU.js.map +0 -1
  66. package/dist/update-removal-D-FspP88.js.map +0 -1
  67. package/dist/version-PlqBTGrc.js +0 -11
  68. package/dist/version-PlqBTGrc.js.map +0 -1
@@ -1,19 +1,19 @@
1
- import { t as getCdkdVersion } from "./version-PlqBTGrc.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-C9qclqRY.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-DINEmsQH.js";
2
+ import { $ as renderUnmatchedPatternsWarning, $t as deprecatedRegionOption, A as followContainerLogs, At as recordEmulatorDefaultRegion, B as resolveRuntimeCodeMountPath, Bt as regionShown, C as waitForRieReady, Cn as STATE_KEY_MAX_CODE_POINTS, Ct as setContainerRegion, Dn as parseStateKey, Dt as workloadGetsEmulatorKeysOnly, E as SENSITIVE_ENV_KEYS, En as listAllStateKeys, Et as warnAwsEmulatorStateSourceHint, F as removeContainer, Ft as namedCliRegion, G as partitionTopLevel, Gt as strandedProfileCredentialsNotice, H as resolveRuntimeImage, Ht as stackRegionResolver, It as rawCliRegion, J as renderAllNoTopLevelStacks, Jt as appOptions, K as refuseStackNameRegionCollisions, Kt as writeProfileCredentialsFile, L as runDetached, Lt as reconcileExportIndexRegion, M as killAndDrainContainerLogs, Mt as exportInferredRegionForSdk, N as pickFreePort, Nt as foldRegionOption, O as ensureDockerAvailable, Ot as emulatorDefaultRegion, P as pullImage, Pt as legacyStateBucketFallbackRegion, Q as renderStacksNoLongerSelected, Qt as deployOptions, Rt as reconcileMarkerRegionWithLegacyDefault, S as invokeRie, Sn as STATE_FILE_SUFFIX, St as resolveContainerRegion, T as DockerRunnerError, Tn as listAllLockKeys, Tt as taskRoleAssumedInRealAws, U as describeStack, Ut as stateWithRegion, V as resolveRuntimeFileExtension, Vt as resolveEffectiveRegion, W as matchStacks, Wt as withOtherIndexRemoval, X as renderNoStackMatch, Xt as commonOptions, Y as renderAmbiguousTargetStack, Yt as applyWaitFlagEnv, Z as renderNotInAppWarning, Zt as contextOptions, _ as copyLayerTreeLastWins, _n as resourceTimeoutOptions, _t as mixedModeActive, a as materializeLayerFromArn, an as parseContextOptions, at as buildCdkPathIndex, b as probeHostGatewaySupport, bn as parsePositiveIntegerOption, bt as profileCredentialsForWorkload, cn as stackOptions, ct as stackForConstructPath, d as resolveAssetCodeDirectory, dn as warnIfDeprecatedRegion, dt as assertAwsEmulatorValue, en as destroyOptions, et as selectTargetStack, f as derivePseudoParametersFromRegion$1, fn as effectiveAssumeRoleArn, ft as attachLocalLoopbackForwarder, g as buildContainerImage$1, gn as parseDuration, gt as localAwsEmulatorCredentials, h as architectureToPlatform, hn as allowUnsupportedTypesOption, ht as localAwsEmulatorActive, i as resolveInlineCodeFilePath, in as noLocalCustomResourcesOption, it as unmatchedPatterns, jt as adoptDeprecatedRegionFlag, k as flushStdio, kt as namedEnvAwsRegion, l as resolveLambdaLayers, ln as stateOptions, lt as stackForPathFormTarget, m as tryResolveImageFnJoin, mn as parseAssumeRoleToken, mt as keepEmulatorIssuedCredentials, n as resolveTmpfsForLambda, nn as guardStackRegionOptions, nt as stacksForDependency, o as resolveLambdaTarget, on as parseStackRegion, ot as readCdkPathOrUndefined, p as substituteImagePlaceholders, pn as normalizeStartApiAssumeRole, pt as getActiveWorkloadAwsWiring$1, q as renderAllLeftOutStageStacks, qt as annotationMessageOptions, r as resolveZipImagePlan, rn as noCfnFallbackOption, rt as stacksNoLongerSelected, s as extractEphemeralStorageMb, sn as skipFinalSnapshotOption, st as resolveCdkPathToLogicalIds, t as resolveLocalBuildPlan$1, tn as exclusivelyOption, tt as stackMatchesPattern, u as assetPathDirs, un as useCdkBootstrapAssetsOption, ut as activateLocalAwsAndRoleArn, v as layerAssetDirectory, vn as validateResourceTimeouts, vt as mixedModeEmulatorOverride, w as CONTAINER_LOG_DRAIN_TIMEOUT_MS, wn as describeStateKey, wt as stateRoleRecordIsEmulatorSide, x as resolveHostGatewayExtraHosts, xn as LOCK_FILE_SUFFIX, xt as realAwsException, y as HOST_GATEWAY_MIN_VERSION, yn as cliArgParser, yt as prepareLocalLoopbackForwarder, z as streamLogs, zt as regionNeedsReconciliation } from "./image-plan-DOnhBOIa.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-BOue-bJm.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-Ce9kvuBB.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-CqrM5nDS.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-CbibK_C3.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-BwlO3Jv_.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-BvN5rnLe.js";
9
+ import { $a as assertSendableRoleArn, $c as withStackInstanceIdWithheld, $i as isFinalSnapshotError, $n as recordAfterRollbackUpdate, $o as isStatefulRecreateTargetForReplace, $r as carriedExportAliasExposure, $s as malformedOrphansWarning, $t as resolvePendingCloudControlRequests, A as serviceTokenBlockingReason, Aa as setResolvedResourceTimeouts, Ac as findActionableSdkUnwired, Ai as noEchoAttributeNamesOf, An as noEchoValueMacsOf, As as malformedLocalResourcesWarning, Ba as isAlwaysLiveAttribute, Bc as S3StateBackend, Bi as orphanRecordsPrintingBag, Bl as hasOwnKey, Bn as changedReferencePath, Bo as carriesDynamicReference, Br as withNameGenerationReached, Bs as repairMalformedResourceEntriesForReadOnly, Bt as refuseRefactorMarker, C as templateIdentity, Cc as accountArgs, Ci as withoutSuperseded, Cl as AssetManifestLoader, Cn as DeploymentEventsReader, Co as refStateLookupFromResource, Cr as computeImplicitDeleteEdges, Cs as refuseMalformedOrphanRecordsForDestroy, D as refusePendingMovesOut, Da as CloudControlProvider, Dc as displayLogicalId, Di as green, Dn as noEchoMacBinding, Ds as unreadableOrphanRecords, E as pendingMovesRefusalMessage, Ec as UNREADABLE_RESOURCES_MAP_ROW, Ei as gray, En as createNoEchoValueMacs, Er as findNestedStackTypeChanges, Es as unpreviewableOrphanRecords, F as isProtectionValueActive, Fa as deleteSkipReason, Fi as createReadOnlyAttributeHealerFactory, Fn as hintSidesOf, Fr as nameGenerationHighWaterOf, Fs as refuseMalformedResourceEntriesForDeploy, Ft as recordRetainedForReadoption, Gc as rebuildClientForBucketRegion, Gi as stateSecretNameNeedles, Gn as mappingPairs, Gr as reachableDivergentParameters, Gs as refuseMalformedResourcePropertiesForDestroy, Ha as stackIdTailOf, Hi as secretNamePrintingBags, Hl as nullPrototypeRecord, Hn as differingRemedy, Ho as withSharedDrainBudget, Hr as inheritProducerRegions, Hs as malformedDriftResourcePropertiesWarning, Ht as updateRefactorMarker, I as perType, Ii as completedReplayEntries, Il as decodeListingKey, In as movedToHint, Io as getAccountInfo, Ir as nameScopeOf, Is as refuseMalformedResourceEntriesForDestroy, It as readRefactorMarker, Ja as resolveDynamicReferences, Jc as applyCrossPrefixScan, Ji as ATOMIC_FINAL_SNAPSHOT_TYPES, Jn as proposeRenames, Jr as displayTextOrWithheld, Js as refuseMalformedResourcePropertiesForOrphan, Ka as secretSegmentsOfState, Kc as CrossPrefixReadError, Ki as storedSecretNameNeedles, Kl as describeFileReadFailure, Kn as parseMappingFile, Kr as resourcesNamingDeclaredParameter, Ks as refuseMalformedResourcePropertiesForDrift, L as readProtection, La as isWaitAbandonedError, Lc as NO_CC_HANDLERS_REASON, Li as journaledOrphanPrintingBag, Ln as rollbackOrphanIds, Lo as isImpossibleEmptyStoredAttribute, Lr as retiredAfterRollback, Ls as refuseMalformedResourceEntriesForImport, Lt as readRefactorMarkerOnce, M as recordedProtectionEvidence, Ma as UNSPECIFIED_SKIP_REASON, Mi as noEchoExactEchoLeavesOf, Mn as findDestructiveChanges, Mr as removeProtectionTypeList, Ms as malformedScrubResourceEntriesRefusalMessage, N as recordedProtectionNote, Na as deleteIndeterminateGuards, Nc as unwrittenCreateOnlyReplacement, Ni as noEchoParameterNamesOf, Nl as ssmResolvedValueType, Nn as formatDestructiveChange, No as recordedReferenceRegions, Nr as orphanNeedsIdentity, Ns as refuseMalformedResourceAttributesForOrphan, O as deferredServiceTokenWarning, Oc as hasReadableOutputs, Oi as red, On as noEchoMacParametersOf, Os as isReadableResourceEntry, P as PROTECTION_PROPERTY_BY_TYPE, Pa as deleteLeftInPlace, Pi as withAttemptedItemsMasked, Pl as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, Pn as findRefactorHints, Pr as nameGenerationCarriedFrom, Ps as refuseMalformedResourceEntries, Pt as keptForRetainedRecord, Qa as assertFlagRoleArn, Qc as stackInstanceIdOf, Qi as effectiveDeletionPolicy, Ql as resolveBucketRegion, Qn as DELETED_RESOURCE_REMEDY, Qo as MULTI_REGION_RECREATE_BLOCKED_TYPES, Qr as secretSafeKeyDisplay, Qs as malformedOrphansRefusalMessage, Qt as pendingRequestCount, Ra as IntrinsicFunctionResolver, Rc as hasNoCloudControlHandlers, Ri as maskEventTextWithBoundBags, Rn as withMovedTo, Ro as carriesFetchableDynamicReference, Rr as retiredNameGenerationsAfter, Rs as refuseMalformedResourceEntriesForImportSave, Rt as refactorMarkerMovesOf, S as renderNestedTemplateTreeDefect, Sa as localCustomResourceCommand, Sc as JSON_LISTING_HOLE_VALUE, Si as supersededResourcesOf, Sl as BOOTSTRAP_MARKER_PREFIX, Sn as planOrphanAdoption, So as isStalePlaceholderArnAttribute, Sr as IMPLICIT_DELETE_DEPENDENCIES, Ss as refuseMalformedOrphanRecords, T as pendingMovesOutOf, Ta as withCustomResourceStack, Tc as STATE_RESOURCES_MALFORMED, Ti as cyan, Tn as NOECHO_MAC_KEY_ALIAS, To as lacksRecordedTableArn, Tr as withPreviousPolicies, Ts as repairMalformedOrphanRecordsForReadOnly, Uc as hasReasonlessBaselineRefusal, Ul as ownValue, Un as isPairableType, Ur as computeParameterTaint, Us as malformedResourcePropertiesWarning, Ut as macWriteOnlyKeys, Va as poisonRenderedSpellingsCollidingIn, Vc as splitImportedOps, Vi as secretNamePrintingBag, Vl as hasPlainPrototype, Vn as changedReferenceReason, Vo as keepsSecretReferenceToken, Vs as unreadableResourceEntries, Vt as sameMove, Wc as hasUnverifiableParameterRefusal, Wi as secretNamedRecordNeedles, Wn as looselyEqual, Wo as INTRINSIC_KEYS, Wr as namesAnyDeclaredParameter, Wt as readsOnlyNoEchoParameters, Xa as refuseUnreadableCdkCrossAccountRefs, Xc as isAccessDenied, Xi as ccRoutedFinalSnapshotError, Xl as resolveAssemblyPath, Xn as replayFailedOperations, Xr as secretBearing, Xs as UNREADABLE_ORPHANS_CONTAINER_ROW, Ya as producerLookupOver, Yc as crossPrefixDeniedWarning, Yi as PRE_DELETE_SNAPSHOT_TYPES, Yl as renderAssemblyPathEscape, Yn as referencedLogicalIds, Yo as findReplacedReadersOfRecreateTargets, Yr as exportAliasCollisionScrubWarning, Ys as repairMalformedResourcePropertiesForReadOnly, Za as applyRoleArnIfSet, Zc as isNotImplemented, Zi as ccRoutedInstanceTakesNoSnapshot, Zn as replayRollback, Zo as shownType, Zr as secretBearingStateKeyWarning, Zs as hasReadableOrphans, _ as readRecordedConditionVerdicts, _a as withPrintingSecrets, _c as refuseMalformedResourcesForDeploy, _i as holdsSupersededResources, _l as getBootstrapMarkerKey, _n as journaledOrphanLines, _o as coerceParameterTypedValue, _r as isReplacementOrphan, _s as isReadableOrphanRecord, a as healSlashedSsmParameterNames, aa as ProviderRegistry, ac as malformedLocalOutputsWarning, ai as collectPublishedOutputNames, an as nestedChildStackName$1, ao as applyCallerIdentityCredentials, ar as undeclaredEmptyObservedKeys, b as isAbsoluteAssetPath, ba as customResourcesFailedWithoutApp, bc as refuseMalformedState, bi as supersededHeldByOtherTypeWarning, bl as validateAssetBucketName, bn as makeForeignHolderScan, bo as AWS_NO_VALUE, br as recordUnderIdIsNotOwn, bs as malformedOrphanRowsKeptWarning, c as slashedSsmNameHealPendingNote, ca as wouldReturnToSdkProvider, ci as DEFAULT_RESOURCE_TIMEOUT_MS, cl as loadPublishableAssetManifest, cn as revertedNestedRowIds, co as classifyRecordedSecretRegion, d as crossStackOutputProvenanceSource, da as customResourceResponseExpirationWarning, dc as repairMalformedOutputsForReadOnly, dl as rewriteTemplateAssetReferences, dn as getCurrentNestedStackContext, do as regionLessSecretName, dr as withCreateTokenLedger, ds as parameterInputsFor, ea as refusesFinalSnapshot, ec as refuseMalformedOrphans, ei as exportNameNoEchoParameters, el as isSecretValuedAttribute, en as NESTED_PENDING_PARENT_REASON, eo as explicitRoleArnOrThrow, er as settleUnsettledPrevious, es as isStatefulRecreateTargetSync, f as inheritedProvenanceForChildDiff, fc as STATE_REGION_DIVERGED, fi as destroyStackRecordsView, fl as AssetModeResolver, fn as withNestedStackContext, fs as maskedInputProof, g as parentSuppliedValues, gc as malformedStateRefusalMessage, gi as deleteSupersededEntry, gl as isCrossRegionRedirect, gn as isHandledOrphan, gr as isJournaledOrphan, gs as deployRefusesOrphanRowsReason, h as conditionInputsFrom, ha as isCustomResourceType$1, hc as malformedResourcesWarning, hl as assertAssetBucketRegion, hn as dropFailedHint, hr as demoteSupersededOrphans, hs as maskedPropertyFingerprint, i as mergeNoChangeOutputs, ia as CC_BROKEN_REASON, ic as malformedExportSourceWarning, ii as collectDeclaredOutputNames, il as createAssetRedirectResolver, io as AWS_CREDENTIAL_ENV_KEYS, ir as equalModuloMask, j as diffSecurity, ja as RollbackInlinePolicyWriters, jc as findHandledUnwrittenCreateOnly, ji as noEchoComparisonForTemplate, jn as constructPathOf$1, jo as recordedOutputReferenceRegions, jr as segmentCleanupOptions, js as malformedResourceEntriesWarning, k as findServiceTokenRefusals, kc as hasReadableResources, ki as yellow, kn as noEchoMacVerdict, ko as keepHeldTokenProvenance, ks as malformedLocalResourceEntriesWarning, l as scanActiveConsumers, la as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, lc as refuseMalformedOutputs, li as DEFAULT_RESOURCE_WARN_AFTER_MS, ln as withNestedRevertRun, lo as classifyReplaySecretRegion, lr as ledgerForStack, ls as maskedPropertyFingerprintsOf, m as conditionFingerprint, ma as readsNoEchoDeleteValues, mc as malformedRenderedContainersWarning, mi as withStackRecords, ml as buildDenyExternalAccessPolicy, mn as dropFailedCommands, mr as seedsDeleteFirstGuard, ms as declaresNoEcho, n as isSecretBearingReferenceString, na as createPreDeleteFinalSnapshot, nc as repairMalformedOrphansForReadOnly, ni as isWholeDynamicReferenceValue, nn as displacedPhysicalIdShown, no as parseIamRoleArn, nr as calculateResourceDrift, o as slashedSsmNameHealAdoptedNote, oa as ccBrokenReason, oc as malformedOutputsRefusalMessage, oi as isExportAliasCollision, on as recordDisplacedSkips, oo as callerEnvCredentials, or as updatePartialMessage, p as makeCanonicalizePropertiesFn, pa as TemplateNoEchoReresolver, pc as refuseDivergentRecordRegionForDestroy, pl as ensureAssetStorage, pn as deleteJournaledOrphans, pr as planRollback, qa as withSecretPhysicalIdsMaskedInState, qc as CrossPrefixScanCache, qi as extractDeploymentEventError, ql as displayAssemblyPath, qn as propertiesChangedReason, qr as WITHHELD_NAME_DISPLAY, qs as refuseMalformedResourcePropertiesForExport, qt as formatResourceLine, r as keptWholeReasonText, ra as buildFinalSnapshotIdentifier, rc as malformedExportNamesWarning, ri as noEchoParameterValueSeed, rl as buildAssetRedirectMap, rn as dropSettledNestedJournals, ro as sendableAssumeRoleCommand, rr as equalModuloMarkedMask, s as slashedSsmNameHealNote, sa as isCustomResource, sc as malformedOutputsWarning, si as bindingSkippedOutputs, so as envCredentialsAreAssumedRole, sr as updatePartialReason, t as DeployEngine, ta as unsupportedFinalSnapshotError, tc as refuseMalformedOrphansForDestroy, ti as exportNameSecretExposure, tl as isSensitiveAttributeName, tn as displacedOpClause, to as isIamRoleArn, tr as withUnprovenUnsettled, ts as renderStatefulReason, u as inRunStackKey, ua as applyCustomResourceResponseExpiration, uc as refuseMalformedOutputsForDestroy, ui as maskingRetryLogger, un as collectNestedChildUnaddressed, uo as producerRegionsFromState, v as childTemplateLoader, va as NO_LOCAL_CUSTOM_RESOURCES_FLAG, vc as refuseMalformedResourcesForDestroy, vi as isSupersededResourceRecord, vl as parseBootstrapMarker, vn as loadJournaledOrphans, vo as isUnboundTemplateParameter, vr as planFailedOps, vs as malformedOrphanRecordsRefusalMessage, w as hasPendingMovesOut, wa as setLocalCustomResourceRuntimeEnabled, wc as withheldAccountClause, wi as bold, wl as getDockerImageBySourceHash, wn as DeploymentEventsStore, wo as lacksRecordedRefArn, wr as resolveReplacementOldType, ws as refuseMalformedOrphansForOrphan, x as listNestedTemplateRows, xa as customResourcesRunWithoutApp, xc as repairMalformedResourcesForReadOnly, xi as supersededHolderOf, xl as validateContainerRepoName, xn as makeSiblingClaimReader, xo as cfnRefValueFromPhysicalId, xr as replacementNeverSwapped, xs as previewableOrphanRecords, y as findNestedTemplateTreeDefect, yc as refuseMalformedResourcesForExport, yi as supersededAfterRollback, yl as readBootstrapMarkerBody, yn as sameJournaledOrphans, yo as parameterTypeMayLoseSecretIdentity, yr as recheckFailedPlan, ys as malformedOrphanRecordsWarning, za as isSelectOutOfBounds, zc as TemplateParser, zi as namingSecretsWithRecordedNoEcho, zl as defineOwnKey, zn as changedReferenceInDiff, zo as isNamelessDynamicReferenceError, zr as retiredNameGenerationsLeaving, zs as refuseMalformedResourceEntriesForOrphan, zt as refactorMarkerRefusalMessage } from "./deploy-engine-Sw2eta-t.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";
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";
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-BIIHrzUa.js";
12
+ import { t as expectedOwnerParam } from "./expected-bucket-owner-DR9qK772.js";
13
+ import { _ as stackInstanceIdCarriedFrom, a as slowCcOperationTimeoutMs, c as exportNamesCarriedFrom, d as importableOutputs, f as isReadableBag, h as shouldRetainResource, l as hasReadableExportSet, m as orphansCarriedFrom, o as acceptedCreateOnlyDropsOf, p as orphansAfterRollback, s as describeRegionValueKind, u as importableOutputKeys } from "./delete-started-C0g7PYI-.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-lOM1aGPr.js";
15
+ import { D as withoutUnsettledProperties, E as withUnsettledProperties, S as unsettledItemsOf, i as withResourceDeadline, w as unsettledPropertiesOf, x as unsettledItemsField } from "./resource-deadline-1VcUPyH4.js";
16
+ import { a as parseEcrRegistryHost, i as looksLikeEcrHostWithForeignSuffix, n as hasEcrRegistryHostLabels, t as ecrRegistryHostPattern } from "./ecr-uri-CQ_BCOjX.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, containsCrossStackIntrinsic, 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() {
@@ -174,7 +181,9 @@ function onStderr(fn) {
174
181
  return result;
175
182
  }
176
183
  function pointEnvironmentAtEmulator(url, port, caBundle) {
177
- Object.assign(process.env, emulatorEnvironment(url, port, process.env));
184
+ const pointed = emulatorEnvironment(url, port, process.env);
185
+ Object.assign(process.env, pointed);
186
+ if (pointed["AWS_REGION"] !== void 0) recordEmulatorDefaultRegion(pointed["AWS_REGION"]);
178
187
  const run = readEmulatorRunFiles(port);
179
188
  const caPath = join(run.dir, "ca.pem");
180
189
  const runCa = run.present && existsSync(caPath) ? caPath : devNull;
@@ -471,9 +480,12 @@ async function bootstrapDestroyCommand(options) {
471
480
  const stateKeys = await listAllStateKeys(stateBackend);
472
481
  if (stateKeys.length > 0) {
473
482
  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");
483
+ 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
484
  }
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");
485
+ 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" }, {
486
+ flag: "--region",
487
+ hole: "r"
488
+ }]).command} for each first.`, "STATE_BUCKET_HOLDS_MARKERS");
477
489
  if (markerSiblings.sameRegionKeys.length > 0) {
478
490
  const canonicalStillPresent = markerBody !== null && resolvedMarkerKey === markerKey;
479
491
  const listing = markerSiblings.sameRegionKeys.map((k, i) => ` ${i + 1}. ${k}`).join("\n");
@@ -629,7 +641,7 @@ async function ensureNoEchoMacKey(args) {
629
641
  return "skipped";
630
642
  }
631
643
  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.`);
644
+ 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
645
  return "failed";
634
646
  };
635
647
  try {
@@ -638,7 +650,7 @@ async function ensureNoEchoMacKey(args) {
638
650
  report(`NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS} already exists`);
639
651
  return "exists";
640
652
  }
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'.`);
653
+ 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
654
  return "failed";
643
655
  } catch (error) {
644
656
  if (errorName(error) !== "NotFoundException") return failed("kms:DescribeKey", error);
@@ -680,7 +692,7 @@ async function ensureNoEchoMacKey(args) {
680
692
  } catch (describeError) {
681
693
  return failed("kms:DescribeKey", describeError);
682
694
  }
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'.`);
695
+ 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
696
  return "failed";
685
697
  }
686
698
  report(`Created the NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS}`);
@@ -1200,7 +1212,7 @@ function createApprovalPrompter(options) {
1200
1212
  return serializePrompt(() => getLiveRenderer().suspendWhile(async () => {
1201
1213
  process.stdout.write(renderApprovalRequest(request));
1202
1214
  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'.`,
1215
+ 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
1216
  suffix: " (y/n) "
1205
1217
  });
1206
1218
  }));
@@ -1298,12 +1310,14 @@ function watchCommandInterrupt(opts) {
1298
1310
  return;
1299
1311
  }
1300
1312
  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");
1313
+ process.stderr.write(`
1314
+ Force-quit.
1315
+ If the next run reports a stack lock, release it with: ${pasteableCommand("cdkd force-unlock", [{ hole: "stack-name" }]).command}\n`);
1302
1316
  process.exit(130);
1303
1317
  }
1304
1318
  markInterrupted();
1305
1319
  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`);
1320
+ 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
1321
  process.exit(130);
1308
1322
  }
1309
1323
  process.stderr.write(`\nInterrupted — ${opts.command} will stop before starting another stack (press Ctrl-C again to force-quit)...\n`);
@@ -1436,7 +1450,7 @@ function collectCrossStackRefs(node, onRef, unconditional) {
1436
1450
  // src/provisioning/register-providers.ts
1437
1451
  let providerClasses;
1438
1452
  function loadProviderClasses() {
1439
- providerClasses ??= import("./provider-classes-Diwm8MK7.js");
1453
+ providerClasses ??= import("./provider-classes-CM8Txuvb.js");
1440
1454
  return providerClasses;
1441
1455
  }
1442
1456
  function registerAllProviders(registry, classes) {
@@ -2243,7 +2257,7 @@ async function ensureAwsEmulatorStateBucket(args) {
2243
2257
  await configureStateBucket(setup);
2244
2258
  } catch (error) {
2245
2259
  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);
2260
+ 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
2261
  }
2248
2262
  logger.info(safeMsg`AWS Emulator had no cdkd bootstrap; bootstrapped it (state bucket ${bucketName}).`);
2249
2263
  return bucketName;
@@ -2629,7 +2643,7 @@ async function probeStatefulRecreateTargetsAsync(targets, clients, logger = getL
2629
2643
  let regionVerified = true;
2630
2644
  if (clients.expectedRegionDiverged) {
2631
2645
  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.`);
2646
+ 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
2647
  }
2634
2648
  const recordedRegion = clients.expectedRegionDiverged ? void 0 : foldRegion(clients.expectedRegion);
2635
2649
  if (recordedRegion) {
@@ -3942,7 +3956,7 @@ async function injectRetainPoliciesRecursiveInternal(templateBody, cfnStackName,
3942
3956
  const r = resource;
3943
3957
  if (r["Type"] !== "AWS::CloudFormation::Stack") continue;
3944
3958
  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.`);
3959
+ 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
3960
  const childTpl = await deps.cfnClient.send(new GetTemplateCommand({
3947
3961
  StackName: childNode.physicalId,
3948
3962
  TemplateStage: "Original"
@@ -4177,7 +4191,7 @@ async function prepareCloudFormationStackRetirement(options) {
4177
4191
  };
4178
4192
  }
4179
4193
  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." });
4194
+ 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
4195
  }
4182
4196
 
4183
4197
  // src/cli/commands/retire-cfn-stack/delete-stack.ts
@@ -5448,8 +5462,19 @@ async function previewNoEchoMacChanges(args) {
5448
5462
  }
5449
5463
 
5450
5464
  // src/cli/commands/diff-recursive/compute-stack-diff.ts
5451
- async function computeStackDiff(currentState, template, region, stackName, stateBackend, diffCalculator, options = {}) {
5452
- const { parameters, canonicalizeProperties, ccRouteUnavailableReason, cfnFallback, producerLookup, consumerAccount, noEchoMacCache, macWriteOnlyLookups, inheritSecretBearingTemplate, inheritedSecrets, inheritedSecretTokens, inheritedDerivedNames, attributeHealer: unboundAttributeHealer, parentUnresolvedParameters, inheritedNoEchoParameters, inheritedNoEchoParametersAnyVerdict } = options;
5465
+ async function computeStackDiff(loadedState, template, region, stackName, stateBackend, diffCalculator, options = {}) {
5466
+ const { parameters, canonicalizeProperties, ccRouteUnavailableReason, cfnFallback, producerLookup, consumerAccount, noEchoMacCache, macWriteOnlyLookups, inheritSecretBearingTemplate, inheritedSecrets, inheritedSecretTokens, inheritedDerivedNames, attributeHealer: unboundAttributeHealer, parentUnresolvedParameters, inheritedNoEchoParameters, inheritedNoEchoParametersAnyVerdict, ssmNameHeal = "apply" } = options;
5467
+ const healSsmNames = (state) => {
5468
+ const healed = healSlashedSsmParameterNames(state, template, stackName);
5469
+ if (healed.heals.length === 0) return state;
5470
+ for (const heal of healed.heals) if (ssmNameHeal === "apply") logger.info(slashedSsmNameHealNote(heal));
5471
+ else logger.info(slashedSsmNameHealPendingNote(heal, stackName));
5472
+ return ssmNameHeal === "apply" ? {
5473
+ ...state,
5474
+ resources: healed.resources
5475
+ } : state;
5476
+ };
5477
+ const currentState = healSsmNames(loadedState);
5453
5478
  let healResources = currentState.resources ?? {};
5454
5479
  let healNamingSecrets;
5455
5480
  const attributeHealer = unboundAttributeHealer && healerUnderRecordPrintingBag(unboundAttributeHealer, () => healResources, (map) => healNamingSecrets?.(map));
@@ -5560,7 +5585,15 @@ async function computeStackDiff(currentState, template, region, stackName, state
5560
5585
  healResources = resources;
5561
5586
  }
5562
5587
  });
5563
- const { adoptedOrphans, adoptedRecords, deployRefusals, stateForDiff, unreadableOrphans } = orphanSplice;
5588
+ const { adoptedOrphans, adoptedRecords, deployRefusals, unreadableOrphans } = orphanSplice;
5589
+ const { stateForDiff } = orphanSplice;
5590
+ if (Object.keys(adoptedRecords ?? {}).length > 0) {
5591
+ const adopted = {
5592
+ ...currentState,
5593
+ resources: adoptedRecords
5594
+ };
5595
+ for (const heal of healSlashedSsmParameterNames(adopted, template, stackName).heals) logger.info(slashedSsmNameHealAdoptedNote(heal));
5596
+ }
5564
5597
  let { blocking } = orphanSplice;
5565
5598
  let maskedInputs;
5566
5599
  if (options.previewMaskedInputs === true) {
@@ -5835,8 +5868,12 @@ function collectCcApiRoutes(template, state, changes, ccRouteUnavailableReason)
5835
5868
  }
5836
5869
 
5837
5870
  // src/cli/commands/diff-recursive/build-tree.ts
5871
+ function childRowRunsEngine(row) {
5872
+ if (row?.changeType === "CREATE") return true;
5873
+ return row?.changeType === "UPDATE" && (row.propertyChanges?.length ?? 0) > 0;
5874
+ }
5838
5875
  async function buildDiffTree(args) {
5839
- const { stackName, displayName, region, template, nestedTemplates, recursive, stateBackend, diffCalculator, parentHasSecretReference, parameters, parentUnresolvedParameters, canonicalizeProperties, ccRouteUnavailableReason, assetRedirect, cfnFallback, producerLookup, consumerAccount, previewOrphanAdoption, attributeHealerFor, ancestorTemplatePaths, isNestedChild, inheritedSecrets, inheritedDerivedNames, inheritedNoEchoParameters, inheritedNoEchoParametersAnyVerdict, refusalRecovery, inheritedReferenceProvenance, inheritedSecretTokens } = args;
5876
+ const { stackName, displayName, region, template, nestedTemplates, recursive, stateBackend, diffCalculator, parentHasSecretReference, parameters, parentUnresolvedParameters, canonicalizeProperties, ccRouteUnavailableReason, assetRedirect, cfnFallback, producerLookup, consumerAccount, previewOrphanAdoption, attributeHealerFor, ancestorTemplatePaths, isNestedChild, ssmNameHeal, inheritedSecrets, inheritedDerivedNames, inheritedNoEchoParameters, inheritedNoEchoParametersAnyVerdict, refusalRecovery, inheritedReferenceProvenance, inheritedSecretTokens } = args;
5840
5877
  const unboundHealer = attributeHealerFor?.(stackName, region);
5841
5878
  const { state, unreadable, unreadableContainers, deployRefusals, found } = await loadStateOrEmpty(stackName, region, stateBackend, refusalRecovery);
5842
5879
  const attributeHealer = unboundHealer;
@@ -5863,6 +5900,7 @@ async function buildDiffTree(args) {
5863
5900
  ...refusalRecovery && { refusalRecovery },
5864
5901
  inheritSecretBearingTemplate: false,
5865
5902
  previewMaskedInputs: !isNestedChild,
5903
+ ...ssmNameHeal && { ssmNameHeal },
5866
5904
  nestedTemplates
5867
5905
  });
5868
5906
  } finally {
@@ -5958,6 +5996,7 @@ async function buildDiffTree(args) {
5958
5996
  ...attributeHealerFor && { attributeHealerFor },
5959
5997
  ancestorTemplatePaths: childAncestorTemplatePaths,
5960
5998
  isNestedChild: true,
5999
+ ssmNameHeal: ssmNameHeal !== "pending" && childRowRunsEngine(changes.get(logicalId)) ? "apply" : "pending",
5961
6000
  parentHasSecretReference: secretBearingAbove,
5962
6001
  inheritedSecrets: printingSecrets,
5963
6002
  ...hasMaskableValues(childDerivedNames) && { inheritedDerivedNames: childDerivedNames },
@@ -6201,7 +6240,7 @@ function renderChangeLines(changes, logFn, ccApiRoutes, adoptedOrphans, refactor
6201
6240
  delete: deleteCount
6202
6241
  };
6203
6242
  }
6204
- const REDACTED_LEGACY_PLAINTEXT = "<redacted: may be legacy plaintext in state — run `cdkd scrub`>";
6243
+ const redactedLegacyPlaintext = () => `<redacted: may be legacy plaintext in state — run ${proseQuoted(cdkdRemedy("cdkd scrub"), "`")}>`;
6205
6244
  function stripDisplayOnlyChars(value) {
6206
6245
  return value.replace(/[\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "").replace(/[\u2028\u2029]/g, " ");
6207
6246
  }
@@ -6215,7 +6254,7 @@ function renderOutputChangeLines(outputChanges, logFn) {
6215
6254
  logFn("\n Outputs:");
6216
6255
  const indent = " ";
6217
6256
  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);
6257
+ const renderOld = (change) => change.oldValueRedacted ? redactedLegacyPlaintext() : render(change.oldValue);
6219
6258
  for (const change of outputChanges) {
6220
6259
  const exported = change.isExport ? " [export]" : "";
6221
6260
  const name = outputNameRow(change);
@@ -6704,7 +6743,7 @@ async function saveScrubbedState(stateBackend, stackName, region, state, loaded)
6704
6743
  const SCRUB_CLEAN_SCOPE_NOTE = " (scrub checks only values the template names through a {{resolve:...}} reference)";
6705
6744
 
6706
6745
  // src/cli/commands/scrub/nested.ts
6707
- const NESTED_STACK_TYPE$1 = "AWS::CloudFormation::Stack";
6746
+ const NESTED_STACK_TYPE$2 = "AWS::CloudFormation::Stack";
6708
6747
  function readNestedChildTemplate$1(templatePath) {
6709
6748
  let template;
6710
6749
  try {
@@ -6739,7 +6778,7 @@ function nestedChildWorkItem(parent, region, child) {
6739
6778
  const nestedChild = child.refusal !== void 0 ? child : {
6740
6779
  logicalId: child.logicalId,
6741
6780
  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.")
6781
+ 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
6782
  };
6744
6783
  return {
6745
6784
  stack: {
@@ -7265,7 +7304,7 @@ var ScrubResolvers = class {
7265
7304
  }
7266
7305
  };
7267
7306
  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");
7307
+ 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
7308
  }
7270
7309
  function unresolvableForeignScrubSecretError(origin, stackName, secretName, region, cause, secrets, recorded = false) {
7271
7310
  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 +7475,7 @@ function effectiveIntrinsicKey(node) {
7436
7475
  return RESOLVER_INTRINSIC_PRECEDENCE.find((key) => key in node);
7437
7476
  }
7438
7477
  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");
7478
+ 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
7479
  }
7441
7480
  function scrubRefusalWording(verdict, loggedExportKey, loggedProducerStack, loggedVia, maskedNames = /* @__PURE__ */ new Set()) {
7442
7481
  const chain = dedupePreservingOrder(loggedVia, "first");
@@ -7449,7 +7488,7 @@ function scrubRefusalWording(verdict, loggedExportKey, loggedProducerStack, logg
7449
7488
  const built = scrubOrder.map((name) => scrubCommandFor(name));
7450
7489
  const remedyCommands = built.map((b) => `Scrub with: ${b.command}`);
7451
7490
  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("");
7491
+ 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
7492
  return {
7454
7493
  templateClaim,
7455
7494
  remedy: scrubOrder.length > 1 ? `Scrub the producers first, from the head of the chain, in the order below` : `Scrub the producer first`,
@@ -7907,7 +7946,7 @@ async function scrubStackResolvePass({ stack, region, logger, newBag, perResourc
7907
7946
  const bagKeys = resolveInput !== null && typeof resolveInput === "object" && !Array.isArray(resolveInput) ? Object.keys(resolveInput) : void 0;
7908
7947
  const intrinsicShapedBag = bagKeys?.some((k) => RESOLVER_DISPATCH_KEYS.has(k)) ?? false;
7909
7948
  const resolveUnits = bagKeys && !intrinsicShapedBag ? Object.entries(resolveInput) : [["", resolveInput]];
7910
- const isNestedRow = templateResource.Type === NESTED_STACK_TYPE$1;
7949
+ const isNestedRow = templateResource.Type === NESTED_STACK_TYPE$2;
7911
7950
  const resolvedRowProps = nullPrototypeRecord();
7912
7951
  if (isNestedRow) nestedRowParameters.set(logicalId, {
7913
7952
  value: void 0,
@@ -7943,7 +7982,7 @@ async function scrubStackResolvePass({ stack, region, logger, newBag, perResourc
7943
7982
  }
7944
7983
  perResourceTemplateProps.set(logicalId, templateResource.Properties);
7945
7984
  const nestedParameters = nestedRowParameters.get(logicalId);
7946
- if (isNestedRow && nestedParameters?.complete === true) recordNestedStackParameterExpressions(recordedSecretValues, NESTED_STACK_TYPE$1, resolvedRowProps, templateResource.Properties);
7985
+ if (isNestedRow && nestedParameters?.complete === true) recordNestedStackParameterExpressions(recordedSecretValues, NESTED_STACK_TYPE$2, resolvedRowProps, templateResource.Properties);
7947
7986
  }
7948
7987
  for (const [orphanIndex, record] of (state.orphans ?? []).entries()) {
7949
7988
  const recordedSecretValues = newBag();
@@ -8372,13 +8411,13 @@ async function scrubStackRewritePass({ stack, region, stateBackend, opts, logger
8372
8411
  continue;
8373
8412
  }
8374
8413
  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.`);
8414
+ 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
8415
  continue;
8377
8416
  }
8378
8417
  const resolved = nestedRowParameters.get(logicalId);
8379
8418
  const parameters = resolved?.complete === true ? nestedChildParameters(resolved.value) : void 0;
8380
8419
  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."));
8420
+ 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
8421
  continue;
8383
8422
  }
8384
8423
  nestedChildren.push({
@@ -8592,14 +8631,14 @@ async function scrubStackRewritePass({ stack, region, stateBackend, opts, logger
8592
8631
  readers = findDroppedOutputReaders(stack.stackName, region, dropping, await (opts.readConsumerRecords ?? (() => readConsumerRecords(stateBackend, region)))());
8593
8632
  } catch (err) {
8594
8633
  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.");
8634
+ 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
8635
  dropping = /* @__PURE__ */ new Set();
8597
8636
  }
8598
8637
  if (readers !== void 0 && readers.length > 0) {
8599
8638
  const read = readers.some((r) => r.key === void 0) ? new Set(dropping) : new Set(readers.map((r) => r.key));
8600
8639
  keptReadOutputKeys = read.size;
8601
8640
  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.");
8641
+ 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
8642
  dropping = new Set([...dropping].filter((key) => !read.has(key)));
8604
8643
  }
8605
8644
  }
@@ -9013,7 +9052,7 @@ async function runScrubTargets({ options, logger, effectiveRegion, region, state
9013
9052
  logger.error(`Scrub of ${shownStack} failed: ${describeFailure(err)}`);
9014
9053
  if (err instanceof Error && err.stack) logger.debug("Stack trace:", err.stack);
9015
9054
  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({
9055
+ 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
9056
  stackName,
9018
9057
  displayName: stackName,
9019
9058
  artifactId: stackName,
@@ -9025,7 +9064,7 @@ async function runScrubTargets({ options, logger, effectiveRegion, region, state
9025
9064
  }
9026
9065
  let unreached;
9027
9066
  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).");
9067
+ 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
9068
  } catch (err) {
9030
9069
  failures.push({ stackName: `${stackName}~*` });
9031
9070
  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 +9550,7 @@ function incompleteRemediationMessage(reports, mode) {
9511
9550
  return [
9512
9551
  `Comparison INCOMPLETE — nothing to ${mode}, and that is NOT a clean bill of health: ${uncompared} of ${total} resource(s) could not be compared.`,
9513
9552
  ...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.`
9553
+ `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
9554
  ];
9516
9555
  }
9517
9556
 
@@ -9640,7 +9679,7 @@ function isDriftSecretRefusal(err) {
9640
9679
  }
9641
9680
  function regionAmbiguousDriftSecretError(logicalId, propertyPath, secretName, foreignProducerRegions, consumerRegion) {
9642
9681
  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");
9682
+ 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
9683
  }
9645
9684
  function refuseUnprovenDriftSecret(leaf, propertyPath, logicalId, consumerRegion, evidence, recordedRegions) {
9646
9685
  if (evidence.complete) return;
@@ -9649,7 +9688,7 @@ function refuseUnprovenDriftSecret(leaf, propertyPath, logicalId, consumerRegion
9649
9688
  const name = classifyReplaySecretRegion(token, consumerRegion, evidence.regions).kind === "local" ? regionLessSecretName(token) : void 0;
9650
9689
  if (name === void 0) continue;
9651
9690
  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");
9691
+ 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
9692
  }
9654
9693
  }
9655
9694
  function noteUnreadableAncestor(stackName, region, why) {
@@ -9750,10 +9789,22 @@ async function resolveStateSecretExpressions(props, resolvers, secrets, options)
9750
9789
  }
9751
9790
 
9752
9791
  // 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.";
9792
+ function acceptRefusedRemedy() {
9793
+ return `Once the deployed template no longer reads a parameter at this resource, ${pasteableCommand("cdkd state refresh-observed", [
9794
+ { hole: "stack" },
9795
+ {
9796
+ flag: "--accept-refused",
9797
+ hole: "logicalId"
9798
+ },
9799
+ {
9800
+ flag: "--template",
9801
+ hole: "file"
9802
+ }
9803
+ ]).command} records a baseline on your assertion that AWS holds no secret the template does not spell as a dynamic reference.`;
9804
+ }
9754
9805
  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;
9806
+ 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();
9807
+ 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
9808
  }
9758
9809
 
9759
9810
  // src/cli/commands/drift/redaction.ts
@@ -10535,7 +10586,7 @@ async function runAccept(reports, regionScope, stateBackend, stateConfig, awsCli
10535
10586
  const refusal = acceptRefusalReason(change, outcome.maskedPaths);
10536
10587
  if (refusal !== void 0) {
10537
10588
  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}`));
10589
+ 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
10590
  continue;
10540
10591
  }
10541
10592
  setAtPath(newBaseline, change.path, change.awsValue);
@@ -11132,7 +11183,7 @@ function warnIfPreV10BaselineGap(state, outcomes, logger) {
11132
11183
  if (affected.length === 0) return [];
11133
11184
  const shown = affected.slice(0, 10).join(", ");
11134
11185
  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.`;
11186
+ 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
11187
  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
11188
  logger.warn(finding);
11138
11189
  logger.warn(note);
@@ -11173,7 +11224,7 @@ function canonicalizeDerivedPatternBName(resourceType, baseline, aws) {
11173
11224
  // src/cli/commands/drift/detect.ts
11174
11225
  async function runDriftForStack(stackName, region, stateBackend, providerRegistry, ccApiFallback, resolvePrincipalUniqueId, malformedRecordMode, nestedChildRecord, refusalRecovery) {
11175
11226
  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.`);
11227
+ if (!result) throw new Error(`No state found for stack '${stackName}' (${region}). Run ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
11177
11228
  const namingScope = nameScopeOf(stackName, stackInstanceIdOf(result.state, displayStackName(stackName)), result.state);
11178
11229
  return await withStackScope(namingScope, async () => {
11179
11230
  const outcomes = [];
@@ -11549,7 +11600,7 @@ async function revertDriftedOutcome(args) {
11549
11600
  const intrinsicObjectPaths = collectUnresolvedIntrinsicObjectPaths(desiredProperties, driftedTopLevelKeys);
11550
11601
  if (intrinsicObjectPaths.length > 0) {
11551
11602
  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.`);
11603
+ 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
11604
  return;
11554
11605
  }
11555
11606
  }
@@ -11745,7 +11796,7 @@ async function runRevert(reports, regionScope, stateBackend, stateConfig, awsCli
11745
11796
  ...reRecordedCount > 0 ? ["the identity the revert returned"] : [],
11746
11797
  ...settledCount > 0 ? ["that a failed deploy's unsettled properties are settled"] : []
11747
11798
  ].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}`) : ""));
11799
+ 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
11800
  }
11750
11801
  }
11751
11802
  } finally {
@@ -11761,8 +11812,8 @@ async function runRevert(reports, regionScope, stateBackend, stateConfig, awsCli
11761
11812
  if (totalUnresolvable > 0) summaryParts.push(`${totalUnresolvable} reference-unresolvable`);
11762
11813
  if (totalFailed > 0) summaryParts.push(`${totalFailed} failed`);
11763
11814
  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.`);
11815
+ 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.`);
11816
+ 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
11817
  }
11767
11818
 
11768
11819
  // src/cli/commands/drift/command.ts
@@ -11882,7 +11933,7 @@ async function driftCommand(stacks, options) {
11882
11933
  if (anyRefusedDeleted) {
11883
11934
  if (anyIncomplete) {
11884
11935
  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.`);
11936
+ 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
11937
  }
11887
11938
  if (!options.dryRun) throw deletedRefusalError(refusedDeleted, mode);
11888
11939
  return;
@@ -11917,7 +11968,7 @@ function refuseDeletedForRemediation(reports, mode, logger) {
11917
11968
  if (outcome.kind !== "deleted") continue;
11918
11969
  if (outcome.nestedStackRecordMissing === true) {
11919
11970
  refused.recordMissing += 1;
11920
- logger.warn(safeMsg` ! ${reportHeading(report)} ${reportResource(outcome)}: NOT ` + (mode === "revert" ? "reverted" : "accepted") + safeMsg` — ${nestedRecordMissingClause(report, outcome)} ${NESTED_RECORD_MISSING_REMEDY}`);
11971
+ logger.warn(safeMsg` ! ${reportHeading(report)} ${reportResource(outcome)}: NOT ` + (mode === "revert" ? "reverted" : "accepted") + safeMsg` — ${nestedRecordMissingClause(report, outcome)} ${nestedRecordMissingRemedy()}`);
11921
11972
  continue;
11922
11973
  }
11923
11974
  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 +11981,7 @@ function deletedRefusalError({ deleted, recordMissing }, mode) {
11930
11981
  const parts = [...deleted > 0 ? [`${deleted} resource(s) deleted outside cdkd`] : [], ...recordMissing > 0 ? [`${recordMissing} nested stack(s) whose state record is gone`] : []];
11931
11982
  return new PartialFailureError(`${parts.join(" and ")} were not ${verb}; each is named above.`);
11932
11983
  }
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.";
11984
+ 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
11985
  function nestedRecordMissingClause(report, outcome) {
11935
11986
  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
11987
  }
@@ -11972,7 +12023,7 @@ function resolveTargetRefs(stacks, stateRefs, options) {
11972
12023
  }
11973
12024
  if (stacks.length === 0) {
11974
12025
  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.");
12026
+ if (candidates.length === 0) throw new Error(`No stacks found in state bucket. Run ${proseQuoted(cdkdRemedy("cdkd deploy"), "`")} first, or pass --all explicitly.`);
11976
12027
  const roots = candidates.filter((r) => !candidates.some((a) => a !== r && isNestedDescendantOf(r, a)));
11977
12028
  if (roots.length === 1) return withNestedDescendants([roots[0]], candidates);
11978
12029
  const listing = roots.map((r) => `${r.stackName}${r.region ? ` (${r.region})` : ""}`).join(", ");
@@ -11981,7 +12032,7 @@ function resolveTargetRefs(stacks, stateRefs, options) {
11981
12032
  const out = [];
11982
12033
  for (const stackName of stacks) {
11983
12034
  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.`);
12035
+ if (matches.length === 0) throw new Error(`No state found for stack '${stackName}'. Run ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
11985
12036
  if (options.stackRegion) {
11986
12037
  const ref = matches.find((r) => r.region === options.stackRegion);
11987
12038
  if (!ref) {
@@ -12040,7 +12091,7 @@ function createIamPrincipalUniqueIdResolver(awsClients) {
12040
12091
 
12041
12092
  // src/cli/commands/drift.ts
12042
12093
  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));
12094
+ 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
12095
  [...commonOptions, ...stateOptions].forEach((opt) => cmd.addOption(opt));
12045
12096
  cmd.addOption(deprecatedRegionOption);
12046
12097
  return cmd;
@@ -12053,7 +12104,7 @@ const NOECHO_PRINTING_BIND_CAP_MS = 1e4;
12053
12104
  async function purgeStateHistoryIfOptedIn(ctx, stackName, region) {
12054
12105
  if (ctx.purgeStateHistory === true) await ctx.stateBackend.purgeDeletedStateHistory(stackName, region);
12055
12106
  }
12056
- const NESTED_STACK_TYPE = "AWS::CloudFormation::Stack";
12107
+ const NESTED_STACK_TYPE$1 = "AWS::CloudFormation::Stack";
12057
12108
  function maskedSnapshotLogger(logger, mask) {
12058
12109
  return {
12059
12110
  info: (message) => logger.info(mask(message)),
@@ -12426,7 +12477,7 @@ function resolvablePrincipalLists(resource) {
12426
12477
  async function recheckUnderLock({ ctx, stackName, state, regionForState, refusalRecovery, lock, restoreBaseRegionAndClients, needsStrongRefCheck }) {
12427
12478
  try {
12428
12479
  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");
12480
+ 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
12481
  if (current.state.terminationProtection === true && ctx.removeProtection !== true) throw new StackTerminationProtectionError(stackName, void 0, {
12431
12482
  args: accountArgs(refusalRecovery),
12432
12483
  clause: withheldAccountClause(refusalRecovery, "the command below prints")
@@ -12475,7 +12526,7 @@ function makeSummaryHints(regionForState, refusalRecovery) {
12475
12526
  ...accountArgs(refusalRecovery)
12476
12527
  ]);
12477
12528
  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()));
12529
+ 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
12530
  return {
12480
12531
  hintFor,
12481
12532
  hintHolesClause
@@ -12587,7 +12638,7 @@ function printDestroySummary({ result, ctx, stackName, logger, preserveState, gu
12587
12638
  if (!preserveState) {
12588
12639
  const leftInAws = result.journaledOrphanSkips > 0;
12589
12640
  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.`);
12641
+ } 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
12642
  else if (result.errorCount === 0) {
12592
12643
  const targets = [...skippedStateTargets];
12593
12644
  const showHint = hintFor("cdkd state show", targets, "Inspect it with");
@@ -12601,7 +12652,7 @@ function printDestroySummary({ result, ctx, stackName, logger, preserveState, gu
12601
12652
  const droppableSkipped = journaledOrphanFailures > 0 ? skippedTargets.filter((t) => t !== stackName) : skippedTargets;
12602
12653
  const skippedCommands = hintFor("cdkd state show", skippedTargets, "Inspect it with") + hintFor("cdkd state orphan", droppableSkipped, "Drop the record with");
12603
12654
  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));
12655
+ 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
12656
  }
12606
12657
  }
12607
12658
 
@@ -13152,7 +13203,7 @@ async function destroyStackUnderLock({ stackName, state, ctx, logger, result, re
13152
13203
  if (result.interrupted) logger.warn(`Destroy interrupted — ${Object.keys(remainingResources).length} resource(s) not deleted. State preserved.`);
13153
13204
  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
13205
  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.");
13206
+ 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
13207
  }
13157
13208
  printDestroySummary({
13158
13209
  result,
@@ -13385,7 +13436,10 @@ function skippedDestroyMessage(totalSkipped, totalOrphanSkips, rerunCommand) {
13385
13436
  const recordSkips = totalSkipped - totalOrphanSkips;
13386
13437
  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
13438
  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}` : "");
13439
+ 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" }, {
13440
+ flag: "--stack-region",
13441
+ hole: "region"
13442
+ }]).command}.` + (totalOrphanSkips > 0 ? ` Separately, ${orphanSentence}` : "");
13389
13443
  }
13390
13444
 
13391
13445
  // src/cli/commands/destroy/helpers.ts
@@ -13464,7 +13518,7 @@ async function selectDestroyTargets(stackArgs, options, stateBackend, logger) {
13464
13518
  synthesized = true;
13465
13519
  } catch (error) {
13466
13520
  if (error instanceof StageLoadError) {
13467
- const named = new StageLoadError(`${error.message} To destroy a deployed stack without the app: cdkd state destroy ${commandHole("stack")}.`);
13521
+ const named = new StageLoadError(`${error.message} To destroy a deployed stack without the app: ${pasteableCommand("cdkd state destroy", [{ hole: "stack" }]).command}.`);
13468
13522
  if (typeof error.stack === "string") {
13469
13523
  const headerLines = `${error.name}: ${error.message}`.split("\n").length;
13470
13524
  const frames = error.stack.split("\n").slice(headerLines).join("\n");
@@ -13480,8 +13534,7 @@ async function selectDestroyTargets(stackArgs, options, stateBackend, logger) {
13480
13534
  if (appStacks.length === 0 && (options.all || wildcardPatterns.length > 0)) {
13481
13535
  const selector = options.all ? "--all" : wildcardPatterns.map((p) => displaySafe(p)).join(", ");
13482
13536
  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);
13537
+ 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
13538
  }
13486
13539
  if (options.all && appStacks.length > 0) {
13487
13540
  const app = partitionTopLevel(appStacks);
@@ -13655,6 +13708,81 @@ async function orderDestroyTargets(targets, appStacks, synthScanStacks, regionFo
13655
13708
  };
13656
13709
  }
13657
13710
 
13711
+ // src/cli/commands/destroy-runner/emulator-custom-resources.ts
13712
+ const NAMED_MAX = 5;
13713
+ const MAX_NESTED_DEPTH = 32;
13714
+ const NESTED_STACK_TYPE = "AWS::CloudFormation::Stack";
13715
+ const LAMBDA_FUNCTION_ARN = /^arn:aws[a-z-]*:lambda:[^:]+:(\d{12}):function:[^:]+(?::[^:]+)?$/;
13716
+ async function refuseCustomResourcesWithoutApp(targets, deps) {
13717
+ const command = localCustomResourceCommand();
13718
+ if (command !== "destroy" && command !== "state destroy") return;
13719
+ if (!customResourcesRunWithoutApp() || targets.length === 0) return;
13720
+ const account = await deps.callerAccount().catch(() => void 0);
13721
+ const found = [];
13722
+ for (const target of targets) {
13723
+ const record = await deps.getState(target.stackName, target.region);
13724
+ if (record === null) continue;
13725
+ const root = target.stackName.split("~")[0] || target.stackName;
13726
+ const customResources = [];
13727
+ await collect(target.stackName, target.region, record.state, root === target.stackName ? void 0 : target.stackName, 0, account, deps, customResources);
13728
+ if (customResources.length === 0) continue;
13729
+ const existing = found.find((f) => f.stackName === root);
13730
+ if (existing === void 0) found.push({
13731
+ stackName: root,
13732
+ customResources
13733
+ });
13734
+ else existing.customResources.push(...customResources);
13735
+ }
13736
+ if (found.length === 0) return;
13737
+ throw new CdkdError(customResourcesWithoutAppMessage(found), "EMULATOR_CR_NO_APP");
13738
+ }
13739
+ function refuseDestroyTargetsWithoutApp(targets, stateBackend, clients) {
13740
+ return refuseCustomResourcesWithoutApp(targets, {
13741
+ getState: (stackName, region) => stateBackend.getState(stackName, region),
13742
+ callerAccount: () => callerAccountOf(clients)
13743
+ });
13744
+ }
13745
+ async function callerAccountOf(clients) {
13746
+ try {
13747
+ const { GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
13748
+ return (await clients.sts.send(new GetCallerIdentityCommand({}))).Account;
13749
+ } catch {
13750
+ return;
13751
+ }
13752
+ }
13753
+ function runsInLocalRuntime(serviceToken, account) {
13754
+ if (typeof serviceToken !== "string") return false;
13755
+ const match = LAMBDA_FUNCTION_ARN.exec(serviceToken);
13756
+ return match !== null && (account === void 0 || match[1] === account);
13757
+ }
13758
+ async function collect(stackName, region, state, nestedStack, depth, account, deps, out) {
13759
+ const label = (logicalId) => plainOrDescribed(logicalId, "logical id") + (nestedStack === void 0 ? "" : ` in nested stack ${plainOrDescribed(nestedStack, "stack name")}`);
13760
+ const rows = state.resources !== null && typeof state.resources === "object" ? state.resources : {};
13761
+ for (const [logicalId, row] of Object.entries(rows)) {
13762
+ if (row === null || typeof row !== "object") continue;
13763
+ if (isCustomResourceType$1(row.resourceType) && runsInLocalRuntime(row.properties?.["ServiceToken"], account)) out.push(label(logicalId));
13764
+ else if (row.resourceType === NESTED_STACK_TYPE && depth < MAX_NESTED_DEPTH) {
13765
+ const childName = `${stackName}~${logicalId}`;
13766
+ const child = await deps.getState(childName, region);
13767
+ if (child !== null) await collect(childName, region, child.state, childName, depth + 1, account, deps, out);
13768
+ }
13769
+ }
13770
+ for (const entry of supersededResourcesOf(state)) if (isCustomResourceType$1(entry.state.resourceType) && runsInLocalRuntime(entry.state.properties?.["ServiceToken"], account)) out.push(label(entry.logicalId));
13771
+ }
13772
+ function customResourcesWithoutAppMessage(found) {
13773
+ const stacks = found.map(({ stackName, customResources }) => {
13774
+ const named = customResources.slice(0, NAMED_MAX);
13775
+ const more = customResources.length - named.length;
13776
+ return `${plainOrDescribed(stackName, "stack name")} (` + named.join(", ") + (more > 0 ? ` and ${more} more` : "") + ")";
13777
+ }).join("; ");
13778
+ const destroy = pasteableCommand("cdkd destroy", found.map(({ stackName }) => ({
13779
+ value: stackName,
13780
+ hole: "stack",
13781
+ opts: { plainIdent: true }
13782
+ })));
13783
+ 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}`;
13784
+ }
13785
+
13658
13786
  // src/cli/commands/destroy/command.ts
13659
13787
  async function destroyCommand(stackArgs, options) {
13660
13788
  const providerClasses = await loadProviderClasses();
@@ -13768,7 +13896,7 @@ async function destroyCommand(stackArgs, options) {
13768
13896
  totalErrors++;
13769
13897
  } else if (appStacks.length > 0 && !notInApp.includes(pattern)) notInApp.push(pattern);
13770
13898
  }
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.`);
13899
+ 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
13900
  if (notInApp.length > 0) logger.warn(renderNotInAppWarning(notInApp));
13773
13901
  }
13774
13902
  logger.info("No matching stacks found in state");
@@ -13811,11 +13939,19 @@ async function destroyCommand(stackArgs, options) {
13811
13939
  if (strict !== void 0) return refs.some((r) => r.region === strict) ? strict : void 0;
13812
13940
  return plannedDestroyRegion(refs, target.synth?.region, fallbackRegionByName.get(target.stackName) ?? region);
13813
13941
  };
13942
+ const customResourceTargets = [];
13814
13943
  for (const target of targets) {
13815
13944
  if (target.synth?.terminationProtection === true && !(options.removeProtection === true && target.dependsOnSelected === void 0)) continue;
13816
13945
  const planned = plannedRegionFor(target);
13817
- if (planned !== void 0) crossPrefixCheck.cache.full(target.stackName, planned, "prestart");
13946
+ if (planned !== void 0) {
13947
+ crossPrefixCheck.cache.full(target.stackName, planned, "prestart");
13948
+ customResourceTargets.push({
13949
+ stackName: target.stackName,
13950
+ region: planned
13951
+ });
13952
+ }
13818
13953
  }
13954
+ await refuseDestroyTargetsWithoutApp(customResourceTargets, stateBackend, awsClients);
13819
13955
  for (const [stackIndex, target] of targets.entries()) {
13820
13956
  const stackName = target.stackName;
13821
13957
  logger.info(`\nPreparing to destroy stack: ${describeTarget(target)}`);
@@ -14004,8 +14140,11 @@ async function destroyCommand(stackArgs, options) {
14004
14140
  break;
14005
14141
  }
14006
14142
  }
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.`);
14143
+ 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" }, {
14144
+ flag: "--stack-region",
14145
+ hole: "region"
14146
+ }]).command} removes the stack's state in that region (every resource's record) without deleting AWS resources.`);
14147
+ if (interrupted || interruptWatch.interrupted() && stoppedEarly) throw new PartialFailureError(`Destroy interrupted by Ctrl-C. State preserved — re-run ${proseQuoted(cdkdRemedy("cdkd destroy"))} to finish.`);
14009
14148
  if (totalSkipped > 0) throw new PartialFailureError(skippedDestroyMessage(totalSkipped, totalOrphanSkips, "cdkd destroy"));
14010
14149
  } finally {
14011
14150
  await Promise.allSettled(deferredTails);
@@ -14089,7 +14228,7 @@ async function stateMigrateCommand(options) {
14089
14228
  logger.info("Migrating state bucket:");
14090
14229
  logger.info(` source: ${legacyBucket} (resolved for --region ${sourceRegionLabel})`);
14091
14230
  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.)`);
14231
+ 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
14232
  const legacyRegion = await resolveBucketRegion(legacyBucket);
14094
14233
  logger.info(` source bucket actual region: ${legacyRegion}`);
14095
14234
  const legacyS3 = new S3Client({
@@ -14207,7 +14346,7 @@ async function assertNoActiveLocks(s3, bucket) {
14207
14346
  if (locks.length > 0) {
14208
14347
  const sample = locks.slice(0, 3).join(", ");
14209
14348
  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.`);
14349
+ 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
14350
  }
14212
14351
  }
14213
14352
  async function ensureDestinationBucket(bucketName, region, accountId, logger) {
@@ -14409,14 +14548,25 @@ function stackTreeToJson(roots) {
14409
14548
  }
14410
14549
 
14411
14550
  // 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";
14551
+ function stateReadFailedReason() {
14552
+ return `state record could not be read; run ${proseQuoted(stateShowCommand$1(), "`")} for the error`;
14553
+ }
14554
+ function lockReadFailedReason() {
14555
+ return `lock could not be read; run ${proseQuoted(stateShowCommand$1(), "`")} for the error`;
14556
+ }
14557
+ function stateShowCommand$1() {
14558
+ return cdkdRemedy("cdkd state show");
14559
+ }
14414
14560
  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
- };
14561
+ function resourcesMalformedReason() {
14562
+ return `resources is not a JSON object; run ${proseQuoted(cdkdRemedy("cdkd state show", "--json"), "`")} to see the record`;
14563
+ }
14564
+ function stateReadReasons() {
14565
+ return {
14566
+ "read-failed": stateReadFailedReason(),
14567
+ "resources-malformed": resourcesMalformedReason()
14568
+ };
14569
+ }
14420
14570
  function stateDestroyTargets(refs, stackRegion) {
14421
14571
  if (stackRegion) return refs.filter((r) => r.region === stackRegion || !r.region);
14422
14572
  return refs.length === 1 ? [...refs] : void 0;
@@ -14459,7 +14609,7 @@ function describedStackRef(ref) {
14459
14609
  return ref.region ? `${name} (${plainOrDescribed(ref.region, "region")})` : name;
14460
14610
  }
14461
14611
  function legacyRecordSubject(stackName) {
14462
- return isPasteableIdent(stackName) ? `Stack ${stackName}` : `A stack whose name is not a plain identifier (see 'cdkd state list --long')`;
14612
+ return isPasteableIdent(stackName) ? `Stack ${stackName}` : `A stack whose name is not a plain identifier (see ${proseQuoted(cdkdRemedy("cdkd state list", "--long"))})`;
14463
14613
  }
14464
14614
  function legacyRecordRefusal(stackName) {
14465
14615
  const migrate = pasteableCommand("cdkd deploy", [{
@@ -14472,7 +14622,9 @@ function legacyRecordRefusal(stackName) {
14472
14622
  }]);
14473
14623
  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
14624
  }
14475
- const STATE_LIST_POINTER = `'cdkd state list --long' shows the records as stored.`;
14625
+ function stateListPointer() {
14626
+ return `${proseQuoted(cdkdRemedy("cdkd state list", "--long"))} shows the records as stored.`;
14627
+ }
14476
14628
  function refIsDescribed(ref) {
14477
14629
  return !isPasteableIdent(ref.stackName) || (ref.region ? !isPasteableIdent(ref.region) : false);
14478
14630
  }
@@ -14492,14 +14644,14 @@ function noStateInRegionError(stackName, requestedRegion, matches, opts) {
14492
14644
  requestedRegion,
14493
14645
  ...matches.flatMap((r) => r.region ? [r.region] : [])
14494
14646
  ].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}` : ""));
14647
+ return /* @__PURE__ */ new Error(`No state found for ${subject} in region ${requested}. Available regions: ${candidates.join(", ")}.` + (anyDescribed ? ` ${stateListPointer()}` : ""));
14496
14648
  }
14497
14649
  function multipleRegionsError(stackName, matches, remedy) {
14498
14650
  return /* @__PURE__ */ new Error(`Stack ${displayStackName(stackName)} has state in multiple regions: ${matches.map((r) => listedRegion(r.region)).join(", ")}.\n${remedy}`);
14499
14651
  }
14500
14652
  function resolveSingleRegion(stackName, refs, requestedRegion) {
14501
14653
  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.`);
14654
+ 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
14655
  if (requestedRegion) {
14504
14656
  const ref = matches.find((r) => r.region === requestedRegion);
14505
14657
  if (!ref) throw noStateInRegionError(stackName, requestedRegion, matches);
@@ -14644,9 +14796,9 @@ async function stateListCommand(options) {
14644
14796
  resourceCount,
14645
14797
  lastModified: state ? isoTimestampOrNull(state.lastModified) : null,
14646
14798
  locked: lockRead.ok ? lockRead.value : null,
14647
- stateReadError: stateReadErrorKind === null ? null : STATE_READ_REASONS[stateReadErrorKind],
14799
+ stateReadError: stateReadErrorKind === null ? null : stateReadReasons()[stateReadErrorKind],
14648
14800
  stateReadErrorKind,
14649
- lockReadError: lockRead.ok ? null : ref.region ? LOCK_READ_FAILED_REASON : LEGACY_LOCK_READ_FAILED_REASON
14801
+ lockReadError: lockRead.ok ? null : ref.region ? lockReadFailedReason() : LEGACY_LOCK_READ_FAILED_REASON
14650
14802
  };
14651
14803
  }));
14652
14804
  const degraded = details.filter((d) => d.stateReadError !== null || d.lockReadError !== null);
@@ -14798,7 +14950,7 @@ async function printStackResources(stackName, options, setup) {
14798
14950
  const ref = resolveSingleRegion(stackName, refs, options.stackRegion);
14799
14951
  if (!ref.region) throw legacyRecordRefusal(stackName);
14800
14952
  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.`);
14953
+ 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
14954
  if (repairMalformedResourcesForReadOnly(stateResult.state)) logger.warn(malformedResourcesWarning(stackName, ref.region, renderRecovery(options, setup)));
14803
14955
  if (options.long || options.json) repairRenderedContainers(stateResult.state, RESOURCES_RENDERED_CONTAINERS, stackName, ref.region, logger, renderRecovery(options, setup));
14804
14956
  const resources = withSecretPhysicalIdsMaskedInState(stateResult.state).resources;
@@ -14983,7 +15135,7 @@ function orphanCommandFor(stackName, region, recovery) {
14983
15135
  },
14984
15136
  ...account
14985
15137
  ]).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
15138
+ 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
15139
  };
14988
15140
  }
14989
15141
  function orphanWithheldPart(what, raw, built, hole) {
@@ -15179,7 +15331,7 @@ async function pickStackRegion$1(stateBackend, stackName, synthRegion, flag) {
15179
15331
  if (refs.length === 0) {
15180
15332
  if (flag) return flag;
15181
15333
  if (synthRegion) return synthRegion;
15182
- throw new Error(`No state found for stack ${quotedOrNotShown(stackName)}. Run 'cdkd state list' to see available stacks.`);
15334
+ throw new Error(`No state found for stack ${quotedOrNotShown(stackName)}. Run ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
15183
15335
  }
15184
15336
  if (flag) {
15185
15337
  if (!refs.find((r) => r.region === flag)) {
@@ -15228,7 +15380,7 @@ function refuseTransientContextIfUnsafe(options) {
15228
15380
  if (overrides.length === 0) return;
15229
15381
  if (!options.acceptTransientContext) {
15230
15382
  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.`);
15383
+ 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
15384
  }
15233
15385
  const logger = getLogger();
15234
15386
  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 +15422,7 @@ function recordedRuleIdIdentifier() {
15270
15422
  if (typeof recorded === "string" && isUsableIdentifier(recorded)) return recorded.trim();
15271
15423
  if (isUsableIdentifier(physicalId)) return physicalId.trim();
15272
15424
  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.`);
15425
+ 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
15426
  }
15275
15427
  };
15276
15428
  }
@@ -15356,19 +15508,19 @@ function cachedSecurityGroupRules(groupId, { ec2Client, securityGroupRuleCache }
15356
15508
  securityGroupRuleCache.set(groupId, pending);
15357
15509
  return pending;
15358
15510
  }
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.";
15511
+ 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
15512
  function sgIngressExportEscapeHatch(logicalId) {
15361
15513
  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
15514
  }
15363
15515
  async function backfillSecurityGroupIngressRuleId({ logicalId, physicalId }, deps) {
15364
15516
  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)}`);
15517
+ 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
15518
  const portRange = tuple.fromPort === tuple.toPort ? `${tuple.fromPort}` : `${tuple.fromPort}-${tuple.toPort}`;
15367
15519
  const tupleNote = `protocol ${showRecordValue(tuple.ipProtocol)}, ports ${portRange} on security group ${showRecordValue(tuple.groupId)}`;
15368
15520
  const lookup = await cachedSecurityGroupRules(tuple.groupId, deps);
15369
15521
  if (!lookup.ok) {
15370
15522
  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.`;
15523
+ 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
15524
  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
15525
  }
15374
15526
  const matched = lookup.rules.filter((rule) => ruleMatchesIngressTuple(rule, tuple));
@@ -15376,12 +15528,12 @@ async function backfillSecurityGroupIngressRuleId({ logicalId, physicalId }, dep
15376
15528
  if (ids.length < matched.length) {
15377
15529
  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
15530
  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}` : "";
15531
+ 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
15532
  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
15533
  }
15382
15534
  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)}`);
15535
+ 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)}`);
15536
+ 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
15537
  }
15386
15538
 
15387
15539
  // src/cli/commands/export/composite-physical-id.ts
@@ -15429,18 +15581,15 @@ async function resolveIdentifierValue(entry, ctx, deps) {
15429
15581
  }
15430
15582
  }
15431
15583
  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.`;
15584
+ 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
15585
  }
15434
15586
  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`;
15587
+ const pair = `${isPasteableIdent(logicalId) ? shellQuote(logicalId) : commandHole("logicalId")}=${commandHole("physicalId")}`;
15588
+ return pasteableCommand("cdkd import", [
15589
+ { hole: "stack" },
15590
+ { literal: `--resource ${pair}` },
15591
+ { literal: "--force" }
15592
+ ]).command;
15444
15593
  }
15445
15594
  function deployRepairCommand(stackName) {
15446
15595
  return pasteableCommand("cdkd deploy", [repairStackArg(stackName)]).command;
@@ -15470,7 +15619,7 @@ function recordedArnIdentifier(options) {
15470
15619
  if (isUsableIdentifier(physicalId)) return physicalId.trim();
15471
15620
  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
15621
  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.`);
15622
+ 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
15623
  }
15475
15624
  };
15476
15625
  }
@@ -15531,7 +15680,7 @@ function resolveRouteDestination(segment, properties) {
15531
15680
  if (declaredValues.some((value) => (canonicalizeIpv4Cidr(value) ?? value) === identifier)) return identifier;
15532
15681
  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
15682
  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.`));
15683
+ 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
15684
  return identifier;
15536
15685
  }
15537
15686
  const ROUTE_PREFIX_LIST_ID_PATTERN = /^pl-[0-9a-f]+$/;
@@ -16476,7 +16625,7 @@ function refusalReason(current) {
16476
16625
  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
16626
  }
16478
16627
  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'.`;
16628
+ 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
16629
  }
16481
16630
  function unrepresentableOverlayFields(resource, overlay) {
16482
16631
  if (!resource || typeof resource !== "object" || Array.isArray(resource)) return [];
@@ -16674,7 +16823,12 @@ async function buildImportPlan(state, template, cfnClient, parentStackName, opti
16674
16823
  blocked.push({
16675
16824
  logicalId,
16676
16825
  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.`
16826
+ 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", [
16827
+ { hole: "stack" },
16828
+ { literal: "--resource" },
16829
+ { literal: `${commandHole("logicalId")}=${commandHole("physicalId")}` },
16830
+ { literal: "--force" }
16831
+ ]).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
16832
  });
16679
16833
  continue;
16680
16834
  }
@@ -16839,12 +16993,12 @@ function sharedImportIdentifierReason(others) {
16839
16993
  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
16994
  }
16841
16995
  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.";
16996
+ 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
16997
  const manualIds = new Set(blocked.filter((b) => b.manual).map((b) => b.logicalId));
16844
16998
  const genericIds = new Set(blocked.filter((b) => b.repair === void 0 && !b.manual && !manualIds.has(b.logicalId)).map((b) => b.logicalId));
16845
16999
  const hasRepair = blocked.some((b) => b.repair !== void 0 && !genericIds.has(b.logicalId) && !manualIds.has(b.logicalId));
16846
17000
  const hasManual = manualIds.size > 0;
16847
- if (genericIds.size === 0 && !hasManual) return "Run each row's 'Repair with:' command, then re-run cdkd export.";
17001
+ if (genericIds.size === 0 && !hasManual) return `Run each row's 'Repair with:' command, then re-run ${cdkdRemedy("cdkd export")}.`;
16848
17002
  if (!hasRepair && !hasManual) return `Either ${generic}`;
16849
17003
  const steps = [];
16850
17004
  if (hasRepair) steps.push("run each 'Repair with:' command given");
@@ -16968,7 +17122,7 @@ function reportDriftBaselineGaps(state, logger, loaded, template, recovery) {
16968
17122
  ...account
16969
17123
  ]).command;
16970
17124
  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.`);
17125
+ 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
17126
  for (const logicalId of unreadable.slice(0, NAMED_BASELINE_IDS)) logger.warn(` ${displayLogicalId(logicalId)}`);
16973
17127
  if (unreadable.length > NAMED_BASELINE_IDS) logger.warn(` ... and ${unreadable.length - NAMED_BASELINE_IDS} more`);
16974
17128
  logger.warn(safeMsg`Inspect it with: ${inspectCommand}`);
@@ -16982,7 +17136,7 @@ function reportDriftBaselineGaps(state, logger, loaded, template, recovery) {
16982
17136
  const refused = missing.filter(([, r]) => r.observedBaselineRefused === true);
16983
17137
  const refreshable = missing.filter(([, r]) => r.observedBaselineRefused !== true);
16984
17138
  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.`));
17139
+ 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
17140
  for (const [logicalId] of refreshable.slice(0, NAMED_BASELINE_IDS)) logger.warn(` ${displayLogicalId(logicalId)}`);
16987
17141
  if (refreshable.length > NAMED_BASELINE_IDS) logger.warn(` ... and ${refreshable.length - NAMED_BASELINE_IDS} more`);
16988
17142
  }
@@ -17730,7 +17884,7 @@ async function exportCommand(stackArg, options) {
17730
17884
  refuseMalformedResourcePropertiesForExport(state, resolvedStackName, recordRegion, lockRecovery);
17731
17885
  const exportJournal = await stateBackend.loadRollbackJournal(resolvedStackName, targetRegion);
17732
17886
  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", [{
17887
+ 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
17888
  value: resolvedStackName,
17735
17889
  hole: "stack"
17736
17890
  }]).command}`);
@@ -17967,7 +18121,7 @@ async function printStackShow(stackName, options, setup) {
17967
18121
  const ref = resolveSingleRegion(stackName, refs, options.stackRegion);
17968
18122
  if (!ref.region) throw legacyRecordRefusal(stackName);
17969
18123
  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.`);
18124
+ 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
18125
  if (options.showNested) {
17972
18126
  const treeWithLocks = await loadLocksForTree(await buildCdkdStateStackTree(stackName, ref.region, setup.stateBackend, stateResult.state, renderRecovery(options, setup)), setup.lockManager, lockInfo);
17973
18127
  if (options.json) {
@@ -18122,17 +18276,12 @@ function isResolvableOrphanRecord(entry) {
18122
18276
  const physicalId = entry.physicalId;
18123
18277
  return typeof physicalId === "string" && physicalId !== "";
18124
18278
  }
18125
- const SECRET_VALUED_ATTRIBUTES = /* @__PURE__ */ new Map([
18126
- ["AWS::AppSync::ApiKey", ["ApiKey"]],
18127
- ["AWS::EC2::IpamExternalResourceVerificationToken", ["TokenValue"]],
18128
- ["AWS::IVS::StreamKey", ["Value"]]
18129
- ]);
18130
18279
  function carriesSensitiveNamedLeaf(value) {
18131
18280
  if (value === null || typeof value !== "object") return false;
18132
18281
  return Object.entries(value).some(([key, leaf]) => isSensitiveAttributeName(key) || carriesSensitiveNamedLeaf(leaf));
18133
18282
  }
18134
18283
  function servableRecordedAttribute(orphan, attribute) {
18135
- if (isAlwaysLiveAttribute(orphan.resourceType, attribute) || isSensitiveAttributeName(attribute) || isCustomResourceType$1(orphan.resourceType) || SECRET_VALUED_ATTRIBUTES.get(orphan.resourceType)?.includes(attribute)) return { served: false };
18284
+ if (isAlwaysLiveAttribute(orphan.resourceType, attribute) || isSensitiveAttributeName(attribute) || isCustomResourceType$1(orphan.resourceType) || isSecretValuedAttribute(orphan.resourceType, attribute)) return { served: false };
18136
18285
  const bag = orphan.attributes;
18137
18286
  if (bag === void 0 || !isReadableBag(bag)) return { served: false };
18138
18287
  const attributes = bag;
@@ -18159,7 +18308,7 @@ function servableRecordedAttribute(orphan, attribute) {
18159
18308
  function unsplicableCachedAttribute(resourceType, attribute, cached) {
18160
18309
  if (isSensitiveAttributeName(attribute)) return "a credential-named attribute";
18161
18310
  if (isCustomResourceType$1(resourceType)) return "a custom resource's attribute";
18162
- if (SECRET_VALUED_ATTRIBUTES.get(resourceType)?.includes(attribute)) return "a secret-valued attribute";
18311
+ if (isSecretValuedAttribute(resourceType, attribute)) return "a secret-valued attribute";
18163
18312
  if (carriesSecretMask(cached)) return `the redaction mask ('${"***"}')`;
18164
18313
  if (carriesDynamicReference(cached)) return "an unresolved dynamic reference";
18165
18314
  if (carriesSensitiveNamedLeaf(cached)) return "a value with a credential-named field";
@@ -18188,6 +18337,11 @@ var AttributeFetcher = class {
18188
18337
  ok: false,
18189
18338
  reason: "state records no usable 'TableARN' for this S3 Tables table, the value CloudFormation's Ref returns, and the physical id is NOT that value"
18190
18339
  };
18340
+ const healedAttribute = lacksRecordedRefArn(o);
18341
+ if (healedAttribute !== void 0) return {
18342
+ ok: false,
18343
+ reason: `state records no usable '${healedAttribute}' for this resource, the value CloudFormation's Ref returns, and the physical id is NOT that value`
18344
+ };
18191
18345
  let maskedKey;
18192
18346
  const value = cfnRefValueFromPhysicalId(o.resourceType, o.physicalId, refStateLookupFromResource(o, (key) => {
18193
18347
  maskedKey = key;
@@ -18545,8 +18699,17 @@ async function orphanCommand(pathArgs, options) {
18545
18699
  roleArn: options.roleArn,
18546
18700
  region: options.region
18547
18701
  });
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}`);
18702
+ if (pathArgs.length === 0) throw new Error(`'cdkd orphan' requires at least one construct path, e.g. 'cdkd orphan MyStack/MyTable'.
18703
+ To remove a stack's state record (the previous behavior), use:
18704
+ ${pasteableCommand("cdkd state orphan", [{
18705
+ value: "MyStack",
18706
+ hole: "stack"
18707
+ }]).command}`);
18708
+ 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", [{
18709
+ value: p,
18710
+ hole: "stack",
18711
+ opts: { patternMatched: true }
18712
+ }]).command}`);
18550
18713
  const effectiveRegion = await resolveEffectiveRegion(options);
18551
18714
  exportInferredRegionForSdk(effectiveRegion);
18552
18715
  const region = effectiveRegion.region;
@@ -18680,7 +18843,7 @@ function resolveConstructPaths(paths, stacks) {
18680
18843
  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
18844
  }
18682
18845
  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.`);
18846
+ 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
18847
  const index = buildCdkPathIndex(candidate.template);
18685
18848
  const matches = resolveCdkPathToLogicalIds(p, index);
18686
18849
  if (matches.length === 0) {
@@ -18706,7 +18869,7 @@ async function pickStackRegion(stateBackend, stackName, synthRegion, flag) {
18706
18869
  region: synthRegion,
18707
18870
  recordRegion: synthRegion
18708
18871
  };
18709
- throw new Error(`No state found for stack ${displayStackName(stackName)}. Run 'cdkd state list' to see available stacks.`);
18872
+ throw new Error(`No state found for stack ${displayStackName(stackName)}. Run ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
18710
18873
  }
18711
18874
  if (flag) {
18712
18875
  if (!refs.find((r) => r.region === flag)) {
@@ -18782,7 +18945,7 @@ async function clearRetainedQuietly(backend, stackName, region, logger) {
18782
18945
  await backend.saveRetainedResources(stackName, region, []);
18783
18946
  return true;
18784
18947
  } 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.`);
18948
+ 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
18949
  return false;
18787
18950
  }
18788
18951
  }
@@ -18817,9 +18980,9 @@ async function clearRetainedWithoutRecord(backend, stackName, stackRegion, logge
18817
18980
  async function stateOrphanCommand(stackArgs, options) {
18818
18981
  const logger = getLogger();
18819
18982
  if (options.verbose) logger.setLevel("debug");
18820
- if (stackArgs.length === 0) throw new Error(`Stack name is required. Usage: cdkd state orphan ${commandHole("stacks...")}`);
18983
+ if (stackArgs.length === 0) throw new Error(`Stack name is required. Usage: ${pasteableCommand("cdkd state orphan", [{ hole: "stacks..." }]).command}`);
18821
18984
  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.`);
18985
+ 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
18986
  await stateOrphanResources(stackArgs[0], options.resource, options);
18824
18987
  return;
18825
18988
  }
@@ -18835,7 +18998,7 @@ async function stateOrphanCommand(stackArgs, options) {
18835
18998
  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
18999
  continue;
18837
19000
  }
18838
- logger.info(safeMsg`No state found for stack: ${plainOrDescribed(stackName, "stack name")}, skipping` + (isPasteableIdent(stackName) ? "" : safeMsg`. ${STATE_LIST_POINTER}`));
19001
+ logger.info(safeMsg`No state found for stack: ${plainOrDescribed(stackName, "stack name")}, skipping` + (isPasteableIdent(stackName) ? "" : safeMsg`. ${stateListPointer()}`));
18839
19002
  continue;
18840
19003
  }
18841
19004
  const targets = options.stackRegion !== void 0 ? stackRefs.filter((r) => r.region === options.stackRegion) : stackRefs;
@@ -18867,7 +19030,7 @@ async function stateOrphanCommand(stackArgs, options) {
18867
19030
  }
18868
19031
  }, ...accountArgs(bannerAccount)]);
18869
19032
  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`);
19033
+ 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
19034
  if (!await confirmStateOrphanRemoval(`Remove state for ${targetList} from s3://${setup.bucket}/${setup.prefix}/?`)) {
18872
19035
  logger.info(safeMsg`Cancelled removal of state for stack: ${plainOrDescribed(stackName, "stack name")}`);
18873
19036
  continue;
@@ -18886,7 +19049,7 @@ async function stateOrphanCommand(stackArgs, options) {
18886
19049
  await setup.lockManager.forceReleaseLock(stackName, void 0);
18887
19050
  await clearRetainedWithoutRecord(setup.stateBackend, stackName, void 0, logger);
18888
19051
  }
18889
- logger.info(safeMsg`✓ Removed state for stack: ${describedStackRef(target)}` + ((options.yes || options.force) && refIsDescribed(target) ? safeMsg`. ${STATE_LIST_POINTER}` : ""));
19052
+ logger.info(safeMsg`✓ Removed state for stack: ${describedStackRef(target)}` + ((options.yes || options.force) && refIsDescribed(target) ? safeMsg`. ${stateListPointer()}` : ""));
18890
19053
  }
18891
19054
  }
18892
19055
  } finally {
@@ -18922,7 +19085,7 @@ async function stateOrphanResources(stackName, requested, options) {
18922
19085
  }));
18923
19086
  try {
18924
19087
  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.`);
19088
+ 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
19089
  const { state, etag, migrationPending } = stateData;
18927
19090
  refuseMalformedState(state, stackName, region, recovery);
18928
19091
  refuseMalformedOutputs(state, stackName, region, recovery);
@@ -18954,7 +19117,7 @@ async function stateOrphanResources(stackName, requested, options) {
18954
19117
  ...accountArgs(recovery)
18955
19118
  ]);
18956
19119
  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}`);
19120
+ 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
19121
  }
18959
19122
  clients = new AwsClients({
18960
19123
  region,
@@ -18981,7 +19144,7 @@ async function stateOrphanResources(stackName, requested, options) {
18981
19144
  });
18982
19145
  const idList = logicalIds.map((id) => displayIdent(id)).join(", ");
18983
19146
  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`);
19147
+ 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
19148
  if (!await confirmStateOrphanRemoval(`Remove the record(s) of ${idList} from state for ${describedStackRef(ref)}?`, { resource: true })) {
18986
19149
  logger.info(safeMsg`Cancelled removal of resource record(s) for stack: ${plainOrDescribed(stackName, "stack name")}`);
18987
19150
  return;
@@ -19032,7 +19195,7 @@ async function protectedRootOf(stackName, state, region, backend) {
19032
19195
  }
19033
19196
  }
19034
19197
  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");
19198
+ 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
19199
  const providerClasses = await loadProviderClasses();
19037
19200
  const logger = getLogger();
19038
19201
  if (options.verbose) {
@@ -19041,7 +19204,7 @@ async function stateDestroyCommand(stackArgs, options) {
19041
19204
  }
19042
19205
  validateResourceTimeouts(options);
19043
19206
  setResolvedResourceTimeouts(options.resourceTimeout);
19044
- if (stackArgs.length === 0) throw new Error(`Stack name is required. Usage: cdkd state destroy ${commandHole("stacks...")}`);
19207
+ if (stackArgs.length === 0) throw new Error(`Stack name is required. Usage: ${pasteableCommand("cdkd state destroy", [{ hole: "stacks..." }]).command}`);
19045
19208
  const setup = await setupStateBackend(options);
19046
19209
  if (options.region) {
19047
19210
  process.env["AWS_REGION"] = setup.region;
@@ -19065,7 +19228,7 @@ async function stateDestroyCommand(stackArgs, options) {
19065
19228
  const stateRefs = await setup.stateBackend.listStacks();
19066
19229
  const knownStackNames = new Set(stateRefs.map((r) => r.stackName));
19067
19230
  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.`);
19231
+ 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
19232
  const stackNames = stackArgs;
19070
19233
  logger.info(safeMsg`Found ${stackNames.length} stack(s) to destroy: ${stackNames.map(listedStackName).join(", ")}`);
19071
19234
  let totalErrors = 0;
@@ -19081,10 +19244,19 @@ async function stateDestroyCommand(stackArgs, options) {
19081
19244
  });
19082
19245
  const crossPrefixCheck = { cache: new CrossPrefixGuard(setup.stateBackend) };
19083
19246
  if (stackNames.length > 1) deferRegistryTail = (released) => deferredTails.push(released);
19247
+ const customResourceTargets = [];
19084
19248
  for (const name of stackNames) {
19085
19249
  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");
19250
+ for (const ref of stateDestroyTargets(refs, options.stackRegion) ?? []) {
19251
+ const targetRegion = ref.region ?? await setup.regionFor(name);
19252
+ crossPrefixCheck.cache.full(name, targetRegion, "prestart");
19253
+ customResourceTargets.push({
19254
+ stackName: name,
19255
+ region: targetRegion
19256
+ });
19257
+ }
19087
19258
  }
19259
+ await refuseDestroyTargetsWithoutApp(customResourceTargets, setup.stateBackend, setup.awsClients);
19088
19260
  for (const [stackIndex, stackName] of stackNames.entries()) {
19089
19261
  const refs = stateRefs.filter((r) => r.stackName === stackName);
19090
19262
  let targets;
@@ -19213,8 +19385,11 @@ async function stateDestroyCommand(stackArgs, options) {
19213
19385
  break;
19214
19386
  }
19215
19387
  }
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.`);
19388
+ 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" }, {
19389
+ flag: "--stack-region",
19390
+ hole: "region"
19391
+ }]).command} removes the stack's state in that region (every resource's record) without deleting AWS resources.`);
19392
+ 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
19393
  if (totalSkipped > 0) throw new PartialFailureError(skippedDestroyMessage(totalSkipped, totalOrphanSkips, "cdkd state destroy"));
19219
19394
  } finally {
19220
19395
  await Promise.allSettled(deferredTails);
@@ -19401,7 +19576,7 @@ async function stateInfoCommand(options) {
19401
19576
  lines.push(`Source: ${formatBucketSource(resolved.source)}`);
19402
19577
  lines.push(`Schema version: ${schemaVersion}`);
19403
19578
  lines.push(`Stacks: ${stateFileKeys.length}`);
19404
- if (assetStorage.length === 0) lines.push("Asset storage: legacy (CDK bootstrap) — run cdkd bootstrap to opt in");
19579
+ if (assetStorage.length === 0) lines.push(`Asset storage: legacy (CDK bootstrap) — run ${cdkdRemedy("cdkd bootstrap")} to opt in`);
19405
19580
  else {
19406
19581
  lines.push(`Asset storage: cdkd-assets mode in ${assetStorage.length} region(s)`);
19407
19582
  for (const entry of assetStorage) lines.push(` ${displayIdent(entry.region)}: ${displayIdent(entry.assetBucket)} / ${displayIdent(entry.containerRepo, { maxCodePoints: STACK_REF_MAX_CODE_POINTS })}`);
@@ -19448,7 +19623,7 @@ function judgeAcceptRefused(record, logicalId, template, stack) {
19448
19623
  };
19449
19624
  if (record.observedBaselineRefused !== true) return {
19450
19625
  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.`
19626
+ 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
19627
  };
19453
19628
  const reason = record.observedBaselineRefusalReason;
19454
19629
  if (reason === "incomplete-resolution") return {
@@ -19737,7 +19912,7 @@ async function refreshObservedForStack(stackName, region, stateBackend, lockMana
19737
19912
  region
19738
19913
  });
19739
19914
  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.`);
19915
+ if (!result) throw new Error(safeMsg`No state found for stack ${ref}. ` + `Run ${proseQuoted(cdkdRemedy("cdkd state list"))} to see available stacks.`);
19741
19916
  const { state, etag, migrationPending } = result;
19742
19917
  refuseMalformedState(state, stackName, region, lockRecovery);
19743
19918
  refuseMalformedResourceEntries(state, stackName, region, lockRecovery);
@@ -19986,7 +20161,7 @@ async function stateRefreshObservedCommand(stackArgs, options) {
19986
20161
  }
19987
20162
  if (!options.yes && !options.dryRun && accept === void 0) {
19988
20163
  const targetList = targets.map(describedStackRef).join(", ");
19989
- if (targets.some(refIsDescribed)) logger.info(STATE_LIST_POINTER);
20164
+ if (targets.some(refIsDescribed)) logger.info(stateListPointer());
19990
20165
  if (!await confirmRefresh(`Refresh observedProperties for ${targets.length} stack(s) (${targetList})?`)) {
19991
20166
  logger.info("Aborted.");
19992
20167
  return;
@@ -20034,7 +20209,7 @@ async function stateRefreshObservedCommand(stackArgs, options) {
20034
20209
  }
20035
20210
  if (totalFailed > 0 || totalNotFound > 0) {
20036
20211
  const parts = [];
20037
- if (totalFailed > 0) parts.push(`${totalFailed} per-resource readback failure(s); re-run 'cdkd state refresh-observed' to retry them.`);
20212
+ if (totalFailed > 0) parts.push(`${totalFailed} per-resource readback failure(s); re-run ${proseQuoted(cdkdRemedy("cdkd state refresh-observed"))} to retry them.`);
20038
20213
  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
20214
  throw new PartialFailureError(`Refresh completed with ${parts.join(" ")} Affected resources keep their previous observedProperties (or no observedProperties at all).`);
20040
20215
  }
@@ -20173,7 +20348,7 @@ const VIEW_ITEMS = [
20173
20348
  }
20174
20349
  ];
20175
20350
  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");
20351
+ 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
20352
  }
20178
20353
  async function runStateBrowse(deps) {
20179
20354
  if (!isInteractiveTerminal(deps.streams)) throw nonInteractiveBrowseRefusal();
@@ -20436,6 +20611,24 @@ function rerunRollback(stackName) {
20436
20611
  }]);
20437
20612
  return withheldTargetClause(rerun, "stack", "cdkd rollback", "This stack's name") + `\nRe-run with: ${rerun.command}`;
20438
20613
  }
20614
+ function failedRollbackTail(stackName, region, failedOrphanIds) {
20615
+ const emulatorFailures = customResourcesFailedWithoutApp();
20616
+ const drop = dropFailedHint(stackName, region, failedOrphanIds);
20617
+ if (emulatorFailures.length === 0) return " — re-run the rollback to retry." + drop + rerunRollback(stackName);
20618
+ const forward = deployForwardForEmulatorCustomResources(stackName, emulatorFailures);
20619
+ return "." + forward.prose + drop + forward.line;
20620
+ }
20621
+ function deployForwardForEmulatorCustomResources(stackName, logicalIds) {
20622
+ const deploy = pasteableCommand("cdkd deploy", [{
20623
+ value: stackName,
20624
+ hole: "stack",
20625
+ opts: { plainIdent: true }
20626
+ }]);
20627
+ return {
20628
+ 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"),
20629
+ line: `\nDeploy forward with: ${deploy.command}`
20630
+ };
20631
+ }
20439
20632
  function backendErrorText(error, stackName, region) {
20440
20633
  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
20634
  return displaySafe(describeAwsFailure(error).detail);
@@ -20446,8 +20639,12 @@ function stackRegionShown(stackName, region) {
20446
20639
  function stackRegionIsPlain(stackName, region) {
20447
20640
  return isPasteableIdent(stackName) && isPasteableIdent(region);
20448
20641
  }
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'.)";
20642
+ function nestedNameDescribedNote() {
20643
+ 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"))}.)`;
20644
+ }
20645
+ function stackRegionDescribedNote() {
20646
+ 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"))}.)`;
20647
+ }
20451
20648
  function snapshotNote(resourceType, effectiveProvisionedBy, skipFinalSnapshot) {
20452
20649
  if (skipFinalSnapshot) return "DeletionPolicy Snapshot — NO final snapshot (--skip-final-snapshot)";
20453
20650
  if (refusesFinalSnapshot(resourceType, effectiveProvisionedBy)) {
@@ -20601,7 +20798,7 @@ async function printRollbackPlanSegments(ctx) {
20601
20798
  async function previewNestedChildRevert(backend, childStackName, region, runId, skipFinalSnapshot) {
20602
20799
  const plain = isPasteableIdent(childStackName);
20603
20800
  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}`];
20801
+ const withPointer = (lines) => plain ? lines : [...lines, ` ${nestedNameDescribedNote()}`];
20605
20802
  if (runId === void 0) return withPointer([` (${shown}: this segment carries no deploy run id — its revert will FAIL and the segment is kept)`]);
20606
20803
  try {
20607
20804
  const [childState, journal] = await Promise.all([backend.getState(childStackName, region), backend.loadRollbackJournal(childStackName, region)]);
@@ -20712,7 +20909,7 @@ async function runRollbackReplay(ctx) {
20712
20909
  ...journal,
20713
20910
  segments: journal.segments.filter((s) => s.reason !== NESTED_PENDING_PARENT_REASON)
20714
20911
  };
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.`);
20912
+ 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
20913
  applyCrossPrefixScan(await crossPrefixScan, {
20717
20914
  stackName,
20718
20915
  region,
@@ -20758,7 +20955,7 @@ async function runRollbackReplay(ctx) {
20758
20955
  const createTokenLedger = ledgerForStack(setup.stateBackend, stackName, region);
20759
20956
  const inSegmentScope = (segment, fn) => withSkipPrefix(segment.skipPrefix ?? legacySkipPrefix(), () => withStackScope(nameScopeOf(stackName, stackInstanceId, stateData?.state), () => withCreateTokenLedger(createTokenLedger, fn)));
20760
20957
  logger.info(`\nRollback plan for ${stackRegionShown(stackName, region)}:`);
20761
- if (!stackRegionIsPlain(stackName, region)) logger.info(STACK_REGION_DESCRIBED_NOTE);
20958
+ if (!stackRegionIsPlain(stackName, region)) logger.info(stackRegionDescribedNote());
20762
20959
  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
20960
  const planStateView = { ...stateResources };
20764
20961
  await printRollbackPlanSegments({
@@ -20963,7 +21160,7 @@ async function runRollbackReplay(ctx) {
20963
21160
  }
20964
21161
  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
21162
  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));
21163
+ if (totalFailures > 0) throw new PartialFailureError(`Rollback completed with ${totalFailures} failed operation(s). Journal preserved` + failedRollbackTail(stackName, region, failedOrphanIds));
20967
21164
  if (totalWarnings > 0) throw new PartialFailureError(`Rollback completed with ${totalWarnings} skipped/unrecoverable operation(s) (see warnings above).`);
20968
21165
  logger.info(`\nRollback of ${stackRegionShown(stackName, region)} complete.`);
20969
21166
  } finally {
@@ -21006,13 +21203,13 @@ async function rollbackCommand(stackArg, options) {
21006
21203
  return !inRegion.some((p) => p.stackName === parent && p.region === c.region);
21007
21204
  });
21008
21205
  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.");
21206
+ 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
21207
  return;
21011
21208
  }
21012
21209
  if (scoped.length > 1) {
21013
21210
  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).`);
21211
+ 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` : "";
21212
+ 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
21213
  }
21017
21214
  ref = scoped[0];
21018
21215
  }
@@ -21315,11 +21512,11 @@ function createEventsCommand() {
21315
21512
  return cmd;
21316
21513
  }
21317
21514
  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) => {
21515
+ 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
21516
  const n = parseInt(v, 10);
21320
21517
  if (!Number.isInteger(n) || n < 0) throw new Error(`Invalid --keep value ${v === "" ? "\"\"" : displayIdent(v)}: expected a non-negative integer.`);
21321
21518
  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())));
21519
+ }))).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
21520
  }
21324
21521
 
21325
21522
  // src/cli/commands/gc/asset-references.ts
@@ -21688,7 +21885,7 @@ async function gcCommand(options) {
21688
21885
  const lockKeys = await listAllLockKeys(stateBackend);
21689
21886
  if (lockKeys.length > 0) {
21690
21887
  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");
21888
+ 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
21889
  }
21693
21890
  const cutoffMs = Date.now() - options.olderThan;
21694
21891
  const responseCandidates = await listResponsePlaceholderCandidates(stateBackend, cutoffMs, logger);
@@ -21782,7 +21979,7 @@ function parseOlderThan(value) {
21782
21979
  return Math.round(num * multiplier);
21783
21980
  }
21784
21981
  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) => {
21982
+ 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
21983
  await gcCommand(options);
21787
21984
  }));
21788
21985
  commonOptions.forEach((opt) => cmd.addOption(opt));
@@ -22016,6 +22213,11 @@ function withoutDependencies(record, drop) {
22016
22213
  }
22017
22214
 
22018
22215
  // src/cli/commands/refactor-move.ts
22216
+ const stackArg = (value) => ({
22217
+ value,
22218
+ hole: "stack",
22219
+ opts: { patternMatched: true }
22220
+ });
22019
22221
  const rowKey = (stack, region, logicalId) => JSON.stringify([
22020
22222
  stack,
22021
22223
  region,
@@ -22231,9 +22433,9 @@ async function applyMoveGroup(input) {
22231
22433
  const loaded = /* @__PURE__ */ new Map();
22232
22434
  for (const plan of plans) {
22233
22435
  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");
22436
+ 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
22437
  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");
22438
+ 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
22439
  loaded.set(plan, {
22238
22440
  state: stateData.state,
22239
22441
  ...stateData.migrationPending && { migrationPending: true }
@@ -22251,7 +22453,7 @@ async function applyMoveGroup(input) {
22251
22453
  const written = [];
22252
22454
  const fail = (plan, error) => {
22253
22455
  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");
22456
+ 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
22457
  };
22256
22458
  const save = async (plan, state, expectedEtag) => {
22257
22459
  try {
@@ -22300,7 +22502,7 @@ async function applyMoveGroup(input) {
22300
22502
  if (markerMoves.length > 0) try {
22301
22503
  await updateRefactorMarker(stateBackend, (moves) => moves.filter((m) => !markerMoves.some((n) => sameMove(m, n))));
22302
22504
  } 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");
22505
+ 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
22506
  }
22305
22507
  });
22306
22508
  }
@@ -22344,12 +22546,12 @@ async function finishPendingMoves(input) {
22344
22546
  if (dest !== null && Object.hasOwn(dest.state.resources, m.to)) finished.push(finishedOf(m));
22345
22547
  else stuck.push(safeMsg`${stackName}.${m.from} -> ${m.toStack}.${m.to}`);
22346
22548
  }
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");
22549
+ 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
22550
  return { finished };
22349
22551
  }
22350
22552
  const { moves: marked, malformed } = pendingMovesOutOf(first.state);
22351
22553
  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");
22554
+ 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
22555
  if (moves.length === 0) return { finished: [] };
22354
22556
  const keyOf = (s) => producerRecordKey(s.stackName, s.region);
22355
22557
  const stacks = /* @__PURE__ */ new Map();
@@ -22402,7 +22604,7 @@ async function finishPendingMoves(input) {
22402
22604
  const describe = safeMsg`${stackName}.${m.from} -> ${m.toStack}.${m.to}`;
22403
22605
  if (dest === void 0) refusals.push(safeMsg`${describe}: ${m.toStack} (${m.toRegion}) has no cdkd state`);
22404
22606
  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`);
22607
+ if (held === void 0) refusals.push(safeMsg`${describe}: neither stack records the resource; adopt it into ${m.toStack} with ${cdkdRemedy("cdkd import")}`);
22406
22608
  else finished.push(finishedOf(m));
22407
22609
  } 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
22610
  else if (held === void 0) {
@@ -22418,7 +22620,7 @@ async function finishPendingMoves(input) {
22418
22620
  });
22419
22621
  additions.set(destKey, list);
22420
22622
  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`);
22623
+ } 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
22624
  else finished.push(finishedOf(m));
22423
22625
  }
22424
22626
  for (const [destKey, list] of additions) {
@@ -22542,7 +22744,11 @@ async function planStackRefactor(input) {
22542
22744
  refuseMalformedOrphans(state, stackName, region, recovery);
22543
22745
  refuseMalformedOrphanRecords(state, stackName, region, recovery);
22544
22746
  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");
22747
+ 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", [{
22748
+ value: stackName,
22749
+ hole: "stack",
22750
+ opts: { patternMatched: true }
22751
+ }]).command)} reports, then re-run ${cdkdRemedy("cdkd refactor")}.`, "REFACTOR_REFUSED");
22546
22752
  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
22753
  const creates = [];
22548
22754
  const deletes = [];
@@ -22565,7 +22771,7 @@ async function planStackRefactor(input) {
22565
22771
  const skipped = [];
22566
22772
  const candidates = proposal.renames.filter((r) => {
22567
22773
  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`;
22774
+ const reason = `a rollback-orphan record also names ${r.from}; run ${proseQuoted(cdkdRemedy("cdkd deploy"))} first to settle it`;
22569
22775
  if (r.source === "override") refusedOverrides.push({
22570
22776
  from: r.from,
22571
22777
  to: r.to,
@@ -22728,7 +22934,7 @@ async function applyStackRefactor(input) {
22728
22934
  if (!await lockManager.acquireLock(plan.stackName, plan.region, owner, "refactor")) throw new Error(await contentionMessage());
22729
22935
  try {
22730
22936
  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");
22937
+ 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
22938
  refuseMalformedState(stateData.state, plan.stackName, plan.region, input.recovery);
22733
22939
  refuseMalformedOrphans(stateData.state, plan.stackName, plan.region, input.recovery);
22734
22940
  refuseMalformedOrphanRecords(stateData.state, plan.stackName, plan.region, input.recovery);
@@ -22746,7 +22952,11 @@ async function applyStackRefactor(input) {
22746
22952
  }
22747
22953
  }
22748
22954
  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");
22955
+ 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", [{
22956
+ value: stackName,
22957
+ hole: "stack",
22958
+ opts: { patternMatched: true }
22959
+ }]).command)} ` + `or a successful ${proseQuoted(cdkdRemedy("cdkd deploy"))} first.`, "REFACTOR_REFUSED");
22750
22960
  }
22751
22961
  function renderRefactorPlan(plan) {
22752
22962
  const lines = [safeMsg`Stack ${plan.stackName} (${plan.region})`];
@@ -23038,7 +23248,7 @@ async function refactorCommand(stacks, options) {
23038
23248
  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
23249
  }
23040
23250
  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");
23251
+ 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
23252
  const toApply = plans.filter((p) => p.renames.length > 0 || p.movesOut.length > 0 || p.movesIn.length > 0);
23043
23253
  if (toApply.length === 0) {
23044
23254
  logger.info("\nNothing to refactor.");
@@ -23069,7 +23279,7 @@ async function refactorCommand(stacks, options) {
23069
23279
  })
23070
23280
  }), holdNotice);
23071
23281
  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.");
23282
+ 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
23283
  return;
23074
23284
  }
23075
23285
  const done = [];
@@ -23094,7 +23304,7 @@ async function refactorCommand(stacks, options) {
23094
23304
  done.push(`${plan.stackName} (${plan.region})`);
23095
23305
  logger.info(safeMsg`Refactored ${plan.renames.length} resource(s) in stack ${plan.stackName} (${plan.region}).`);
23096
23306
  }
23097
- logger.info("\nAWS resources were not touched. Run 'cdkd diff' to confirm the renamed resources show no change.");
23307
+ logger.info(safeMsg`\nAWS resources were not touched. Run ${proseQuoted(cdkdRemedy("cdkd diff"))} to confirm the renamed resources show no change.`);
23098
23308
  } finally {
23099
23309
  awsClients.destroy();
23100
23310
  }
@@ -23184,7 +23394,7 @@ async function publishAssetsCommand(stacks, options) {
23184
23394
  try {
23185
23395
  bucket = await resolveStateBucketWithDefault(options.stateBucket, baseRegion, legacyStateBucketFallbackRegion(effectiveRegion));
23186
23396
  } 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.");
23397
+ 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
23398
  markerAccess = null;
23189
23399
  return null;
23190
23400
  }
@@ -23321,7 +23531,7 @@ async function publishAssetsCommand(stacks, options) {
23321
23531
  logger.info(`\n${green("✓")} ${bold("Asset publishing complete")} (${totalAssets} asset(s))`);
23322
23532
  }
23323
23533
  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));
23534
+ 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
23535
  [
23326
23536
  ...commonOptions,
23327
23537
  ...appOptions,
@@ -24140,7 +24350,7 @@ async function resolveImportedProperties(stackState, template, region, stateBack
24140
24350
  attributes: resource.attributes
24141
24351
  });
24142
24352
  } 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'.` : ""));
24353
+ 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
24354
  threw = true;
24145
24355
  }
24146
24356
  if (recordedSecretValues.size > 0 && resource.attributes !== void 0) resource.attributes = redactForState(resource.attributes, {
@@ -24170,7 +24380,7 @@ async function resolveImportedProperties(stackState, template, region, stateBack
24170
24380
  const unreadable = refusedHere.filter((id) => parameterTaint.unclassifiable.has(id));
24171
24381
  if (refusedHere.length > 0) {
24172
24382
  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'.");
24383
+ 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
24384
  }
24175
24385
  }
24176
24386
  positionImportedNoEcho(stackState, noEchoInputs, template, conditions, unsafeObservedBaselineLogicalIds, logger);
@@ -24184,7 +24394,7 @@ async function claimRegistryMarkerAfterImport(backend, stackName, region, logger
24184
24394
  switch (answer.kind) {
24185
24395
  case "clear": return;
24186
24396
  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.");
24397
+ 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
24398
  return;
24189
24399
  case "in-progress":
24190
24400
  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 +24852,7 @@ async function runLockedImport(ctx) {
24642
24852
  await stateBackend.saveState(stackInfo.stackName, targetRegion, stackState, saveOptions);
24643
24853
  logger.info(`✓ State written: ${stackInfo.stackName} (${targetRegion})`);
24644
24854
  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.`);
24855
+ logger.info(safeMsg` ${importedRows.length} resource(s) imported. ` + safeMsg`See how the imported state lines up with the template with: ${cdkdRemedy("cdkd diff")}`);
24646
24856
  if (migrationCfnStackName && migrationTree && accountIdForNestedSynth) await importNestedStackChildrenRecursive({
24647
24857
  lockRecovery,
24648
24858
  parentStackName: stackInfo.stackName,
@@ -24774,7 +24984,7 @@ async function importCommand(stackArg, options) {
24774
24984
  const overrides = parseResourceOverrides(options.resource, options.resourceMapping, options.resourceMappingInline);
24775
24985
  if (overrides.size > 0) logger.debug(`User-supplied physical IDs: ${[...overrides.keys()].join(", ")}`);
24776
24986
  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.");
24987
+ 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
24988
  const template = stackInfo.template;
24779
24989
  const templateParser = new TemplateParser();
24780
24990
  const resources = collectImportableResources(template);
@@ -24936,7 +25146,7 @@ async function loadStateForStack(stackName, synthRegion, opts) {
24936
25146
  const logger = getLogger();
24937
25147
  const prefix = opts.logPrefix ?? "--from-state";
24938
25148
  const warn = opts.warn ?? ((message) => logger.warn(message));
24939
- const region = canonicalizeRegion(opts.region ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"] ?? synthRegion ?? "us-east-1");
25149
+ const region = canonicalizeRegion(opts.region ?? namedEnvAwsRegion() ?? process.env["AWS_DEFAULT_REGION"] ?? synthRegion ?? emulatorDefaultRegion() ?? "us-east-1");
24940
25150
  const clientRegion = canonicalizeRegion(opts.region) || void 0;
24941
25151
  let stateBucket;
24942
25152
  try {
@@ -26529,6 +26739,80 @@ function warnIamRoutes(routesWithAuth) {
26529
26739
  return true;
26530
26740
  }
26531
26741
 
26742
+ // src/cli/commands/local-invoke/execution-role.ts
26743
+ function suggestAssumeRoleFromState(state, logicalId) {
26744
+ const logger = getLogger();
26745
+ const roleArn = resolveExecutionRoleArnFromState(state, logicalId);
26746
+ 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.`);
26747
+ }
26748
+ function maybeSuggestAssumeRole(options, state, logicalId) {
26749
+ if (options.assumeRole !== void 0) return false;
26750
+ if (!options.fromState || !state) return false;
26751
+ if (stateRoleRecordIsEmulatorSide()) return false;
26752
+ suggestAssumeRoleFromState(state, logicalId);
26753
+ return true;
26754
+ }
26755
+ function resolveExecutionRoleArnFromState(state, logicalId, roleProperty = "Role") {
26756
+ const found = classifyExecutionRoleArnFromState(state, logicalId, roleProperty);
26757
+ if (found.kind === "ok") return found.arn;
26758
+ if (found.kind === "malformed") getLogger().warn(`${found.description}. Ignoring it.`);
26759
+ }
26760
+ function mixedModeEmulatorRoleWarning(pin) {
26761
+ 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.`;
26762
+ }
26763
+ function resolveBareAssumeRoleFromState(state, logicalId) {
26764
+ const logger = getLogger();
26765
+ if (stateRoleRecordIsEmulatorSide()) {
26766
+ logger.warn(mixedModeEmulatorRoleWarning("--assume-role '<arn>'"));
26767
+ return;
26768
+ }
26769
+ const arn = resolveExecutionRoleArnFromState(state, logicalId);
26770
+ if (arn) {
26771
+ logger.info(safeMsg`--assume-role: auto-resolved execution role from cdkd state: ${shellBoundedDisplay(displayIdent(arn, { maxCodePoints: 613 }))}`);
26772
+ return arn;
26773
+ }
26774
+ 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.");
26775
+ }
26776
+ function classifyExecutionRoleArnFromState(state, logicalId, roleProperty = "Role") {
26777
+ const lambda = state.resources[logicalId];
26778
+ if (!lambda) return { kind: "miss" };
26779
+ const roleRef = lambda.properties?.[roleProperty] ?? lambda.observedProperties?.[roleProperty];
26780
+ if (typeof roleRef === "string") {
26781
+ if (isIamRoleArn(roleRef)) return {
26782
+ kind: "ok",
26783
+ arn: roleRef
26784
+ };
26785
+ if (roleRef.startsWith("arn:")) return {
26786
+ kind: "malformed",
26787
+ 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 }))}`
26788
+ };
26789
+ return { kind: "miss" };
26790
+ }
26791
+ if (typeof roleRef === "object" && roleRef !== null) {
26792
+ const refLogicalId = pickReferencedLogicalId(roleRef);
26793
+ if (refLogicalId) {
26794
+ const cached = state.resources[refLogicalId]?.attributes?.["Arn"];
26795
+ if (typeof cached === "string" && isIamRoleArn(cached)) return {
26796
+ kind: "ok",
26797
+ arn: cached
26798
+ };
26799
+ if (typeof cached === "string" && cached.startsWith("arn:")) return {
26800
+ kind: "malformed",
26801
+ description: `The cached Arn attribute of ${quotedOrDescribed(refLogicalId, "logical id")} is not a well-formed IAM role ARN: ${shellBoundedDisplay(displayIdent(cached, { maxCodePoints: 613 }))}`
26802
+ };
26803
+ }
26804
+ }
26805
+ return { kind: "miss" };
26806
+ }
26807
+ function pickReferencedLogicalId(intrinsic) {
26808
+ if ("Ref" in intrinsic && typeof intrinsic["Ref"] === "string") return intrinsic["Ref"];
26809
+ if ("Fn::GetAtt" in intrinsic) {
26810
+ const arg = intrinsic["Fn::GetAtt"];
26811
+ if (Array.isArray(arg) && typeof arg[0] === "string") return arg[0];
26812
+ if (typeof arg === "string") return arg.split(".")[0];
26813
+ }
26814
+ }
26815
+
26532
26816
  // src/cli/commands/local-start-api/assume-role.ts
26533
26817
  function resolveStartApiAssumeRoleArn(args) {
26534
26818
  const { logicalId, assumeRole, lambdaResource, stateBundle } = args;
@@ -26539,6 +26823,10 @@ function resolveStartApiAssumeRoleArn(args) {
26539
26823
  const roleProp = (lambdaResource.Properties ?? {})["Role"];
26540
26824
  if (typeof roleProp === "string" && isIamRoleArn(roleProp)) return roleProp;
26541
26825
  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 })));
26826
+ if (stateBundle && stateRoleRecordIsEmulatorSide()) {
26827
+ getLogger().warn(mixedModeEmulatorRoleWarning(assumeRolePin(logicalId)));
26828
+ return;
26829
+ }
26542
26830
  if (stateBundle) {
26543
26831
  const fromState = classifyExecutionRoleArnFromState(stateBundle.state, logicalId);
26544
26832
  if (fromState.kind === "malformed") throw malformedAutoRoleError(logicalId, fromState.description);
@@ -27211,6 +27499,7 @@ async function emulate(args) {
27211
27499
  failedRoles.add(args.roleArn);
27212
27500
  logger.warn(safeMsg`${args.flag}: AssumeRole(${shownRole}) was refused, and cdkd cannot emulate the role's permissions instead: ${reason}.`);
27213
27501
  };
27502
+ 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
27503
  const { STSClient, GetCallerIdentityCommand, GetFederationTokenCommand } = await import("@aws-sdk/client-sts");
27215
27504
  const sts = new STSClient({
27216
27505
  ...awsClientDefaults({
@@ -27392,11 +27681,11 @@ async function assumeLambdaExecutionRole$1(roleArn, region, emulateRoleVia) {
27392
27681
  DurationSeconds: 3600
27393
27682
  }))).Credentials;
27394
27683
  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 {
27684
+ return keepEmulatorIssuedCredentials({
27396
27685
  accessKeyId: creds.AccessKeyId,
27397
27686
  secretAccessKey: creds.SecretAccessKey,
27398
27687
  sessionToken: creds.SessionToken
27399
- };
27688
+ });
27400
27689
  } catch (err) {
27401
27690
  if (err instanceof CdkdError) throw err;
27402
27691
  const emulated = await emulateRoleAfterDeniedAssume(err, {
@@ -27407,7 +27696,7 @@ async function assumeLambdaExecutionRole$1(roleArn, region, emulateRoleVia) {
27407
27696
  flag: "--assume-role",
27408
27697
  sessionNamePrefix: "cdkd-local-start-api"
27409
27698
  });
27410
- if (emulated) return emulated;
27699
+ if (emulated) return keepEmulatorIssuedCredentials(emulated);
27411
27700
  const rendered = describeLocalAwsFailureForWarn(err, "STS AssumeRole");
27412
27701
  throw new CdkdError(`--assume-role: STS AssumeRole(${displayIdent(roleArn, { maxCodePoints: 613 })}) failed: ${rendered}.`, "LOCAL_START_API_ASSUMEROLE_FAILED", redactedAwsCause(err, "STS AssumeRole failed"));
27413
27702
  } finally {
@@ -27644,6 +27933,12 @@ function detectEcsImageResolutionNeeds(stack) {
27644
27933
  const flat = extractImageString(image);
27645
27934
  if (flat !== void 0 && extractEcrRepoComponent(flat) !== void 0 && !CDK_ASSET_IMAGE_REPO_RE.test(flat)) needsAssetRepoMarker = true;
27646
27935
  if (containerHasIntrinsicEnvOrSecret(co)) needsEnvOrSecretSubstitution = true;
27936
+ const argv = containerArgvElements(co);
27937
+ if (argv.some((v) => v !== null && typeof v === "object")) needsEnvOrSecretSubstitution = true;
27938
+ if (argv.some(isCrossStackIntrinsic)) {
27939
+ needsEnvOrSecretSubstitution = true;
27940
+ needsCrossStackResolver = true;
27941
+ }
27647
27942
  if (containerHasCrossStackEnvOrSecret(co)) {
27648
27943
  needsEnvOrSecretSubstitution = true;
27649
27944
  needsCrossStackResolver = true;
@@ -27683,10 +27978,16 @@ function containerHasCrossStackEnvOrSecret(c) {
27683
27978
  }
27684
27979
  return false;
27685
27980
  }
27981
+ function containerArgvElements(c) {
27982
+ const health = c["HealthCheck"];
27983
+ return [
27984
+ c["Command"],
27985
+ c["EntryPoint"],
27986
+ health && typeof health === "object" ? health["Command"] : void 0
27987
+ ].flatMap((l) => Array.isArray(l) ? l : []);
27988
+ }
27686
27989
  function isCrossStackIntrinsic(value) {
27687
- if (!value || typeof value !== "object") return false;
27688
- const obj = value;
27689
- return "Fn::ImportValue" in obj || "Fn::GetStackOutput" in obj;
27990
+ return containsCrossStackIntrinsic(value);
27690
27991
  }
27691
27992
  function volumeHasIntrinsicSourcePath(v) {
27692
27993
  if (!v || typeof v !== "object") return false;
@@ -27812,10 +28113,11 @@ function parseContainerDefinition(raw, idx, taskLogicalId, resources, stack, con
27812
28113
  const name = pickString(c["Name"]);
27813
28114
  if (!name) throw new EcsTaskResolutionError(`Task '${taskLogicalId}' ContainerDefinitions[${idx}] has no Name.`);
27814
28115
  const image = parseContainerImage(c["Image"], name, taskLogicalId, resources, stack, context);
27815
- const command = pickStringArray(c["Command"]);
27816
- const entryPoint = pickStringArray(c["EntryPoint"]);
27817
- const workingDirectory = pickString(c["WorkingDirectory"]);
27818
28116
  const subContext = buildSubstitutionContextFromImageContext(context);
28117
+ const unresolvedCommandElements = [];
28118
+ const command = resolveArgvArray(c["Command"], "Command", subContext, unresolvedCommandElements);
28119
+ const entryPoint = resolveArgvArray(c["EntryPoint"], "EntryPoint", subContext, unresolvedCommandElements);
28120
+ const workingDirectory = pickString(c["WorkingDirectory"]);
27819
28121
  const environment = {};
27820
28122
  const droppedEnvKeys = [];
27821
28123
  if (Array.isArray(c["Environment"])) for (const entry of c["Environment"]) {
@@ -27923,7 +28225,7 @@ function parseContainerDefinition(raw, idx, taskLogicalId, resources, stack, con
27923
28225
  let healthCheck;
27924
28226
  if (c["HealthCheck"] && typeof c["HealthCheck"] === "object") {
27925
28227
  const h = c["HealthCheck"];
27926
- const command2 = pickStringArray(h["Command"]);
28228
+ const command2 = resolveArgvArray(h["Command"], "HealthCheck.Command", subContext, unresolvedCommandElements);
27927
28229
  if (command2 && command2.length > 0) {
27928
28230
  healthCheck = { command: command2 };
27929
28231
  if (typeof h["Interval"] === "number") healthCheck.interval = h["Interval"];
@@ -27973,8 +28275,133 @@ function parseContainerDefinition(raw, idx, taskLogicalId, resources, stack, con
27973
28275
  if (privileged !== void 0) out.privileged = privileged;
27974
28276
  if (readonlyRootFilesystem !== void 0) out.readonlyRootFilesystem = readonlyRootFilesystem;
27975
28277
  if (droppedSecretKeys.length > 0) out.droppedSecretNames = droppedSecretKeys.map((d) => d.key);
28278
+ if (unresolvedCommandElements.length > 0) out.unresolvedCommandElements = unresolvedCommandElements;
28279
+ return out;
28280
+ }
28281
+ function resolveArgvArray(raw, field, subContext, unresolved) {
28282
+ if (!Array.isArray(raw)) return void 0;
28283
+ return raw.map((element, index) => {
28284
+ if (typeof element === "string") return element;
28285
+ if (typeof element === "number" || typeof element === "boolean") return String(element);
28286
+ if (!element || typeof element !== "object" || Array.isArray(element)) {
28287
+ unresolved.push({
28288
+ field,
28289
+ index,
28290
+ reason: "not a string or an intrinsic"
28291
+ });
28292
+ return "";
28293
+ }
28294
+ if (isCrossStackIntrinsic(element)) {
28295
+ unresolved.push({
28296
+ field,
28297
+ index,
28298
+ reason: CROSS_STACK_ARGV_REASON
28299
+ });
28300
+ return "";
28301
+ }
28302
+ if (!subContext) {
28303
+ unresolved.push({
28304
+ field,
28305
+ index,
28306
+ reason: NO_STATE_ARGV_REASON
28307
+ });
28308
+ return "";
28309
+ }
28310
+ const secret = secretAttributeRead(element, subContext.resources);
28311
+ if (secret !== void 0) {
28312
+ unresolved.push({
28313
+ field,
28314
+ index,
28315
+ reason: secret
28316
+ });
28317
+ return "";
28318
+ }
28319
+ const sub = substituteAgainstState(element, subContext);
28320
+ if (sub.kind !== "literal") {
28321
+ unresolved.push({
28322
+ field,
28323
+ index,
28324
+ reason: sub.reason
28325
+ });
28326
+ return "";
28327
+ }
28328
+ const arg = argvValue(sub.value);
28329
+ if ("value" in arg) return arg.value;
28330
+ unresolved.push({
28331
+ field,
28332
+ index,
28333
+ reason: arg.reason
28334
+ });
28335
+ return "";
28336
+ });
28337
+ }
28338
+ function secretAttributeRead(element, stateResources) {
28339
+ for (const [logicalId, attribute] of getAttReads(element)) {
28340
+ const record = Object.hasOwn(stateResources, logicalId) ? stateResources[logicalId] : void 0;
28341
+ const recorded = record?.attributes;
28342
+ const stored = recorded && Object.hasOwn(recorded, attribute) ? recorded[attribute] : void 0;
28343
+ if (isSensitiveAttributeName(attribute) || isSecretValuedAttribute(record?.resourceType, attribute) || stored === "***") return `reads the secret attribute ${logicalId}.${attribute}, which cdkd will not put on the docker run command line; pass the value through Environment or Secrets instead`;
28344
+ }
28345
+ }
28346
+ function computedAttributeRead(node) {
28347
+ if (node === null || typeof node !== "object") return void 0;
28348
+ if (Array.isArray(node)) {
28349
+ for (const item of node) {
28350
+ const r = computedAttributeRead(item);
28351
+ if (r !== void 0) return r;
28352
+ }
28353
+ return;
28354
+ }
28355
+ for (const [key, value] of Object.entries(node)) {
28356
+ if (key === "Fn::GetAtt" && isCrossStackIntrinsic(value)) return "a Fn::GetAtt whose logical ID or attribute name is a cross-stack reference, which CloudFormation does not accept";
28357
+ if (key === "Fn::Sub") {
28358
+ const template = Array.isArray(value) ? value[0] : value;
28359
+ if (isCrossStackIntrinsic(template)) return "a Fn::Sub whose template is a cross-stack reference, which CloudFormation does not accept";
28360
+ }
28361
+ const r = computedAttributeRead(value);
28362
+ if (r !== void 0) return r;
28363
+ }
28364
+ }
28365
+ function getAttReads(node, out = []) {
28366
+ if (node === null || typeof node !== "object") return out;
28367
+ if (Array.isArray(node)) {
28368
+ for (const item of node) getAttReads(item, out);
28369
+ return out;
28370
+ }
28371
+ for (const [key, value] of Object.entries(node)) {
28372
+ if (key === "Fn::GetAtt") {
28373
+ if (Array.isArray(value) && typeof value[0] === "string" && typeof value[1] === "string") out.push([value[0], value[1]]);
28374
+ else if (typeof value === "string" && value.includes(".")) {
28375
+ const dot = value.indexOf(".");
28376
+ out.push([value.slice(0, dot), value.slice(dot + 1)]);
28377
+ }
28378
+ } else if (key === "Fn::Sub") {
28379
+ const template = Array.isArray(value) ? value[0] : value;
28380
+ if (typeof template === "string") for (const m of template.matchAll(/\$\{([^}!]+)\}/g)) {
28381
+ const ref = m[1];
28382
+ const dot = ref.indexOf(".");
28383
+ if (dot > 0 && !ref.startsWith("AWS::")) out.push([ref.slice(0, dot), ref.slice(dot + 1)]);
28384
+ }
28385
+ }
28386
+ getAttReads(value, out);
28387
+ }
27976
28388
  return out;
27977
28389
  }
28390
+ const NO_STATE_ARGV_REASON = "intrinsic-valued and no deployed state was loaded: deploy the stack and pass --from-state (cdkd-deployed) or --from-cfn-stack (cdk-deployed) to substitute it against that state (Ref, Fn::GetAtt, Fn::Sub, Fn::Join, Fn::Select, Fn::Split and pseudo parameters resolve; Fn::If and Fn::FindInMap do not)";
28391
+ const CROSS_STACK_ARGV_REASON = "a cross-stack reference (Fn::ImportValue / Fn::GetStackOutput): it resolves only from a state source (--from-state / --from-cfn-stack) with the producer stack deployed";
28392
+ function argvValue(value) {
28393
+ if (typeof value === "number" || typeof value === "boolean") return { value: String(value) };
28394
+ if (typeof value !== "string") return { reason: "resolved to a non-string value" };
28395
+ if (value === "***") return { reason: `resolved to the secret mask (${"***"}), not the deployed value` };
28396
+ if (containsDynamicReference(value)) return { reason: "resolved to a CloudFormation dynamic reference ({{resolve:...}}), which cdkd resolves only in Environment, because resolving one here would put the secret on the docker run argv; move the value into an Environment variable or a Secrets entry" };
28397
+ return { value };
28398
+ }
28399
+ function assertEcsTaskCommandsResolved(task) {
28400
+ const lines = [];
28401
+ for (const container of task.containers) for (const u of container.unresolvedCommandElements ?? []) lines.push(` - Container '${container.name}' ${u.field}[${u.index}]: ${u.reason}`);
28402
+ if (lines.length === 0) return;
28403
+ throw new EcsTaskResolutionError(`Task '${task.taskDefinitionLogicalId}' has container command elements cdkd could not resolve:\n${lines.join("\n")}\ncdkd refuses to run the task with these arguments missing, since that runs a different command than the deployed task. Deploy the stack and pass --from-state (cdkd-deployed) or --from-cfn-stack (cdk-deployed) so each element resolves against deployed state.`);
28404
+ }
27978
28405
  function buildSubstitutionContextFromImageContext(context) {
27979
28406
  if (!context?.stateResources) return void 0;
27980
28407
  const subContext = { resources: context.stateResources };
@@ -28091,7 +28518,7 @@ function resolveEcsTaskTarget(target, stacks, context) {
28091
28518
  logicalId = parsed.pathOrId;
28092
28519
  }
28093
28520
  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.`);
28521
+ 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
28522
  if (resource.Type !== "AWS::ECS::TaskDefinition") throw new EcsTaskResolutionError(`Resource '${logicalId}' in ${stack.stackName} is ${resource.Type}, not an AWS::ECS::TaskDefinition.`);
28096
28523
  return extractTaskDefinitionProperties(stack, logicalId, resource, context);
28097
28524
  }
@@ -28183,6 +28610,21 @@ function notFoundError(target, stack, resources) {
28183
28610
  }
28184
28611
 
28185
28612
  // src/local/ecs-task-resolver/cross-stack.ts
28613
+ function argvTarget(container, field) {
28614
+ if (field === "Command") return container.command;
28615
+ if (field === "EntryPoint") return container.entryPoint;
28616
+ return container.healthCheck?.command;
28617
+ }
28618
+ function rawArgv(c, field) {
28619
+ let raw;
28620
+ if (field === "Command") raw = c["Command"];
28621
+ else if (field === "EntryPoint") raw = c["EntryPoint"];
28622
+ else {
28623
+ const h = c["HealthCheck"];
28624
+ raw = h && typeof h === "object" ? h["Command"] : void 0;
28625
+ }
28626
+ return Array.isArray(raw) ? raw : void 0;
28627
+ }
28186
28628
  async function applyCrossStackResolverToTask(task, context) {
28187
28629
  if (!context.crossStackResolver) return;
28188
28630
  const { resolveDynamicReferences: _envOnly, ...secretContext } = context;
@@ -28241,6 +28683,38 @@ async function applyCrossStackResolverToTask(task, context) {
28241
28683
  if (container.droppedSecretNames) container.droppedSecretNames = container.droppedSecretNames.filter((n) => n !== sName);
28242
28684
  }
28243
28685
  }
28686
+ if (container.unresolvedCommandElements?.length) {
28687
+ const remaining = [];
28688
+ for (const u of container.unresolvedCommandElements) {
28689
+ const target = argvTarget(container, u.field);
28690
+ const rawElement = rawArgv(c, u.field)?.[u.index];
28691
+ if (!target || !isCrossStackIntrinsic(rawElement)) {
28692
+ remaining.push(u);
28693
+ continue;
28694
+ }
28695
+ const refusal = secretAttributeRead(rawElement, secretContext.resources) ?? computedAttributeRead(rawElement);
28696
+ if (refusal !== void 0) {
28697
+ remaining.push({
28698
+ ...u,
28699
+ reason: refusal
28700
+ });
28701
+ continue;
28702
+ }
28703
+ const masked = { hit: false };
28704
+ const sub = await substituteAgainstStateAsync(rawElement, withMaskWatch(secretContext, masked));
28705
+ const arg = masked.hit ? { reason: `resolved a cross-stack value recorded as the secret mask (${"***"}), not the deployed value` } : sub.kind === "literal" ? argvValue(sub.value) : { reason: sub.reason };
28706
+ if ("value" in arg) {
28707
+ target[u.index] = arg.value;
28708
+ continue;
28709
+ }
28710
+ remaining.push({
28711
+ ...u,
28712
+ reason: arg.reason
28713
+ });
28714
+ }
28715
+ if (remaining.length > 0) container.unresolvedCommandElements = remaining;
28716
+ else delete container.unresolvedCommandElements;
28717
+ }
28244
28718
  if (resolvedEnvKeys.size > 0 || resolvedSecretNames.size > 0) {
28245
28719
  container.warnings = container.warnings.filter((w) => {
28246
28720
  for (const k of resolvedEnvKeys) if (w.startsWith(`Environment '${k}' dropped:`)) return false;
@@ -28255,6 +28729,22 @@ async function applyCrossStackResolverToTask(task, context) {
28255
28729
  }
28256
28730
  }
28257
28731
  }
28732
+ function withMaskWatch(context, masked) {
28733
+ const inner = context.crossStackResolver;
28734
+ if (!inner) return context;
28735
+ const watch = (v) => {
28736
+ if (v === "***") masked.hit = true;
28737
+ return v;
28738
+ };
28739
+ const resolver = {
28740
+ resolveImport: async (exportName) => watch(await inner.resolveImport(exportName)),
28741
+ resolveGetStackOutput: async (stack, region, output) => watch(await inner.resolveGetStackOutput(stack, region, output))
28742
+ };
28743
+ return {
28744
+ ...context,
28745
+ crossStackResolver: resolver
28746
+ };
28747
+ }
28258
28748
 
28259
28749
  // src/cli/commands/local-start-api/state.ts
28260
28750
  function stateBundleKey(stackName, workload) {
@@ -28340,7 +28830,7 @@ async function loadStateForRoutedStacks(stacks, routes, routesWithAuth, options)
28340
28830
  }
28341
28831
  async function resolvePseudoParametersForStartApi(stateRegion, options) {
28342
28832
  const logger = getLogger();
28343
- const region = canonicalizeRegion(options.region ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"] ?? stateRegion);
28833
+ const region = canonicalizeRegion(options.region ?? namedEnvAwsRegion() ?? process.env["AWS_DEFAULT_REGION"] ?? stateRegion);
28344
28834
  const sourceFlag = options.fromState ? "--from-state" : "--from-cfn-stack";
28345
28835
  let accountId;
28346
28836
  try {
@@ -28668,7 +29158,7 @@ async function localStartApiCommand(target, options) {
28668
29158
  let apiFilter = target;
28669
29159
  if (options.api !== void 0) {
28670
29160
  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>'.");
29161
+ 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
29162
  apiFilter = options.api;
28673
29163
  }
28674
29164
  warnIfDeprecatedRegion(options);
@@ -28761,7 +29251,7 @@ async function localStartApiCommand(target, options) {
28761
29251
  assumeRole: options.assumeRole,
28762
29252
  containerHost: options.containerHost,
28763
29253
  ...debugPortBase !== void 0 && { debugPort: debugPortBase + index },
28764
- stsRegion: canonicalizeRegion(options.region ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"]),
29254
+ stsRegion: canonicalizeRegion(options.region ?? namedEnvAwsRegion() ?? process.env["AWS_DEFAULT_REGION"]),
28765
29255
  inlineTmpDirs,
28766
29256
  layerTmpDirs,
28767
29257
  stateByStack,
@@ -28952,7 +29442,7 @@ async function localStartApiCommand(target, options) {
28952
29442
 
28953
29443
  // src/cli/commands/local-start-api.ts
28954
29444
  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));
29445
+ 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
29446
  [
28957
29447
  ...commonOptions,
28958
29448
  ...appOptions,
@@ -29652,6 +30142,11 @@ function buildDockerRunArgs(opts) {
29652
30142
  ...wiring,
29653
30143
  env: {}
29654
30144
  });
30145
+ for (const h of awsEmulatorSqsHostBlocks(finalEnv, wiring)) {
30146
+ const mapping = `${h.host}:${h.ip}`;
30147
+ args.push("--add-host", mapping);
30148
+ ownerAddHosts.push(mapping);
30149
+ }
29655
30150
  }
29656
30151
  const sensitiveKeys = /* @__PURE__ */ new Set([
29657
30152
  ...SENSITIVE_ENV_KEYS,
@@ -30265,7 +30760,7 @@ async function resolveStackAccountId$1(source) {
30265
30760
  // src/cli/commands/local-run-task/image-context.ts
30266
30761
  function resolveEcsConsumerRegion(stateRecordRegion, options, synthRegion) {
30267
30762
  if (stateRecordRegion) return stateRecordRegion;
30268
- return canonicalizeRegion((options.region || process.env["AWS_REGION"]) ?? process.env["AWS_DEFAULT_REGION"] ?? synthRegion ?? "us-east-1");
30763
+ return canonicalizeRegion((options.region || namedEnvAwsRegion()) ?? process.env["AWS_DEFAULT_REGION"] ?? synthRegion ?? emulatorDefaultRegion() ?? "us-east-1");
30269
30764
  }
30270
30765
  async function buildEcsImageResolutionContext$1(candidate, stateProvider, options) {
30271
30766
  const logger = getLogger();
@@ -30279,7 +30774,7 @@ async function buildEcsImageResolutionContext$1(candidate, stateProvider, option
30279
30774
  let stateRecordRegion;
30280
30775
  const wantsPseudoForEnvOrSecret = !!stateProvider && needs.needsEnvOrSecretSubstitution;
30281
30776
  if (needs.needsPseudoParameters || wantsPseudoForEnvOrSecret) {
30282
- const region = canonicalizeRegion(options.region ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"] ?? candidate.region);
30777
+ const region = canonicalizeRegion(options.region ?? namedEnvAwsRegion() ?? process.env["AWS_DEFAULT_REGION"] ?? candidate.region ?? emulatorDefaultRegion());
30283
30778
  if (!region) logger.warn("Resolver references ${AWS::Region} but cdkd could not determine the target region. Pass --region, set AWS_REGION, or declare env.region on the CDK stack.");
30284
30779
  let accountId;
30285
30780
  try {
@@ -30311,7 +30806,7 @@ async function buildEcsImageResolutionContext$1(candidate, stateProvider, option
30311
30806
  }
30312
30807
  } else if (!stateProvider && needs.needsStateResources) {
30313
30808
  if (!options.imageOverride?.length) logger.warn("Container Image references a same-stack AWS::ECR::Repository. Pass --from-state (cdkd-deployed) or --from-cfn-stack (cdk-deployed) to substitute the deployed repository URI, or --image-override to build it from a local Dockerfile. Otherwise the run stops before any container starts.");
30314
- } else if (!stateProvider && needs.needsEnvOrSecretSubstitution) logger.warn("Container Environment / Secrets entries contain CloudFormation intrinsics (Ref / Fn::GetAtt / Fn::Sub / Fn::Join). Pass --from-state (cdkd-deployed) or --from-cfn-stack (cdk-deployed) to substitute them against deployed state. Without a state source these entries are dropped (per-key warnings will follow).");
30809
+ } else if (!stateProvider && needs.needsEnvOrSecretSubstitution) logger.warn("Container Environment / Secrets / Command entries contain CloudFormation intrinsics (Ref / Fn::GetAtt / Fn::Sub / Fn::Join). Pass --from-state (cdkd-deployed) or --from-cfn-stack (cdk-deployed) to substitute them against deployed state. Without a state source Environment / Secrets entries are dropped (per-key warnings will follow) and an intrinsic Command / EntryPoint / HealthCheck.Command element refuses the run.");
30315
30810
  if (needs.needsAssetRepoMarker && options.fromState) {
30316
30811
  const containerRepo = await loadBootstrapContainerRepo(candidate.region, {
30317
30812
  statePrefix: options.statePrefix,
@@ -30331,7 +30826,7 @@ async function buildEcsImageResolutionContext$1(candidate, stateProvider, option
30331
30826
  };
30332
30827
  }
30333
30828
  function taskRoleRecordIsEmulatorSide() {
30334
- return getActiveWorkloadAwsWiring$1()?.mixed !== void 0 && !realAwsException("IAM");
30829
+ return stateRoleRecordIsEmulatorSide();
30335
30830
  }
30336
30831
  function pickCandidateStack(parsed, target, stacks) {
30337
30832
  const byPrefix = stackForPathFormTarget(parsed, target, stacks);
@@ -30601,7 +31096,8 @@ async function localRunTaskCommand(target, options) {
30601
31096
  dynamicRefs.dispose();
30602
31097
  }
30603
31098
  }
30604
- } else if (!stateProvider && taskNeeds.needsCrossStackResolver) logger.warn("Container Environment / Secrets entries contain Fn::ImportValue / Fn::GetStackOutput intrinsics. Pass --from-state (cdkd-deployed) or --from-cfn-stack (cdk-deployed) to substitute them against deployed state.");
31099
+ } else if (!stateProvider && taskNeeds.needsCrossStackResolver) logger.warn("Container Environment / Secrets / Command entries contain Fn::ImportValue / Fn::GetStackOutput intrinsics. Pass --from-state (cdkd-deployed) or --from-cfn-stack (cdk-deployed) to substitute them against deployed state.");
31100
+ assertEcsTaskCommandsResolved(task);
30605
31101
  sigintHandler = () => {
30606
31102
  sigintCount += 1;
30607
31103
  if (sigintCount >= 2) {
@@ -30707,6 +31203,11 @@ async function applyPerContainerNames(task, target, stacks, candidate, options,
30707
31203
  if (!mine || !into) continue;
30708
31204
  into.environment = mine.environment;
30709
31205
  into.secrets = mine.secrets;
31206
+ if (mine.command) into.command = mine.command;
31207
+ if (mine.entryPoint) into.entryPoint = mine.entryPoint;
31208
+ if (mine.healthCheck) into.healthCheck = mine.healthCheck;
31209
+ if (mine.unresolvedCommandElements) into.unresolvedCommandElements = mine.unresolvedCommandElements;
31210
+ else delete into.unresolvedCommandElements;
30710
31211
  }
30711
31212
  } finally {
30712
31213
  provider.dispose();
@@ -30868,7 +31369,7 @@ async function runAgentCoreWatchLoop(args) {
30868
31369
  currentAbort?.abort();
30869
31370
  return;
30870
31371
  }
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.`);
31372
+ 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
31373
  reloadFailed = true;
30873
31374
  currentAbort?.abort();
30874
31375
  }
@@ -31239,6 +31740,10 @@ function resolveAssumeRoleArnUncached(options, resolved, loaded) {
31239
31740
  if (options.assumeRole === true) {
31240
31741
  if (resolved.roleArn !== void 0 && isIamRoleArn(resolved.roleArn)) return resolved.roleArn;
31241
31742
  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.`);
31743
+ if (loaded && stateRoleRecordIsEmulatorSide()) {
31744
+ getLogger().warn(mixedModeEmulatorRoleWarning("--assume-role '<arn>'"));
31745
+ return;
31746
+ }
31242
31747
  if (loaded) {
31243
31748
  const fromState = resolveExecutionRoleArnFromState(loaded, resolved.logicalId, "RoleArn");
31244
31749
  if (fromState) {
@@ -31290,16 +31795,16 @@ async function assumeAgentCoreExecutionRole(roleArn, region, emulateRoleVia) {
31290
31795
  flag: "--assume-role",
31291
31796
  sessionNamePrefix: `${getEmbedConfig().resourceNamePrefix}-invoke-agentcore`
31292
31797
  });
31293
- if (emulated) return emulated;
31798
+ if (emulated) return keepEmulatorIssuedCredentials(emulated);
31294
31799
  throw err;
31295
31800
  }
31296
31801
  const creds = response.Credentials;
31297
31802
  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 {
31803
+ return keepEmulatorIssuedCredentials({
31299
31804
  accessKeyId: creds.AccessKeyId,
31300
31805
  secretAccessKey: creds.SecretAccessKey,
31301
31806
  sessionToken: creds.SessionToken
31302
- };
31807
+ });
31303
31808
  } finally {
31304
31809
  sts.destroy();
31305
31810
  }
@@ -31445,7 +31950,7 @@ async function resolveAgentCoreCodeImageFromS3(resolved, code, s3Source, options
31445
31950
  key: s3Source.key,
31446
31951
  ...s3Source.versionId !== void 0 && { versionId: s3Source.versionId }
31447
31952
  };
31448
- const region = canonicalizeRegion(options.region ?? options.stackRegion ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"] ?? resolved.stack.region);
31953
+ const region = canonicalizeRegion(options.region ?? options.stackRegion ?? namedEnvAwsRegion() ?? process.env["AWS_DEFAULT_REGION"] ?? resolved.stack.region ?? emulatorDefaultRegion());
31449
31954
  const assumeRoleArn = resolveAssumeRoleArn(options, resolved, loaded);
31450
31955
  let credentials;
31451
31956
  if (assumeRoleArn) try {
@@ -31513,7 +32018,7 @@ function describeIntrinsic(value) {
31513
32018
  }
31514
32019
  async function buildAgentCoreImageContext(candidate, stateProvider, options) {
31515
32020
  const logger = getLogger();
31516
- const region = canonicalizeRegion(options.region ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"] ?? candidate.region);
32021
+ const region = canonicalizeRegion(options.region ?? namedEnvAwsRegion() ?? process.env["AWS_DEFAULT_REGION"] ?? candidate.region ?? emulatorDefaultRegion());
31517
32022
  let accountId;
31518
32023
  try {
31519
32024
  accountId = await resolveStackAccountId(region, options.profile, options.fromState, options.fromCfnStack);
@@ -31660,7 +32165,7 @@ async function buildSigV4HeadersIfRequested(options, resolved, loaded, host, por
31660
32165
  getLogger().warn(`Runtime '${resolved.logicalId}' declares a customJwtAuthorizer; --sigv4 ignored (JWT path takes precedence).`);
31661
32166
  return;
31662
32167
  }
31663
- const region = canonicalizeRegion(options.region ?? options.stackRegion ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"] ?? resolved.stack.region);
32168
+ const region = canonicalizeRegion(options.region ?? options.stackRegion ?? namedEnvAwsRegion() ?? process.env["AWS_DEFAULT_REGION"] ?? resolved.stack.region ?? emulatorDefaultRegion());
31664
32169
  if (!region) throw new CdkdError("--sigv4: no region resolved for the AgentCore signing scope. Pass --region '<region>', set AWS_REGION, or use --from-cfn-stack with a region-bound stack.", "LOCAL_INVOKE_AGENTCORE_SIGV4_NO_REGION");
31665
32170
  const credentials = await resolveHostCredentialsForSigV4(options, resolved, loaded, region);
31666
32171
  const signed = await signAgentCoreInvocation({
@@ -31815,7 +32320,10 @@ async function localInvokeAgentCoreCommand(target, options) {
31815
32320
  roleFlag: "--assume-role",
31816
32321
  roleRequested: options.assumeRole === true || typeof options.assumeRole === "string"
31817
32322
  });
31818
- await activateLocalAwsAndRoleArn(options);
32323
+ await activateLocalAwsAndRoleArn({
32324
+ ...options,
32325
+ singleWorkload: true
32326
+ });
31819
32327
  await ensureDockerAvailable();
31820
32328
  const profileCredentials = await profileCredentialsForWorkload(options.profile, resolveProfileCredentials);
31821
32329
  if (options.profile && profileCredentials) profileCredsFile = await writeProfileCredentialsFile(options.profile, profileCredentials);
@@ -31848,6 +32356,10 @@ async function localInvokeAgentCoreCommand(target, options) {
31848
32356
  };
31849
32357
  const resolved = resolveAgentCoreTarget(resolvedTarget, stacks, imageContext);
31850
32358
  logger.info(`Target: ${resolved.stack.stackName}/${resolved.logicalId} (${resolved.protocol})`);
32359
+ logMixedModeForWorkload({
32360
+ logicalId: resolved.logicalId,
32361
+ cdkPath: readCdkPathOrUndefined(resolved.resource)
32362
+ }, `AgentCore runtime ${resolved.stack.stackName}/${resolved.logicalId}`);
31851
32363
  const isMcp = resolved.protocol === AGENTCORE_MCP_PROTOCOL;
31852
32364
  const isA2a = resolved.protocol === AGENTCORE_A2A_PROTOCOL;
31853
32365
  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 +32568,7 @@ function parseTimeoutMs(raw) {
32056
32568
  return parsed;
32057
32569
  }
32058
32570
  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) => {
32571
+ 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
32572
  await localInvokeAgentCoreCommand(target, options);
32061
32573
  }));
32062
32574
  [
@@ -32152,7 +32664,7 @@ async function applyLambdaCredentialEnv(dockerEnv, args) {
32152
32664
  setContainerRegion(dockerEnv, containerRegion);
32153
32665
  assumeSucceeded = true;
32154
32666
  } 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.`);
32667
+ 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
32668
  }
32157
32669
  if (!assumeSucceeded) {
32158
32670
  forwardAwsEnv(dockerEnv);
@@ -32191,16 +32703,16 @@ async function assumeLambdaExecutionRole(roleArn, region, emulateRoleVia) {
32191
32703
  flag: "--assume-role",
32192
32704
  sessionNamePrefix: "cdkd-local-invoke"
32193
32705
  });
32194
- if (emulated) return emulated;
32706
+ if (emulated) return keepEmulatorIssuedCredentials(emulated);
32195
32707
  throw err;
32196
32708
  }
32197
32709
  const creds = response.Credentials;
32198
32710
  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 {
32711
+ return keepEmulatorIssuedCredentials({
32200
32712
  accessKeyId: creds.AccessKeyId,
32201
32713
  secretAccessKey: creds.SecretAccessKey,
32202
32714
  sessionToken: creds.SessionToken
32203
- };
32715
+ });
32204
32716
  } finally {
32205
32717
  sts.destroy();
32206
32718
  }
@@ -32249,72 +32761,6 @@ async function readStdin() {
32249
32761
  return Buffer.concat(chunks).toString("utf-8");
32250
32762
  }
32251
32763
 
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
32764
  // src/cli/commands/local-invoke/template-env.ts
32319
32765
  function envHasIntrinsicValue(templateEnv) {
32320
32766
  if (!templateEnv) return false;
@@ -32327,16 +32773,11 @@ function envHasIntrinsicValue(templateEnv) {
32327
32773
  }
32328
32774
  function envHasCrossStackIntrinsic(templateEnv) {
32329
32775
  if (!templateEnv) return false;
32330
- for (const v of Object.values(templateEnv)) {
32331
- if (!v || typeof v !== "object") continue;
32332
- const obj = v;
32333
- if ("Fn::ImportValue" in obj || "Fn::GetStackOutput" in obj) return true;
32334
- }
32335
- return false;
32776
+ return Object.values(templateEnv).some(containsCrossStackIntrinsic);
32336
32777
  }
32337
32778
  async function resolvePseudoParametersForInvoke(stackRegion, options) {
32338
32779
  const logger = getLogger();
32339
- const region = canonicalizeRegion(options.region ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"] ?? stackRegion);
32780
+ const region = canonicalizeRegion(options.region ?? namedEnvAwsRegion() ?? process.env["AWS_DEFAULT_REGION"] ?? stackRegion ?? emulatorDefaultRegion());
32340
32781
  const sourceFlag = options.fromState ? "--from-state" : "--from-cfn-stack";
32341
32782
  if (!region) logger.warn(`${sourceFlag}: resolver references \${AWS::Region} but cdkd could not determine the target region. Pass --region, set AWS_REGION, or declare env.region on the CDK stack.`);
32342
32783
  let accountId;
@@ -32476,7 +32917,10 @@ async function localInvokeCommand(target, options) {
32476
32917
  roleFlag: "--assume-role",
32477
32918
  roleRequested: options.assumeRole === true || typeof options.assumeRole === "string"
32478
32919
  });
32479
- await activateLocalAwsAndRoleArn(options);
32920
+ await activateLocalAwsAndRoleArn({
32921
+ ...options,
32922
+ singleWorkload: true
32923
+ });
32480
32924
  await ensureDockerAvailable();
32481
32925
  const profileCredentials = await profileCredentialsForWorkload(options.profile, resolveProfileCredentials);
32482
32926
  if (options.profile && profileCredentials) profileCredsFile = await writeProfileCredentialsFile(options.profile, profileCredentials);
@@ -32500,6 +32944,10 @@ async function localInvokeCommand(target, options) {
32500
32944
  refuseFailedLookups([lambda.stack], stacks, failedLookups);
32501
32945
  const targetLabel = lambda.kind === "zip" ? lambda.runtime : "container image";
32502
32946
  logger.info(`Target: ${lambda.stack.stackName}/${lambda.logicalId} (${targetLabel})`);
32947
+ logMixedModeForWorkload({
32948
+ logicalId: lambda.logicalId,
32949
+ cdkPath: readCdkPathOrUndefined(lambda.resource)
32950
+ }, `Lambda ${lambda.stack.stackName}/${lambda.logicalId}`);
32503
32951
  imagePlan = await resolveImagePlan(lambda, options);
32504
32952
  const { env: templateEnvResolved, sensitiveEnvKeys, stateForRoleHint, stateRegion } = await resolveInvokeTemplateEnv(lambda, options);
32505
32953
  let resolvedAssumeRoleArn;
@@ -32849,4 +33297,4 @@ function collectVerbFlags(program) {
32849
33297
  }
32850
33298
 
32851
33299
  export { resolveSecretDerivedPrincipals as a, buildProgram, isResolvableSecretPrincipalList as i, runDestroyForStack as n, canonicalizeIpProtocolValue as o, holdsUnprovenSecretPrincipalToken as r, canonicalizeIpv4Cidr as t };
32852
- //# sourceMappingURL=program-CDu5N31o.js.map
33300
+ //# sourceMappingURL=program-DAAu8qUr.js.map