@cdkd/cli 0.334.3 → 0.335.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/ambient-client-defaults-B9bnuob2.js +960 -0
  2. package/dist/ambient-client-defaults-B9bnuob2.js.map +1 -0
  3. package/dist/{asg-provider-Gu-qQLG9.js → asg-provider-pl5tnbiA.js} +4 -3
  4. package/dist/asg-provider-pl5tnbiA.js.map +1 -0
  5. package/dist/cli.js +2 -2
  6. package/dist/{db-instance-modify-retry-AJiRFAXa.js → db-instance-modify-retry-CD7NSyq4.js} +10 -9
  7. package/dist/{db-instance-modify-retry-AJiRFAXa.js.map → db-instance-modify-retry-CD7NSyq4.js.map} +1 -1
  8. package/dist/{deploy-engine-BktCSZdi.js → deploy-engine-iQpILlcZ.js} +2130 -1951
  9. package/dist/deploy-engine-iQpILlcZ.js.map +1 -0
  10. package/dist/{iam-role-provider-BJ5XgxFH.js → iam-role-provider-jC3_bsf-.js} +4 -3
  11. package/dist/iam-role-provider-jC3_bsf-.js.map +1 -0
  12. package/dist/index.d.ts +34 -42
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +3 -3
  15. package/dist/{neptune-provider-6SGPWYUE.js → neptune-provider-CNEMvt4t.js} +5 -4
  16. package/dist/neptune-provider-CNEMvt4t.js.map +1 -0
  17. package/dist/{program-Dm0zFrcG.js → program-DaGdaozO.js} +21 -9
  18. package/dist/program-DaGdaozO.js.map +1 -0
  19. package/dist/{provider-classes-BDPm7luc.js → provider-classes-ZpRORGt2.js} +10 -9
  20. package/dist/provider-classes-ZpRORGt2.js.map +1 -0
  21. package/dist/{rds-provider--9aIoAY-.js → rds-provider-Ce7ua-ww.js} +289 -30
  22. package/dist/rds-provider-Ce7ua-ww.js.map +1 -0
  23. package/dist/read-replica-BJAUZwWe.js +201 -0
  24. package/dist/read-replica-BJAUZwWe.js.map +1 -0
  25. package/dist/{update-removal-73OUGFVU.js → update-removal-Dh6W86TO.js} +148 -1098
  26. package/dist/update-removal-Dh6W86TO.js.map +1 -0
  27. package/dist/{version-CO5muce9.js → version-BxcTCG5i.js} +2 -2
  28. package/dist/{version-CO5muce9.js.map → version-BxcTCG5i.js.map} +1 -1
  29. package/package.json +1 -1
  30. package/dist/asg-provider-Gu-qQLG9.js.map +0 -1
  31. package/dist/deploy-engine-BktCSZdi.js.map +0 -1
  32. package/dist/iam-role-provider-BJ5XgxFH.js.map +0 -1
  33. package/dist/neptune-provider-6SGPWYUE.js.map +0 -1
  34. package/dist/program-Dm0zFrcG.js.map +0 -1
  35. package/dist/provider-classes-BDPm7luc.js.map +0 -1
  36. package/dist/rds-provider--9aIoAY-.js.map +0 -1
  37. package/dist/update-removal-73OUGFVU.js.map +0 -1
@@ -1,8 +1,9 @@
1
1
  import { f as __exportAll, l as s3ClientDefaults, r as getAwsClients } from "./aws-clients-ez_oXu6x.js";
2
2
  import { $ as safeMsg, A as currentNameGeneration, B as SAFE_MSG_ALTERED_CHAR, D as looksLikeCdkdGeneratedName, E as generateResourceNameWithFallback, F as isNameGeneration, H as STACK_REF_MAX_CODE_POINTS, I as withNameGeneration, J as displaySafe, K as displayAwsMessage, L as withSkipPrefix, M as getCurrentStackInstanceId, N as getCurrentStackName, Q as plainIdentOr, R as withStackScope, U as UNRENDERABLE, V as SECRET_REF_MAX_CODE_POINTS, W as asIsMessage, X as isPasteableIdent, Y as displayStackName, _ as explicitNamePropertyFor, a as safeStringify$1, b as withoutGeneratedFallbackName, c as isStdoutReservedForPayload, f as currentLogLineMasker, g as applyDefaultNameForFallback, h as alternateNamePropertiesFor, j as getCurrentSkipPrefix, k as stackInstanceNameSuffix, m as getLiveRenderer, n as describeAwsFailure, nt as truncateCodePoints, p as installLogLineMaskerSource, q as displayIdent, s as getLogger, t as VERBOSE_POINTER, tt as terminalSafe, v as fallbackNamePropertyFor, y as generatedNameFor, z as withStackScopeBeforeStateRead } from "./aws-failure-text-CoS1huLy.js";
3
- import { $n as isThrottlingError, An as isUpdateUnsupportedError, Ar as shellBoundedDisplay, At as segmentAfterAnchor, B as resolveExplicitPhysicalId, Bn as stripControlChars, Cr as commandHole, Ct as canonicalizeRoute53QueryName, Dn as ResourceUpdateNotSupportedError, Dr as physicalIdShownBesideCommand, Dt as logicalIdShown, Er as pasteableCommand, F as isQuotableImportValue, Fn as isReplayedNameCollisionFrom, Ft as maskDeep, Gn as isAmbiguousOutcomeError, Gt as isAuxiliaryMarkOf, H as assertRegionMatch, Ht as createdResourceIdentityBeforeFailure, I as normalizeAwsTagsToCfn, It as maskerOrIdentity, J as compensateProtectionFlip, Jn as isRetryableTransientError, Kt as markAuxiliaryFailure, L as quotedRemedyLogicalId, Ln as markReplayMayCollide, Lt as withDerivedNameMasks, Mn as isNameCollisionErrorFrom, Mr as withheldTargetClause, Mt as createMaskedLogSinks, Nn as isNameCooldownError, Nt as createMaskedRetryLogger, Or as plainOrDescribed, Pn as isRecreateRetryableError, Pt as isSecretDerivedValue, Qn as isMarkedNonRetryable, R as refusalTypeShown, Rn as relayedNameCollision, Rt as RETRY_AUXILIARY_OWNER, Sn as MacroExpansionError, Sr as UNSHOWABLE_VALUE, St as startInterruptWatch, Tr as isInertUnquoted, Tt as compositeIdSeparatorRefusal, U as isMarkedNotGone, Un as formatRetryClassificationSignals, Ut as hasCreatedBeforeFailure, V as RESOURCE_NOT_FOUND, Vt as createdBeforeFailure, W as markNotGone, Wn as isAmbiguousCcHandlerErrorCode, Wt as isAuxiliaryFailure, X as deleteWithProtectionCompensation, Xn as retryClassificationText, Xt as UNREPRODUCIBLE_LOCK_CLAUSE, Yn as isTransientServerError, Yt as replayMadeAnotherResource, Zt as buildForceUnlockCommand, _n as normalizeAwsError, _r as SynthesisError, _t as monotonicNowMs, an as CUSTOM_RESOURCE_RESPONSE_PREFIX, ar as IntrinsicResolutionRefusalError, at as runDeleteAttempt, br as SHELL_ACTIVE, c as clearCreatedReport, cr as AssetError, ct as DELETION_PROTECTION_DOC_POINTER, dr as DeploymentNotApprovedError, en as formatLockExpiry, er as markNonRetryable, et as isTerminalDeleteFailure, f as retractCreatedResource, fn as withPasteableAwsProfile, ft as pasteableAwsCommand, g as holdsSecretDerivedEntry, gn as credentialFingerprint, gr as StateError, gt as ElapsedBudgetRegistry, hn as clientDefaultsFor, hr as ResourceTimeoutError, ht as ElapsedBudget, in as sanitizeRecoveryValue, ir as DynamicReferenceRegionAmbiguousError, j as withoutServerErrorRetries, jn as hasReplayMayCollide, jr as shellQuote, jt as stateOrphanRecordRemedy, kr as quotedOrDescribed, kt as resourceTypeShown, l as collectCreatedResources, lr as CdkdError, mn as ambientCredentialConfig, mr as ProvisioningError, n as prepareRemovalForUpdate, nn as formatLockOwner, nr as wrapMaskedAwsError, nt as observeThenDisableProtection, o as withoutInjectedRemovals, on as DEFAULT_STATE_PREFIX, or as MalformedProducerRecordRefusalError, pn as ambientClientDefaults, pr as LockError, pt as protectedReplacementAdvice, q as ProtectionFlipRegistry, qn as isIamPropagationError, qt as markCreatedBeforeFailure, r as removalWarning, rn as recoveryCommandFlags, rr as CrossAccountSecretRefusalError, rt as protectionFlipKey, s as CreatedResourceSink, sn as injectiveKey, sr as AccountIdUnavailableError, tn as formatLockOperation, tr as markRedactedCause, u as reportCreatedResource, un as producerRecordKey, vr as isSoftAbort, wn as DependencyError, x as withUnchangedSecretPrincipalLists, xr as SHELL_ACTIVE_WHY, xt as isInterruptedWaitError, zn as escapeRegExp$3, zt as carryCreatedBeforeFailure } from "./update-removal-73OUGFVU.js";
3
+ import { $ as DeploymentNotApprovedError, B as isMarkedNonRetryable, C as isReplayedNameCollisionFrom, D as escapeRegExp$3, E as relayedNameCollision, F as isIamPropagationError, G as CrossAccountSecretRefusalError, H as markNonRetryable, I as isRetryableTransientError, J as MalformedProducerRecordRefusalError, K as DynamicReferenceRegionAmbiguousError, L as isTransientServerError, M as isAmbiguousCcHandlerErrorCode, N as isAmbiguousOutcomeError, O as stripControlChars, R as retryClassificationText, S as isRecreateRetryableError, T as markReplayMayCollide, U as markRedactedCause, V as isThrottlingError, W as wrapMaskedAwsError, X as AssetError, Y as AccountIdUnavailableError, Z as CdkdError, _t as quotedOrDescribed, a as normalizeAwsError, at as SynthesisError, b as isNameCollisionErrorFrom, bt as withheldTargetClause, ct as SHELL_ACTIVE, dt as commandHole, f as DependencyError, gt as plainOrDescribed, h as ResourceUpdateNotSupportedError, ht as physicalIdShownBesideCommand, i as credentialFingerprint, it as StateError, j as formatRetryClassificationSignals, lt as SHELL_ACTIVE_WHY, mt as pasteableCommand, n as ambientCredentialConfig, nt as ProvisioningError, ot as isSoftAbort, pt as isInertUnquoted, q as IntrinsicResolutionRefusalError, r as clientDefaultsFor, rt as ResourceTimeoutError, t as ambientClientDefaults, tt as LockError, u as MacroExpansionError, ut as UNSHOWABLE_VALUE, v as isUpdateUnsupportedError, vt as shellBoundedDisplay, x as isNameCooldownError, y as hasReplayMayCollide, yt as shellQuote } from "./ambient-client-defaults-B9bnuob2.js";
4
4
  import { a as setAssumedRoleCredentials, c as ambientRegion, i as getPreAssumeEnvCredentials, n as awsClientDefaults, o as setPreAssumeEnvCredentials, r as getAssumedRoleCredentials, s as quietS3Logger, t as SECOND_ROLE_PUBLISH_REFUSAL } from "./aws-client-defaults-BLXFsfMa.js";
5
- import { t as getCdkdVersion } from "./version-CO5muce9.js";
5
+ import { At as segmentAfterAnchor, B as resolveExplicitPhysicalId, Ct as canonicalizeRoute53QueryName, Dt as logicalIdShown, F as isQuotableImportValue, Ft as maskDeep, G as compensateProtectionFlip, Gt as isAuxiliaryMarkOf, H as assertRegionMatch, Ht as createdResourceIdentityBeforeFailure, I as normalizeAwsTagsToCfn, It as maskerOrIdentity, J as observeThenDisableProtection, K as deleteWithProtectionCompensation, Kt as markAuxiliaryFailure, L as quotedRemedyLogicalId, Lt as withDerivedNameMasks, Mt as createMaskedLogSinks, Nt as createMaskedRetryLogger, Pt as isSecretDerivedValue, R as refusalTypeShown, Rt as RETRY_AUXILIARY_OWNER, St as startInterruptWatch, Tt as compositeIdSeparatorRefusal, U as isMarkedNotGone, Ut as hasCreatedBeforeFailure, V as RESOURCE_NOT_FOUND, Vt as createdBeforeFailure, W as markNotGone, Wt as isAuxiliaryFailure, Xt as UNREPRODUCIBLE_LOCK_CLAUSE, Yt as replayMadeAnotherResource, Zt as buildForceUnlockCommand, an as CUSTOM_RESOURCE_RESPONSE_PREFIX, at as isTerminalDeleteFailure, c as clearCreatedReport, ct as ElapsedBudget, dt as DELETION_PROTECTION_DOC_POINTER, en as formatLockExpiry, f as retractCreatedResource, fn as withPasteableAwsProfile, g as holdsSecretDerivedEntry, gt as protectedReplacementAdvice, ht as pasteableAwsCommand, in as sanitizeRecoveryValue, it as ProtectionFlipRegistry, j as withoutServerErrorRetries, jt as stateOrphanRecordRemedy, kt as resourceTypeShown, l as collectCreatedResources, lt as ElapsedBudgetRegistry, n as prepareRemovalForUpdate, nn as formatLockOwner, o as withoutInjectedRemovals, on as DEFAULT_STATE_PREFIX, ot as protectionFlipKey, qt as markCreatedBeforeFailure, r as removalWarning, rn as recoveryCommandFlags, s as CreatedResourceSink, sn as injectiveKey, st as runDeleteAttempt, tn as formatLockOperation, u as reportCreatedResource, un as producerRecordKey, ut as monotonicNowMs, x as withUnchangedSecretPrincipalLists, xt as isInterruptedWaitError, zt as carryCreatedBeforeFailure } from "./update-removal-Dh6W86TO.js";
6
+ import { t as getCdkdVersion } from "./version-BxcTCG5i.js";
6
7
  import { createHash, randomUUID } from "node:crypto";
7
8
  import { AsyncLocalStorage } from "node:async_hooks";
8
9
  import { CreateBucketCommand, DeleteObjectCommand, DeleteObjectsCommand, GetBucketLifecycleConfigurationCommand, GetBucketLocationCommand, GetBucketReplicationCommand, GetObjectCommand, HeadBucketCommand, HeadObjectCommand, ListObjectVersionsCommand, ListObjectsV2Command, NoSuchKey, PutBucketEncryptionCommand, PutBucketLifecycleConfigurationCommand, PutBucketPolicyCommand, PutObjectCommand, PutPublicAccessBlockCommand, S3Client, S3ServiceException } from "@aws-sdk/client-s3";
@@ -5585,24 +5586,7 @@ function renderPhaseTimings() {
5585
5586
  return lines;
5586
5587
  }
5587
5588
 
5588
- // src/types/state.ts
5589
- const STATE_SCHEMA_VERSIONS_READABLE = [
5590
- 1,
5591
- 2,
5592
- 3,
5593
- 4,
5594
- 5,
5595
- 6,
5596
- 7,
5597
- 8,
5598
- 9,
5599
- 10,
5600
- 11,
5601
- 12,
5602
- 13,
5603
- 14,
5604
- 15
5605
- ];
5589
+ // src/types/state/resource-state.ts
5606
5590
  function hasUnverifiableParameterRefusal(record) {
5607
5591
  return record?.observedBaselineRefused === true && record.observedBaselineRefusalReason === "unverifiable-parameter";
5608
5592
  }
@@ -5610,6 +5594,8 @@ function hasReasonlessBaselineRefusal(record) {
5610
5594
  const reason = record?.observedBaselineRefusalReason;
5611
5595
  return record?.observedBaselineRefused === true && reason !== "unverifiable-parameter" && reason !== "incomplete-resolution";
5612
5596
  }
5597
+
5598
+ // src/types/state/helpers.ts
5613
5599
  function shouldRetainResource(deletionPolicy) {
5614
5600
  return deletionPolicy === "Retain" || deletionPolicy === "RetainExceptOnCreate";
5615
5601
  }
@@ -5672,6 +5658,25 @@ function orphansAfterRollback(previous, newlyOrphaned) {
5672
5658
  return { orphans: [...byLogicalId.values()] };
5673
5659
  }
5674
5660
 
5661
+ // src/types/state.ts
5662
+ const STATE_SCHEMA_VERSIONS_READABLE = [
5663
+ 1,
5664
+ 2,
5665
+ 3,
5666
+ 4,
5667
+ 5,
5668
+ 6,
5669
+ 7,
5670
+ 8,
5671
+ 9,
5672
+ 10,
5673
+ 11,
5674
+ 12,
5675
+ 13,
5676
+ 14,
5677
+ 15
5678
+ ];
5679
+
5675
5680
  // src/state/create-token-ledger.ts
5676
5681
  const CREATE_TOKEN_LEDGER_VERSION = 1;
5677
5682
  function emptyCreateTokenLedger(nonce) {
@@ -15651,6 +15656,7 @@ const PROPERTY_COVERAGE_BY_TYPE = /* @__PURE__ */ new Map([
15651
15656
  }],
15652
15657
  ["AWS::RDS::DBCluster", {
15653
15658
  handled: /* @__PURE__ */ new Set([
15659
+ "AllocatedStorage",
15654
15660
  "AssociatedRoles",
15655
15661
  "AutoMinorVersionUpgrade",
15656
15662
  "AvailabilityZones",
@@ -15661,6 +15667,7 @@ const PROPERTY_COVERAGE_BY_TYPE = /* @__PURE__ */ new Map([
15661
15667
  "DatabaseInsightsMode",
15662
15668
  "DatabaseName",
15663
15669
  "DBClusterIdentifier",
15670
+ "DBClusterInstanceClass",
15664
15671
  "DBClusterParameterGroupName",
15665
15672
  "DBSubnetGroupName",
15666
15673
  "DeletionProtection",
@@ -15673,6 +15680,7 @@ const PROPERTY_COVERAGE_BY_TYPE = /* @__PURE__ */ new Map([
15673
15680
  "EngineMode",
15674
15681
  "EngineVersion",
15675
15682
  "GlobalClusterIdentifier",
15683
+ "Iops",
15676
15684
  "KmsKeyId",
15677
15685
  "ManageMasterUserPassword",
15678
15686
  "MasterUserAuthenticationType",
@@ -15696,15 +15704,12 @@ const PROPERTY_COVERAGE_BY_TYPE = /* @__PURE__ */ new Map([
15696
15704
  "VpcSecurityGroupIds"
15697
15705
  ]),
15698
15706
  sdkUnwired: /* @__PURE__ */ new Map([
15699
- ["AllocatedStorage", "not yet implemented by cdkd"],
15700
- ["DBClusterInstanceClass", "not yet implemented by cdkd"],
15701
15707
  ["DBInstanceParameterGroupName", "not yet implemented by cdkd"],
15702
15708
  ["DBSystemId", "reserved for future use, per the CloudFormation schema (cloudformation:DescribeType, us-east-1, 2026-11-07); no observable behaviour to wire. Kept unhandled so a template declaring it keeps its Cloud Control route"],
15703
15709
  ["DeleteAutomatedBackups", "delete-time flag, sent on the delete when the record carries it; kept unhandled so a template declaring it keeps its Cloud Control route. Final snapshots are governed by DeletionPolicy: Snapshot, which this flag does not control"],
15704
15710
  ["Domain", "not yet implemented by cdkd"],
15705
15711
  ["DomainIAMRoleName", "not yet implemented by cdkd"],
15706
15712
  ["EnableGlobalWriteForwarding", "not yet implemented by cdkd"],
15707
- ["Iops", "not yet implemented by cdkd"],
15708
15713
  ["ReplicationSourceIdentifier", "not yet implemented by cdkd"],
15709
15714
  ["RestoreToTime", "not yet implemented by cdkd"],
15710
15715
  ["RestoreType", "not yet implemented by cdkd"],
@@ -15784,6 +15789,7 @@ const PROPERTY_COVERAGE_BY_TYPE = /* @__PURE__ */ new Map([
15784
15789
  "PreferredMaintenanceWindow",
15785
15790
  "PromotionTier",
15786
15791
  "PubliclyAccessible",
15792
+ "SourceDBInstanceIdentifier",
15787
15793
  "StorageEncrypted",
15788
15794
  "StorageThroughput",
15789
15795
  "StorageType",
@@ -15816,7 +15822,6 @@ const PROPERTY_COVERAGE_BY_TYPE = /* @__PURE__ */ new Map([
15816
15822
  ["RestoreTime", "not yet implemented by cdkd"],
15817
15823
  ["SourceDBClusterIdentifier", "not yet implemented by cdkd"],
15818
15824
  ["SourceDBInstanceAutomatedBackupsArn", "not yet implemented by cdkd"],
15819
- ["SourceDBInstanceIdentifier", "not yet implemented by cdkd"],
15820
15825
  ["SourceDbiResourceId", "not yet implemented by cdkd"],
15821
15826
  ["SourceRegion", "not yet implemented by cdkd"],
15822
15827
  ["TdeCredentialArn", "not yet implemented by cdkd"],
@@ -28483,7 +28488,81 @@ function deleteIndeterminateGuards(result) {
28483
28488
  return out;
28484
28489
  }
28485
28490
 
28486
- // src/deployment/inline-policy-claims.ts
28491
+ // src/deployment/inline-policy-claims/names.ts
28492
+ function sameIamName(a, b) {
28493
+ return typeof a === "string" && IAM_NAME.test(a) && a.toLowerCase() === b.toLowerCase();
28494
+ }
28495
+ function removalKey(kind, principal, policyName) {
28496
+ return JSON.stringify([
28497
+ kind,
28498
+ principal.toLowerCase(),
28499
+ policyName.toLowerCase()
28500
+ ]);
28501
+ }
28502
+ const IAM_NAME = /^[\w+=,.@-]+$/;
28503
+ const POLICY_LIST_FIELDS = {
28504
+ role: "Roles",
28505
+ group: "Groups",
28506
+ user: "Users"
28507
+ };
28508
+ const PRINCIPAL_KINDS = {
28509
+ "AWS::IAM::Role": "role",
28510
+ "AWS::IAM::Group": "group",
28511
+ "AWS::IAM::User": "user"
28512
+ };
28513
+ const STANDALONE_POLICY_KINDS = {
28514
+ "AWS::IAM::RolePolicy": "role",
28515
+ "AWS::IAM::GroupPolicy": "group",
28516
+ "AWS::IAM::UserPolicy": "user"
28517
+ };
28518
+ function isStandaloneInlinePolicyType(resourceType) {
28519
+ return Object.hasOwn(STANDALONE_POLICY_KINDS, resourceType);
28520
+ }
28521
+ function standaloneInlinePolicyOf(resourceType, properties) {
28522
+ if (!isStandaloneInlinePolicyType(resourceType)) return void 0;
28523
+ const kind = STANDALONE_POLICY_KINDS[resourceType];
28524
+ const props = properties ?? {};
28525
+ return {
28526
+ kind,
28527
+ principal: props[PRINCIPAL_NAME_FIELDS[kind]],
28528
+ policyName: props["PolicyName"]
28529
+ };
28530
+ }
28531
+ function standaloneInlinePolicyHandedOff(resourceType, properties, claimed, physicalId) {
28532
+ if (claimed === void 0) return false;
28533
+ const target = standaloneInlinePolicyOf(resourceType, properties);
28534
+ if (target === void 0) return false;
28535
+ const { kind, principal, policyName } = target;
28536
+ if (typeof principal !== "string" || !IAM_NAME.test(principal)) return false;
28537
+ if (typeof policyName !== "string" || !IAM_NAME.test(policyName)) return false;
28538
+ if (physicalId !== void 0 && physicalId.toLowerCase() !== `${policyName}|${principal}`.toLowerCase()) return false;
28539
+ return claimed(kind, principal, policyName) === true;
28540
+ }
28541
+ function isInlinePolicyPrincipalType(resourceType) {
28542
+ return Object.hasOwn(PRINCIPAL_KINDS, resourceType);
28543
+ }
28544
+ function principalKindOf(resourceType) {
28545
+ return Object.hasOwn(PRINCIPAL_KINDS, resourceType) ? PRINCIPAL_KINDS[resourceType] : void 0;
28546
+ }
28547
+ const ANY = "*";
28548
+ const PRINCIPAL_NAME_FIELDS = {
28549
+ role: "RoleName",
28550
+ group: "GroupName",
28551
+ user: "UserName"
28552
+ };
28553
+ function nameKey(value) {
28554
+ return typeof value === "string" && IAM_NAME.test(value) ? value.toLowerCase() : "*";
28555
+ }
28556
+ function policiesNames(policies) {
28557
+ if (policies === void 0 || policies === null) return [];
28558
+ if (!Array.isArray(policies)) return ["*"];
28559
+ return policies.map((entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry) ? nameKey(entry["PolicyName"]) : "*");
28560
+ }
28561
+ function ownPoliciesChange(change) {
28562
+ return (change?.propertyChanges ?? []).some((c) => c.path === "Policies" && c.inPlacePropagated !== true && c.replacementPropagated !== true);
28563
+ }
28564
+
28565
+ // src/deployment/inline-policy-claims/claimed.ts
28487
28566
  function isInlinePolicyClaimedByCompletedWriter(args, kind, principal, policyName) {
28488
28567
  const { selfLogicalId, writers, changes, stateResources } = args;
28489
28568
  for (const [lid, write] of writers) {
@@ -28512,6 +28591,8 @@ function isInlinePolicyClaimedByCompletedWriter(args, kind, principal, policyNam
28512
28591
  }
28513
28592
  return false;
28514
28593
  }
28594
+
28595
+ // src/deployment/inline-policy-claims/rollback-writers.ts
28515
28596
  var RollbackInlinePolicyWriters = class {
28516
28597
  entries = /* @__PURE__ */ new Map();
28517
28598
  removals = /* @__PURE__ */ new Map();
@@ -28661,95 +28742,28 @@ function inlinePolicyHolders(stateResources, kind, principal, policyName) {
28661
28742
  unreadable: [...new Set(unreadable)]
28662
28743
  };
28663
28744
  }
28664
- function sameIamName(a, b) {
28665
- return typeof a === "string" && IAM_NAME.test(a) && a.toLowerCase() === b.toLowerCase();
28666
- }
28667
- function removalKey(kind, principal, policyName) {
28668
- return JSON.stringify([
28669
- kind,
28670
- principal.toLowerCase(),
28671
- policyName.toLowerCase()
28672
- ]);
28673
- }
28674
- const IAM_NAME = /^[\w+=,.@-]+$/;
28675
- const POLICY_LIST_FIELDS = {
28676
- role: "Roles",
28677
- group: "Groups",
28678
- user: "Users"
28679
- };
28680
- const PRINCIPAL_KINDS = {
28681
- "AWS::IAM::Role": "role",
28682
- "AWS::IAM::Group": "group",
28683
- "AWS::IAM::User": "user"
28684
- };
28685
- const STANDALONE_POLICY_KINDS = {
28686
- "AWS::IAM::RolePolicy": "role",
28687
- "AWS::IAM::GroupPolicy": "group",
28688
- "AWS::IAM::UserPolicy": "user"
28689
- };
28690
- function isStandaloneInlinePolicyType(resourceType) {
28691
- return Object.hasOwn(STANDALONE_POLICY_KINDS, resourceType);
28692
- }
28693
- function standaloneInlinePolicyOf(resourceType, properties) {
28694
- if (!isStandaloneInlinePolicyType(resourceType)) return void 0;
28695
- const kind = STANDALONE_POLICY_KINDS[resourceType];
28696
- const props = properties ?? {};
28697
- return {
28698
- kind,
28699
- principal: props[PRINCIPAL_NAME_FIELDS[kind]],
28700
- policyName: props["PolicyName"]
28701
- };
28702
- }
28703
- function standaloneInlinePolicyHandedOff(resourceType, properties, claimed, physicalId) {
28704
- if (claimed === void 0) return false;
28705
- const target = standaloneInlinePolicyOf(resourceType, properties);
28706
- if (target === void 0) return false;
28707
- const { kind, principal, policyName } = target;
28708
- if (typeof principal !== "string" || !IAM_NAME.test(principal)) return false;
28709
- if (typeof policyName !== "string" || !IAM_NAME.test(policyName)) return false;
28710
- if (physicalId !== void 0 && physicalId.toLowerCase() !== `${policyName}|${principal}`.toLowerCase()) return false;
28711
- return claimed(kind, principal, policyName) === true;
28712
- }
28713
- function isInlinePolicyPrincipalType(resourceType) {
28714
- return Object.hasOwn(PRINCIPAL_KINDS, resourceType);
28715
- }
28716
- function principalKindOf(resourceType) {
28717
- return Object.hasOwn(PRINCIPAL_KINDS, resourceType) ? PRINCIPAL_KINDS[resourceType] : void 0;
28718
- }
28719
- const ANY = "*";
28720
- const PRINCIPAL_NAME_FIELDS = {
28721
- role: "RoleName",
28722
- group: "GroupName",
28723
- user: "UserName"
28724
- };
28725
- function nameKey(value) {
28726
- return typeof value === "string" && IAM_NAME.test(value) ? value.toLowerCase() : ANY;
28727
- }
28745
+
28746
+ // src/deployment/inline-policy-claims/order-writers.ts
28728
28747
  function templatePrincipalKeys(entry, kind, templateResources, stateResources) {
28729
28748
  if (typeof entry === "string") return [nameKey(entry)];
28730
28749
  const ref = typeof entry === "object" && entry !== null && !Array.isArray(entry) ? entry["Ref"] : void 0;
28731
- if (typeof ref !== "string" || !Object.hasOwn(templateResources, ref)) return [ANY];
28750
+ if (typeof ref !== "string" || !Object.hasOwn(templateResources, ref)) return ["*"];
28732
28751
  const target = templateResources[ref];
28733
- if (principalKindOf(target.Type) !== kind) return [ANY];
28752
+ if (principalKindOf(target.Type) !== kind) return ["*"];
28734
28753
  return principalSelfKeys(ref, kind, target, stateResources);
28735
28754
  }
28736
28755
  function principalSelfKeys(logicalId, kind, template, stateResources) {
28737
28756
  const keys = [`ref:${logicalId}`];
28738
28757
  const declared = template?.Properties?.[PRINCIPAL_NAME_FIELDS[kind]];
28739
28758
  const declaredKey = nameKey(declared);
28740
- if (declaredKey !== ANY) keys.push(declaredKey);
28759
+ if (declaredKey !== "*") keys.push(declaredKey);
28741
28760
  const record = Object.hasOwn(stateResources, logicalId) ? stateResources[logicalId] : void 0;
28742
28761
  if (record !== void 0 && principalKindOf(record.resourceType) === kind) {
28743
28762
  const recordedKey = nameKey(record.physicalId);
28744
- if (recordedKey !== ANY) keys.push(recordedKey);
28763
+ if (recordedKey !== "*") keys.push(recordedKey);
28745
28764
  }
28746
28765
  return keys;
28747
28766
  }
28748
- function policiesNames(policies) {
28749
- if (policies === void 0 || policies === null) return [];
28750
- if (!Array.isArray(policies)) return [ANY];
28751
- return policies.map((entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry) ? nameKey(entry["PolicyName"]) : ANY);
28752
- }
28753
28767
  function standaloneClaimSides(logicalId, change, templateResources, stateResources) {
28754
28768
  const template = Object.hasOwn(templateResources, logicalId) ? templateResources[logicalId] : void 0;
28755
28769
  const desired = standaloneInlinePolicyOf(change.resourceType, template?.Properties ?? {});
@@ -28806,10 +28820,10 @@ function inlinePolicyClaimsOf(logicalId, change, templateResources, stateResourc
28806
28820
  const principals = [];
28807
28821
  const listed = desired[field];
28808
28822
  if (Array.isArray(listed)) for (const entry of listed) principals.push(...templatePrincipalKeys(entry, kind, templateResources, stateResources));
28809
- else if (listed !== void 0) principals.push(ANY);
28823
+ else if (listed !== void 0) principals.push("*");
28810
28824
  const held = old[field];
28811
28825
  if (Array.isArray(held)) principals.push(...held.map(nameKey));
28812
- else if (held !== void 0 && held !== null) principals.push(ANY);
28826
+ else if (held !== void 0 && held !== null) principals.push("*");
28813
28827
  cross(kind, principals, names);
28814
28828
  }
28815
28829
  return claims;
@@ -28835,7 +28849,7 @@ function orderInlinePolicyWriters(args) {
28835
28849
  id,
28836
28850
  claim
28837
28851
  });
28838
- if (claim.principal === ANY || claim.name === ANY) {
28852
+ if (claim.principal === "*" || claim.name === "*") {
28839
28853
  loose.push({
28840
28854
  id,
28841
28855
  claim
@@ -28854,7 +28868,7 @@ function orderInlinePolicyWriters(args) {
28854
28868
  const principalRows = new Set(writers.filter((id) => isInlinePolicyPrincipalType(changes.get(id).resourceType)));
28855
28869
  const standaloneRows = new Set(writers.filter((id) => isStandaloneInlinePolicyType(changes.get(id).resourceType)));
28856
28870
  const sides = new Map([...standaloneRows].map((id) => [id, standaloneClaimSides(id, changes.get(id), templateResources, stateResources)]));
28857
- const sameClaim = (p, q) => p.kind === q.kind && (p.principal === ANY || q.principal === ANY || p.principal === q.principal) && (p.name === ANY || q.name === ANY || p.name === q.name);
28871
+ const sameClaim = (p, q) => p.kind === q.kind && (p.principal === "*" || q.principal === "*" || p.principal === q.principal) && (p.name === "*" || q.name === "*" || p.name === q.name);
28858
28872
  const releasesFor = (a, b) => sides.get(a).old.some((o) => sides.get(b).desired.some((d) => sameClaim(o, d)));
28859
28873
  const pairs = /* @__PURE__ */ new Map();
28860
28874
  const pair = (a, b) => {
@@ -28875,7 +28889,7 @@ function orderInlinePolicyWriters(args) {
28875
28889
  const list = [...ids];
28876
28890
  for (let i = 0; i < list.length; i++) for (let j = i + 1; j < list.length; j++) pair(list[i], list[j]);
28877
28891
  }
28878
- const meets = (a, b) => a === ANY || b === ANY || a === b;
28892
+ const meets = (a, b) => a === "*" || b === "*" || a === b;
28879
28893
  for (const { id, claim } of loose) for (const other of all) {
28880
28894
  if (other.claim.kind !== claim.kind) continue;
28881
28895
  if (meets(claim.principal, other.claim.principal) && meets(claim.name, other.claim.name)) pair(id, other.id);
@@ -28906,6 +28920,8 @@ function orderInlinePolicyWriters(args) {
28906
28920
  }
28907
28921
  return added;
28908
28922
  }
28923
+
28924
+ // src/deployment/inline-policy-claims/order-reversals.ts
28909
28925
  function recordInlinePolicyKeys(record) {
28910
28926
  if (record === void 0 || record === null || typeof record !== "object") return [];
28911
28927
  const props = record.properties ?? {};
@@ -28951,7 +28967,7 @@ function orderInlinePolicyReversals(replay, stateResources) {
28951
28967
  if (keys.length > 0) keysOf.set(op, new Set(keys));
28952
28968
  }
28953
28969
  if (keysOf.size < 2) return [...replay];
28954
- const meets = (a, b) => a === ANY || b === ANY || a === b;
28970
+ const meets = (a, b) => a === "*" || b === "*" || a === b;
28955
28971
  const collide = (a, b) => {
28956
28972
  for (const ka of a) {
28957
28973
  const [kindA, pA, nA] = JSON.parse(ka);
@@ -28983,9 +28999,6 @@ function orderInlinePolicyReversals(replay, stateResources) {
28983
28999
  }
28984
29000
  return order;
28985
29001
  }
28986
- function ownPoliciesChange(change) {
28987
- return (change?.propertyChanges ?? []).some((c) => c.path === "Policies" && c.inPlacePropagated !== true && c.replacementPropagated !== true);
28988
- }
28989
29002
 
28990
29003
  // src/provisioning/cc-protection-properties.ts
28991
29004
  const CC_PROTECTION_PROPERTIES = {
@@ -29094,6 +29107,7 @@ const SLOW_CC_OPERATION_TIMEOUTS = {
29094
29107
  },
29095
29108
  "AWS::RDS::DBCluster": {
29096
29109
  create: 60 * MINUTE_MS,
29110
+ update: 90 * MINUTE_MS,
29097
29111
  delete: 60 * MINUTE_MS
29098
29112
  },
29099
29113
  "AWS::DynamoDB::Table": { update: 75 * MINUTE_MS },
@@ -29366,7 +29380,7 @@ async function deleteInIdLogScope(logicalId, physicalId, resourceType, propertie
29366
29380
  const indeterminateGuard = await this.confirmDeleteTargetIdentity(logicalId, resourceType, physicalId, context);
29367
29381
  if (context?.removeProtection === true && resourceType === "AWS::AutoScaling::AutoScalingGroup") {
29368
29382
  this.logger.debug(`Delegating protected AutoScalingGroup ${logicalId} delete to the SDK ASGProvider (Cloud Control cannot force-delete a protected ASG)`);
29369
- const { ASGProvider } = await import("./asg-provider-Gu-qQLG9.js");
29383
+ const { ASGProvider } = await import("./asg-provider-pl5tnbiA.js");
29370
29384
  const delegateRegion = ambientRegion();
29371
29385
  let asgProvider = this.asgDeleteDelegates.get(delegateRegion);
29372
29386
  if (asgProvider === void 0) {
@@ -29520,7 +29534,7 @@ async function sdkDeleteDelegateInCcRegion(resourceType, logicalId, physicalId)
29520
29534
  const family = SDK_DELETE_FAMILIES.get(resourceType);
29521
29535
  const cached = this.sdkDeleteDelegates.get(family);
29522
29536
  if (cached !== void 0 && cached.region === ccRegion) return cached.provider;
29523
- const provider = family === "rds" ? new (await (import("./rds-provider--9aIoAY-.js"))).RDSProvider({ region: ccRegion }) : new (await (import("./neptune-provider-6SGPWYUE.js"))).NeptuneProvider({ region: ccRegion });
29537
+ const provider = family === "rds" ? new (await (import("./rds-provider-Ce7ua-ww.js"))).RDSProvider({ region: ccRegion }) : new (await (import("./neptune-provider-CNEMvt4t.js"))).NeptuneProvider({ region: ccRegion });
29524
29538
  this.sdkDeleteDelegates.set(family, {
29525
29539
  region: ccRegion,
29526
29540
  provider
@@ -32454,6 +32468,100 @@ var CustomResourceProvider = class CustomResourceProvider {
32454
32468
  }
32455
32469
  };
32456
32470
 
32471
+ // src/provisioning/sticky-exempt-physical-id.ts
32472
+ const ECS_SERVICE_CC_ID = /^(arn:aws[-a-z]*:ecs:[a-z0-9-]+:\d{12}:service\/([A-Za-z0-9_-]+)(?:\/([A-Za-z0-9_-]+))?)\|([^|\s]+)$/;
32473
+ const CLUSTER_ARN = /^arn:aws[-a-z]*:ecs:[a-z0-9-]+:\d{12}:cluster\/([A-Za-z0-9_-]+)$/;
32474
+ const CLUSTER_NAME = /^[A-Za-z0-9_-]+$/;
32475
+ function ecsServiceSdkPhysicalId(ccPhysicalId) {
32476
+ const match = ECS_SERVICE_CC_ID.exec(ccPhysicalId);
32477
+ if (match === null) throw new Error("its recorded physical id is not the `<serviceArn>|<cluster>` form Cloud Control records for AWS::ECS::Service");
32478
+ const [, serviceArn, first, second, clusterSegment] = match;
32479
+ const clusterArn = CLUSTER_ARN.exec(clusterSegment);
32480
+ if (clusterArn === null && !CLUSTER_NAME.test(clusterSegment)) throw new Error("the cluster segment of its recorded physical id is neither a cluster name nor a cluster ARN");
32481
+ const clusterName = clusterArn === null ? clusterSegment : clusterArn[1];
32482
+ if (second !== void 0 && first !== clusterName) throw new Error("its recorded physical id names one cluster in the service ARN and another after the `|`");
32483
+ return serviceArn;
32484
+ }
32485
+
32486
+ // src/provisioning/provider-registry/routing.ts
32487
+ function getProviderFor(input) {
32488
+ const debug = (message) => {
32489
+ if (input.quiet !== true) this.logger.debug(message);
32490
+ };
32491
+ const { resourceType, properties, provisionedBy } = input;
32492
+ if (isCustomResource(resourceType)) {
32493
+ debug(`Using Custom Resource provider for ${resourceType}`);
32494
+ return {
32495
+ provider: this.customResourceProvider,
32496
+ provisionedBy: "sdk"
32497
+ };
32498
+ }
32499
+ let returningToSdk = false;
32500
+ if (provisionedBy === "cc-api") {
32501
+ if (!wouldReturnToSdkProvider({
32502
+ resourceType,
32503
+ desiredProperties: properties,
32504
+ previousProperties: input.previousProperties,
32505
+ allowedUnsupportedProperties: this.allowedUnsupportedProperties,
32506
+ forceCcApi: input.forceCcApi === true
32507
+ })) {
32508
+ debug(`Routing ${resourceType} via Cloud Control (state-recorded provisionedBy=cc-api)`);
32509
+ return {
32510
+ provider: this.cloudControlProvider,
32511
+ provisionedBy: "cc-api"
32512
+ };
32513
+ }
32514
+ returningToSdk = true;
32515
+ }
32516
+ const specificProvider = this.providers.get(resourceType);
32517
+ if (specificProvider) {
32518
+ const actionableDrops = findActionableSdkUnwired(resourceType, properties, this.allowedUnsupportedProperties, input.previousProperties);
32519
+ if (actionableDrops.length === 0) {
32520
+ debug(`Using specific SDK provider for ${resourceType}`);
32521
+ if (returningToSdk) {
32522
+ debug(`${resourceType} is returning to its SDK provider from a state-recorded cc-api route; the resource is updated in place`);
32523
+ return {
32524
+ provider: specificProvider,
32525
+ provisionedBy: "sdk",
32526
+ sdkMigration: true
32527
+ };
32528
+ }
32529
+ return {
32530
+ provider: specificProvider,
32531
+ provisionedBy: "sdk"
32532
+ };
32533
+ }
32534
+ const unroutable = this.ccRouteUnavailableReason(resourceType);
32535
+ if (unroutable !== void 0) throw new Error(this.buildUnroutableSdkUnwiredMessage(resourceType, actionableDrops, unroutable));
32536
+ debug(`Auto-routing ${resourceType} via Cloud Control (SDK-unwired properties: ${actionableDrops.map((d) => d.property).join(", ")})`);
32537
+ return {
32538
+ provider: this.cloudControlProvider,
32539
+ provisionedBy: "cc-api",
32540
+ ccRouteReason: { properties: actionableDrops.map((d) => d.property) }
32541
+ };
32542
+ }
32543
+ if (CloudControlProvider.isSupportedResourceType(resourceType)) {
32544
+ debug(`Using Cloud Control API provider for ${resourceType}`);
32545
+ return {
32546
+ provider: this.cloudControlProvider,
32547
+ provisionedBy: "cc-api"
32548
+ };
32549
+ }
32550
+ if (this.allowedUnsupportedTypes.has(resourceType)) {
32551
+ debug(`Routing escape-hatch-allowed type ${resourceType} through Cloud Control API`);
32552
+ return {
32553
+ provider: this.cloudControlProvider,
32554
+ provisionedBy: "cc-api"
32555
+ };
32556
+ }
32557
+ throw new Error(`No provider available for resource type: ${resourceType}. This resource type is not supported by Cloud Control API and no SDK provider is registered.`);
32558
+ }
32559
+ function buildUnroutableSdkUnwiredMessage(resourceType, drops, reason) {
32560
+ const details = drops.map((d) => safeMsg` - ${d.property}: ${d.rationale}`).join("\n");
32561
+ const overrideHint = drops.map((d) => safeMsg`${resourceType}:${d.property}`).join(",");
32562
+ return safeMsg`${resourceType} uses properties cdkd's SDK Provider does not handle, and ` + safeMsg`this type cannot fall back to Cloud Control API (${reason}):\n` + `${details}\nRemove the properties, or force the SDK provider path and accept leaving them unwritten via --prefer-sdk-route ${overrideHint} (the provider may still reject the resource if the property is required).`;
32563
+ }
32564
+
32457
32565
  // src/provisioning/mutually-exclusive-properties.ts
32458
32566
  const MUTUALLY_EXCLUSIVE_PROPERTIES = /* @__PURE__ */ new Map([["AWS::EC2::Route", [{
32459
32567
  properties: [
@@ -34227,19 +34335,125 @@ function validatePropertyShapes(resources) {
34227
34335
  throw new Error("Properties validation failed: the following resources declare a property whose kind contradicts the resource type's schema:\n" + lines.join("\n") + "\n\nCloudFormation rejects these templates too. Give each property a list where its schema expects a list and an object where it expects an object.");
34228
34336
  }
34229
34337
 
34230
- // src/provisioning/sticky-exempt-physical-id.ts
34231
- const ECS_SERVICE_CC_ID = /^(arn:aws[-a-z]*:ecs:[a-z0-9-]+:\d{12}:service\/([A-Za-z0-9_-]+)(?:\/([A-Za-z0-9_-]+))?)\|([^|\s]+)$/;
34232
- const CLUSTER_ARN = /^arn:aws[-a-z]*:ecs:[a-z0-9-]+:\d{12}:cluster\/([A-Za-z0-9_-]+)$/;
34233
- const CLUSTER_NAME = /^[A-Za-z0-9_-]+$/;
34234
- function ecsServiceSdkPhysicalId(ccPhysicalId) {
34235
- const match = ECS_SERVICE_CC_ID.exec(ccPhysicalId);
34236
- if (match === null) throw new Error("its recorded physical id is not the `<serviceArn>|<cluster>` form Cloud Control records for AWS::ECS::Service");
34237
- const [, serviceArn, first, second, clusterSegment] = match;
34238
- const clusterArn = CLUSTER_ARN.exec(clusterSegment);
34239
- if (clusterArn === null && !CLUSTER_NAME.test(clusterSegment)) throw new Error("the cluster segment of its recorded physical id is neither a cluster name nor a cluster ARN");
34240
- const clusterName = clusterArn === null ? clusterSegment : clusterArn[1];
34241
- if (second !== void 0 && first !== clusterName) throw new Error("its recorded physical id names one cluster in the service ARN and another after the `|`");
34242
- return serviceArn;
34338
+ // src/provisioning/provider-registry/validate.ts
34339
+ function validateResourceTypes(resourceTypes) {
34340
+ const unsupportedTypes = [];
34341
+ for (const resourceType of resourceTypes) if (!this.hasProvider(resourceType)) unsupportedTypes.push(resourceType);
34342
+ if (unsupportedTypes.length > 0) {
34343
+ const details = unsupportedTypes.map((type) => {
34344
+ return ` - ${type}\n ${isNonProvisionable(type) ? "AWS reports this type as NON_PROVISIONABLE (Cloud Control API cannot manage it) and cdkd has no SDK provider for it." : "cdkd does not currently support this type — no SDK provider is registered, and the type is either on cdkd's Cloud Control blocklist (pending a dedicated SDK provider) or is not an AWS:: namespace."}\n Request support: ${unsupportedTypeIssueUrl(type)}`;
34345
+ }).join("\n");
34346
+ throw new Error(`The following resource types are not supported by cdkd:\n` + details + `\n\nTo attempt deployment anyway (Cloud Control will likely fail for NON_PROVISIONABLE types), re-run with: --allow-unsupported-types ${unsupportedTypes.join(",")}`);
34347
+ }
34348
+ this.logger.debug(`Validated ${resourceTypes.size} resource types: all have available providers`);
34349
+ }
34350
+ function validateResourceProperties(resources) {
34351
+ const materialized = [...resources];
34352
+ validatePropertyShapes(materialized);
34353
+ this.validateMutuallyExclusiveProperties(materialized);
34354
+ this.validateNestedRequiredProperties(materialized);
34355
+ this.validateCustomResourceSecureReferences(materialized);
34356
+ this.reportSdkUnwiredDecisions(materialized);
34357
+ }
34358
+ function validateMutuallyExclusiveProperties(resources) {
34359
+ const lines = [];
34360
+ for (const { logicalId, resourceType, properties } of resources) for (const violation of findMutuallyExclusiveViolations(resourceType, properties)) lines.push(buildMutuallyExclusiveMessage(logicalId, violation));
34361
+ if (lines.length === 0) return;
34362
+ throw new Error(`The following resources declare mutually exclusive properties:\n` + lines.join("\n") + "\n\nCloudFormation rejects these combinations too — edit the template to declare only one of each set.");
34363
+ }
34364
+ function validateNestedRequiredProperties(resources) {
34365
+ const lines = [];
34366
+ for (const { logicalId, resourceType, properties } of resources) for (const violation of findNestedRequiredViolations(resourceType, properties)) lines.push(buildNestedRequiredMessage(logicalId, violation));
34367
+ if (lines.length === 0) return;
34368
+ throw new Error(`The following resources declare a nested property block without a member it requires:\n` + lines.join("\n") + "\n\nCloudFormation rejects these blocks too. Declare the missing members; leaving a whole block out is not a violation.");
34369
+ }
34370
+ function validateCustomResourceSecureReferences(resources) {
34371
+ const lines = [];
34372
+ for (const { logicalId, resourceType, properties } of resources) {
34373
+ const paths = findSecureReferencePaths(resourceType, properties);
34374
+ if (paths.length > 0) lines.push(buildSecureReferenceMessage(logicalId, paths));
34375
+ }
34376
+ if (lines.length === 0) return;
34377
+ throw new Error("The following custom resources pass a secure dynamic reference ({{resolve:secretsmanager:...}} / {{resolve:ssm-secure:...}}) in their properties:\n" + lines.join("\n") + "\n\nCloudFormation does not support secure dynamic references in custom resources, so the template is rejected before anything is resolved. Have the handler read the secret itself (pass its name or ARN instead), or use a plain {{resolve:ssm:...}} parameter for a value that is not secret.");
34378
+ }
34379
+
34380
+ // src/provisioning/provider-registry/report.ts
34381
+ function reportSdkUnwiredDecisions(resources) {
34382
+ for (const { logicalId, resourceType, properties, provisionedBy, previousProperties } of resources) {
34383
+ const drops = findSdkUnwiredProperties(resourceType, properties);
34384
+ const unrecognizedRoute = findRoutableUnrecognizedProperties(resourceType, properties, this.allowedUnsupportedProperties, previousProperties);
34385
+ const stickyCc = provisionedBy === "cc-api" && !STICKY_CC_MIGRATION_EXEMPT.has(resourceType);
34386
+ const overridden = stickyCc ? [] : findAcceptedSdkUnwired(resourceType, properties, this.allowedUnsupportedProperties, previousProperties);
34387
+ const autoRouted = [...drops.map(({ property }) => property).filter((property) => !this.allowedUnsupportedProperties.has(`${resourceType}:${property}`)), ...unrecognizedRoute].sort((a, b) => a.localeCompare(b));
34388
+ if (autoRouted.length > 0) {
34389
+ const unroutable = this.ccRouteUnavailableReason(resourceType);
34390
+ if (unroutable !== void 0) throw new Error(safeMsg`${logicalId}: ` + this.buildUnroutableSdkUnwiredMessage(resourceType, drops.filter((d) => autoRouted.includes(d.property)), unroutable));
34391
+ const propList = autoRouted.join(", ");
34392
+ const overrideHint = autoRouted.map((p) => `${resourceType}:${p}`).join(",");
34393
+ const message = `${logicalId} (${resourceType}): routing via Cloud Control API (cdkd's SDK Provider does not yet wire ${propList} — CC API will forward the full property map.${unrecognizedRoute.length === 0 ? "" : ` ${unrecognizedRoute.join(", ")} ${unrecognizedRoute.length === 1 ? "is" : "are"} not in cdkd's CFn schema snapshot: Cloud Control applies a property AWS published since, and rejects a misspelled one as CloudFormation does.`} Override via --prefer-sdk-route ${overrideHint}.)`;
34394
+ if (provisionedBy === "cc-api") this.logger.debug(message);
34395
+ else this.logger.info(message);
34396
+ }
34397
+ const named = drops.map(({ property }) => property).filter((property) => this.allowedUnsupportedProperties.has(`${resourceType}:${property}`));
34398
+ if (named.length > 0 && (stickyCc || autoRouted.length > 0)) {
34399
+ const list = named.join(", ");
34400
+ const isAre = named.length === 1 ? "is" : "are";
34401
+ const [cause, remedy] = stickyCc ? ["this resource's state record already routes it to Cloud Control (provisionedBy: cc-api), which is decided before any property is consulted", "Returning this resource to the SDK provider is a destroy-and-recreate, not a flag change — see https://cdkd.dev/cli-deploy-safety/. Widening --prefer-sdk-route alone cannot do it."] : [`${autoRouted.join(", ")} ${autoRouted.length === 1 ? "is" : "are"} not covered by it, and one uncovered property routes the whole RESOURCE to Cloud Control`, `To keep the resource on its SDK provider, add ${autoRouted.map((p) => `${resourceType}:${p}`).join(",")} to --prefer-sdk-route as well.`];
34402
+ this.logger.warn(`${logicalId} (${resourceType}): --prefer-sdk-route had no effect for ${list} — ${cause}. Cloud Control forwards the full property map, so ${list} ${isAre} written to AWS after all. ${remedy}`);
34403
+ }
34404
+ if (overridden.length > 0) {
34405
+ const createOnly = getPropertyCoverage(resourceType)?.createOnlyDrops;
34406
+ const unroutable = this.ccRouteUnavailableReason(resourceType);
34407
+ const reroutable = unroutable === void 0 ? overridden.filter((p) => createOnly?.has(p) !== true) : [];
34408
+ const needsRecreate = unroutable === void 0 ? overridden.filter((p) => createOnly?.has(p) === true) : [];
34409
+ const remedies = [];
34410
+ if (unroutable !== void 0) remedies.push(`This type cannot be routed via Cloud Control API (${unroutable}), so removing the override makes the deploy refuse at pre-flight instead of rerouting; cdkd has no route that applies ${overridden.length === 1 ? "it" : "them"} to this type.`);
34411
+ if (reroutable.length > 0) remedies.push(`Remove the override for ${reroutable.join(", ")} to route this resource via Cloud Control API instead.`);
34412
+ if (needsRecreate.length > 0) {
34413
+ const one = needsRecreate.length === 1;
34414
+ remedies.push(`${needsRecreate.join(", ")} ${one ? "is" : "are"} create-only, so removing the override does not apply ${one ? "it" : "them"} in place -- a create-only property can only be applied by recreating the resource. Where cdkd created the resource without ${one ? "it" : "them"}, a deploy without the override refuses unless something else already forces a replacement or the recreate is opted into.`);
34415
+ }
34416
+ this.logger.warn(`${logicalId} (${resourceType}): ${overridden.join(", ")} will be left unwritten (--prefer-sdk-route override accepted). ${remedies.join(" ")}`);
34417
+ }
34418
+ this.reportUnrecognizedProperties(logicalId, resourceType, properties, {
34419
+ provisionedBy,
34420
+ autoRouted: autoRouted.length > 0,
34421
+ previousProperties
34422
+ });
34423
+ }
34424
+ }
34425
+ function reportUnrecognizedProperties(logicalId, resourceType, properties, route) {
34426
+ if (route.provisionedBy === "cc-api" && !STICKY_CC_MIGRATION_EXEMPT.has(resourceType) || route.autoRouted) return;
34427
+ const unrecognized = findUnrecognizedProperties(resourceType, properties).filter((property) => !this.allowedUnsupportedProperties.has(`${resourceType}:${property}`));
34428
+ if (unrecognized.length === 0) return;
34429
+ const coverage = getPropertyCoverage(resourceType);
34430
+ const unroutable = this.ccRouteUnavailableReason(resourceType) ?? (STICKY_CC_MIGRATION_EXEMPT.get(resourceType)?.mode === "cc-broken" ? "Cloud Control's handler cannot manage this type correctly" : coverage?.ccRouteUnavailable === true ? "the type's SDK provider opts out of the Cloud Control fallback (disableCcApiFallback)" : void 0);
34431
+ const readOnly = unrecognized.filter((p) => coverage?.readOnly.has(p) === true);
34432
+ const notReadOnly = unrecognized.filter((p) => coverage?.readOnly.has(p) !== true);
34433
+ const undecided = unroutable === void 0 ? notReadOnly.filter((p) => containsIntrinsic$1(properties?.[p]) && route.previousProperties != null && typeof route.previousProperties === "object" && Object.hasOwn(route.previousProperties, p)) : [];
34434
+ const rest = notReadOnly.filter((p) => !undecided.includes(p));
34435
+ const sentences = [];
34436
+ const isAre = (names) => names.length === 1 ? "is" : "are";
34437
+ if (readOnly.length > 0) sentences.push(`${readOnly.join(", ")} ${isAre(readOnly)} read-only — an attribute AWS computes, which no engine sets (CloudFormation ignores it too); remove it.`);
34438
+ if (rest.length > 0 && unroutable !== void 0) sentences.push(`${rest.join(", ")} ${isAre(rest)} not in cdkd's CFn schema snapshot, and this type cannot be routed via Cloud Control API (${unroutable}), so cdkd has no route that applies ${rest.length === 1 ? "it" : "them"}. If it is a property AWS published since the snapshot, please report it: ${unsupportedPropertyIssueUrl(resourceType, rest[0])}.`);
34439
+ else if (rest.length > 0) sentences.push(`${rest.join(", ")} ${isAre(rest)} not in cdkd's CFn schema snapshot and unchanged since this resource was deployed on the SDK route, so it stays there and cdkd does not send ${rest.length === 1 ? "it" : "them"}. Changing ${rest.length === 1 ? "it" : "one"} routes the resource via Cloud Control API, which applies a property AWS published since the snapshot and rejects a misspelled one, as CloudFormation does.`);
34440
+ if (undecided.length > 0) sentences.push(`${undecided.join(", ")} ${isAre(undecided)} not in cdkd's CFn schema snapshot and ${undecided.length === 1 ? "its value holds" : "their values hold"} an intrinsic, so the route is decided once it resolves: a value unchanged since the SDK-route deploy stays there and is not sent, and a changed one routes via Cloud Control API.`);
34441
+ if (sentences.length === 0) return;
34442
+ const overrideHint = unrecognized.map((p) => `${resourceType}:${p}`).join(",");
34443
+ this.logger.warn(`${logicalId} (${resourceType}): ${unrecognized.length === 1 ? "a property" : "properties"} ${readOnly.length + rest.length > 0 ? "will NOT" : "may not"} reach AWS — the deploy will still report success. ${sentences.join(" ")} If the drop is intended — an addPropertyOverride escape hatch — silence this via --prefer-sdk-route ${overrideHint}.`);
34444
+ }
34445
+ function findAutoRouteHits(resources) {
34446
+ const hits = [];
34447
+ for (const { logicalId, resourceType, properties, previousProperties } of resources) {
34448
+ const actionable = findActionableSdkUnwired(resourceType, properties, this.allowedUnsupportedProperties, previousProperties);
34449
+ if (actionable.length === 0) continue;
34450
+ hits.push({
34451
+ logicalId,
34452
+ resourceType,
34453
+ properties: actionable.map((d) => d.property)
34454
+ });
34455
+ }
34456
+ return hits;
34243
34457
  }
34244
34458
 
34245
34459
  // src/provisioning/provider-registry.ts
@@ -34388,85 +34602,14 @@ var ProviderRegistry = class {
34388
34602
  this.providers.delete(resourceType);
34389
34603
  }
34390
34604
  getProviderFor(input) {
34391
- const debug = (message) => {
34392
- if (input.quiet !== true) this.logger.debug(message);
34393
- };
34394
- const { resourceType, properties, provisionedBy } = input;
34395
- if (isCustomResource(resourceType)) {
34396
- debug(`Using Custom Resource provider for ${resourceType}`);
34397
- return {
34398
- provider: this.customResourceProvider,
34399
- provisionedBy: "sdk"
34400
- };
34401
- }
34402
- let returningToSdk = false;
34403
- if (provisionedBy === "cc-api") {
34404
- if (!wouldReturnToSdkProvider({
34405
- resourceType,
34406
- desiredProperties: properties,
34407
- previousProperties: input.previousProperties,
34408
- allowedUnsupportedProperties: this.allowedUnsupportedProperties,
34409
- forceCcApi: input.forceCcApi === true
34410
- })) {
34411
- debug(`Routing ${resourceType} via Cloud Control (state-recorded provisionedBy=cc-api)`);
34412
- return {
34413
- provider: this.cloudControlProvider,
34414
- provisionedBy: "cc-api"
34415
- };
34416
- }
34417
- returningToSdk = true;
34418
- }
34419
- const specificProvider = this.providers.get(resourceType);
34420
- if (specificProvider) {
34421
- const actionableDrops = findActionableSdkUnwired(resourceType, properties, this.allowedUnsupportedProperties, input.previousProperties);
34422
- if (actionableDrops.length === 0) {
34423
- debug(`Using specific SDK provider for ${resourceType}`);
34424
- if (returningToSdk) {
34425
- debug(`${resourceType} is returning to its SDK provider from a state-recorded cc-api route; the resource is updated in place`);
34426
- return {
34427
- provider: specificProvider,
34428
- provisionedBy: "sdk",
34429
- sdkMigration: true
34430
- };
34431
- }
34432
- return {
34433
- provider: specificProvider,
34434
- provisionedBy: "sdk"
34435
- };
34436
- }
34437
- const unroutable = this.ccRouteUnavailableReason(resourceType);
34438
- if (unroutable !== void 0) throw new Error(this.buildUnroutableSdkUnwiredMessage(resourceType, actionableDrops, unroutable));
34439
- debug(`Auto-routing ${resourceType} via Cloud Control (SDK-unwired properties: ${actionableDrops.map((d) => d.property).join(", ")})`);
34440
- return {
34441
- provider: this.cloudControlProvider,
34442
- provisionedBy: "cc-api",
34443
- ccRouteReason: { properties: actionableDrops.map((d) => d.property) }
34444
- };
34445
- }
34446
- if (CloudControlProvider.isSupportedResourceType(resourceType)) {
34447
- debug(`Using Cloud Control API provider for ${resourceType}`);
34448
- return {
34449
- provider: this.cloudControlProvider,
34450
- provisionedBy: "cc-api"
34451
- };
34452
- }
34453
- if (this.allowedUnsupportedTypes.has(resourceType)) {
34454
- debug(`Routing escape-hatch-allowed type ${resourceType} through Cloud Control API`);
34455
- return {
34456
- provider: this.cloudControlProvider,
34457
- provisionedBy: "cc-api"
34458
- };
34459
- }
34460
- throw new Error(`No provider available for resource type: ${resourceType}. This resource type is not supported by Cloud Control API and no SDK provider is registered.`);
34605
+ return getProviderFor.call(this, input);
34461
34606
  }
34462
34607
  ccRouteUnavailableReason(resourceType) {
34463
34608
  if (hasNoCloudControlHandlers(resourceType)) return NO_CC_HANDLERS_REASON;
34464
34609
  if (this.providers.get(resourceType)?.disableCcApiFallback === true) return "the type's SDK provider opts out of the Cloud Control fallback (disableCcApiFallback)";
34465
34610
  }
34466
34611
  buildUnroutableSdkUnwiredMessage(resourceType, drops, reason) {
34467
- const details = drops.map((d) => safeMsg` - ${d.property}: ${d.rationale}`).join("\n");
34468
- const overrideHint = drops.map((d) => safeMsg`${resourceType}:${d.property}`).join(",");
34469
- return safeMsg`${resourceType} uses properties cdkd's SDK Provider does not handle, and ` + safeMsg`this type cannot fall back to Cloud Control API (${reason}):\n` + `${details}\nRemove the properties, or force the SDK provider path and accept leaving them unwritten via --prefer-sdk-route ${overrideHint} (the provider may still reject the resource if the property is required).`;
34612
+ return buildUnroutableSdkUnwiredMessage.call(this, resourceType, drops, reason);
34470
34613
  }
34471
34614
  getProvider(resourceType) {
34472
34615
  return this.getProviderFor({ resourceType }).provider;
@@ -34492,121 +34635,28 @@ var ProviderRegistry = class {
34492
34635
  return null;
34493
34636
  }
34494
34637
  validateResourceTypes(resourceTypes) {
34495
- const unsupportedTypes = [];
34496
- for (const resourceType of resourceTypes) if (!this.hasProvider(resourceType)) unsupportedTypes.push(resourceType);
34497
- if (unsupportedTypes.length > 0) {
34498
- const details = unsupportedTypes.map((type) => {
34499
- return ` - ${type}\n ${isNonProvisionable(type) ? "AWS reports this type as NON_PROVISIONABLE (Cloud Control API cannot manage it) and cdkd has no SDK provider for it." : "cdkd does not currently support this type — no SDK provider is registered, and the type is either on cdkd's Cloud Control blocklist (pending a dedicated SDK provider) or is not an AWS:: namespace."}\n Request support: ${unsupportedTypeIssueUrl(type)}`;
34500
- }).join("\n");
34501
- throw new Error(`The following resource types are not supported by cdkd:\n` + details + `\n\nTo attempt deployment anyway (Cloud Control will likely fail for NON_PROVISIONABLE types), re-run with: --allow-unsupported-types ${unsupportedTypes.join(",")}`);
34502
- }
34503
- this.logger.debug(`Validated ${resourceTypes.size} resource types: all have available providers`);
34638
+ return validateResourceTypes.call(this, resourceTypes);
34504
34639
  }
34505
34640
  validateResourceProperties(resources) {
34506
- const materialized = [...resources];
34507
- validatePropertyShapes(materialized);
34508
- this.validateMutuallyExclusiveProperties(materialized);
34509
- this.validateNestedRequiredProperties(materialized);
34510
- this.validateCustomResourceSecureReferences(materialized);
34511
- this.reportSdkUnwiredDecisions(materialized);
34641
+ return validateResourceProperties.call(this, resources);
34512
34642
  }
34513
34643
  validateMutuallyExclusiveProperties(resources) {
34514
- const lines = [];
34515
- for (const { logicalId, resourceType, properties } of resources) for (const violation of findMutuallyExclusiveViolations(resourceType, properties)) lines.push(buildMutuallyExclusiveMessage(logicalId, violation));
34516
- if (lines.length === 0) return;
34517
- throw new Error(`The following resources declare mutually exclusive properties:\n` + lines.join("\n") + "\n\nCloudFormation rejects these combinations too — edit the template to declare only one of each set.");
34644
+ return validateMutuallyExclusiveProperties.call(this, resources);
34518
34645
  }
34519
34646
  validateNestedRequiredProperties(resources) {
34520
- const lines = [];
34521
- for (const { logicalId, resourceType, properties } of resources) for (const violation of findNestedRequiredViolations(resourceType, properties)) lines.push(buildNestedRequiredMessage(logicalId, violation));
34522
- if (lines.length === 0) return;
34523
- throw new Error(`The following resources declare a nested property block without a member it requires:\n` + lines.join("\n") + "\n\nCloudFormation rejects these blocks too. Declare the missing members; leaving a whole block out is not a violation.");
34647
+ return validateNestedRequiredProperties.call(this, resources);
34524
34648
  }
34525
34649
  validateCustomResourceSecureReferences(resources) {
34526
- const lines = [];
34527
- for (const { logicalId, resourceType, properties } of resources) {
34528
- const paths = findSecureReferencePaths(resourceType, properties);
34529
- if (paths.length > 0) lines.push(buildSecureReferenceMessage(logicalId, paths));
34530
- }
34531
- if (lines.length === 0) return;
34532
- throw new Error("The following custom resources pass a secure dynamic reference ({{resolve:secretsmanager:...}} / {{resolve:ssm-secure:...}}) in their properties:\n" + lines.join("\n") + "\n\nCloudFormation does not support secure dynamic references in custom resources, so the template is rejected before anything is resolved. Have the handler read the secret itself (pass its name or ARN instead), or use a plain {{resolve:ssm:...}} parameter for a value that is not secret.");
34650
+ return validateCustomResourceSecureReferences.call(this, resources);
34533
34651
  }
34534
34652
  reportSdkUnwiredDecisions(resources) {
34535
- for (const { logicalId, resourceType, properties, provisionedBy, previousProperties } of resources) {
34536
- const drops = findSdkUnwiredProperties(resourceType, properties);
34537
- const unrecognizedRoute = findRoutableUnrecognizedProperties(resourceType, properties, this.allowedUnsupportedProperties, previousProperties);
34538
- const stickyCc = provisionedBy === "cc-api" && !STICKY_CC_MIGRATION_EXEMPT.has(resourceType);
34539
- const overridden = stickyCc ? [] : findAcceptedSdkUnwired(resourceType, properties, this.allowedUnsupportedProperties, previousProperties);
34540
- const autoRouted = [...drops.map(({ property }) => property).filter((property) => !this.allowedUnsupportedProperties.has(`${resourceType}:${property}`)), ...unrecognizedRoute].sort((a, b) => a.localeCompare(b));
34541
- if (autoRouted.length > 0) {
34542
- const unroutable = this.ccRouteUnavailableReason(resourceType);
34543
- if (unroutable !== void 0) throw new Error(safeMsg`${logicalId}: ` + this.buildUnroutableSdkUnwiredMessage(resourceType, drops.filter((d) => autoRouted.includes(d.property)), unroutable));
34544
- const propList = autoRouted.join(", ");
34545
- const overrideHint = autoRouted.map((p) => `${resourceType}:${p}`).join(",");
34546
- const message = `${logicalId} (${resourceType}): routing via Cloud Control API (cdkd's SDK Provider does not yet wire ${propList} — CC API will forward the full property map.${unrecognizedRoute.length === 0 ? "" : ` ${unrecognizedRoute.join(", ")} ${unrecognizedRoute.length === 1 ? "is" : "are"} not in cdkd's CFn schema snapshot: Cloud Control applies a property AWS published since, and rejects a misspelled one as CloudFormation does.`} Override via --prefer-sdk-route ${overrideHint}.)`;
34547
- if (provisionedBy === "cc-api") this.logger.debug(message);
34548
- else this.logger.info(message);
34549
- }
34550
- const named = drops.map(({ property }) => property).filter((property) => this.allowedUnsupportedProperties.has(`${resourceType}:${property}`));
34551
- if (named.length > 0 && (stickyCc || autoRouted.length > 0)) {
34552
- const list = named.join(", ");
34553
- const isAre = named.length === 1 ? "is" : "are";
34554
- const [cause, remedy] = stickyCc ? ["this resource's state record already routes it to Cloud Control (provisionedBy: cc-api), which is decided before any property is consulted", "Returning this resource to the SDK provider is a destroy-and-recreate, not a flag change — see https://cdkd.dev/cli-deploy-safety/. Widening --prefer-sdk-route alone cannot do it."] : [`${autoRouted.join(", ")} ${autoRouted.length === 1 ? "is" : "are"} not covered by it, and one uncovered property routes the whole RESOURCE to Cloud Control`, `To keep the resource on its SDK provider, add ${autoRouted.map((p) => `${resourceType}:${p}`).join(",")} to --prefer-sdk-route as well.`];
34555
- this.logger.warn(`${logicalId} (${resourceType}): --prefer-sdk-route had no effect for ${list} — ${cause}. Cloud Control forwards the full property map, so ${list} ${isAre} written to AWS after all. ${remedy}`);
34556
- }
34557
- if (overridden.length > 0) {
34558
- const createOnly = getPropertyCoverage(resourceType)?.createOnlyDrops;
34559
- const unroutable = this.ccRouteUnavailableReason(resourceType);
34560
- const reroutable = unroutable === void 0 ? overridden.filter((p) => createOnly?.has(p) !== true) : [];
34561
- const needsRecreate = unroutable === void 0 ? overridden.filter((p) => createOnly?.has(p) === true) : [];
34562
- const remedies = [];
34563
- if (unroutable !== void 0) remedies.push(`This type cannot be routed via Cloud Control API (${unroutable}), so removing the override makes the deploy refuse at pre-flight instead of rerouting; cdkd has no route that applies ${overridden.length === 1 ? "it" : "them"} to this type.`);
34564
- if (reroutable.length > 0) remedies.push(`Remove the override for ${reroutable.join(", ")} to route this resource via Cloud Control API instead.`);
34565
- if (needsRecreate.length > 0) {
34566
- const one = needsRecreate.length === 1;
34567
- remedies.push(`${needsRecreate.join(", ")} ${one ? "is" : "are"} create-only, so removing the override does not apply ${one ? "it" : "them"} in place -- a create-only property can only be applied by recreating the resource. Where cdkd created the resource without ${one ? "it" : "them"}, a deploy without the override refuses unless something else already forces a replacement or the recreate is opted into.`);
34568
- }
34569
- this.logger.warn(`${logicalId} (${resourceType}): ${overridden.join(", ")} will be left unwritten (--prefer-sdk-route override accepted). ${remedies.join(" ")}`);
34570
- }
34571
- this.reportUnrecognizedProperties(logicalId, resourceType, properties, {
34572
- provisionedBy,
34573
- autoRouted: autoRouted.length > 0,
34574
- previousProperties
34575
- });
34576
- }
34653
+ return reportSdkUnwiredDecisions.call(this, resources);
34577
34654
  }
34578
34655
  reportUnrecognizedProperties(logicalId, resourceType, properties, route) {
34579
- if (route.provisionedBy === "cc-api" && !STICKY_CC_MIGRATION_EXEMPT.has(resourceType) || route.autoRouted) return;
34580
- const unrecognized = findUnrecognizedProperties(resourceType, properties).filter((property) => !this.allowedUnsupportedProperties.has(`${resourceType}:${property}`));
34581
- if (unrecognized.length === 0) return;
34582
- const coverage = getPropertyCoverage(resourceType);
34583
- const unroutable = this.ccRouteUnavailableReason(resourceType) ?? (STICKY_CC_MIGRATION_EXEMPT.get(resourceType)?.mode === "cc-broken" ? "Cloud Control's handler cannot manage this type correctly" : coverage?.ccRouteUnavailable === true ? "the type's SDK provider opts out of the Cloud Control fallback (disableCcApiFallback)" : void 0);
34584
- const readOnly = unrecognized.filter((p) => coverage?.readOnly.has(p) === true);
34585
- const notReadOnly = unrecognized.filter((p) => coverage?.readOnly.has(p) !== true);
34586
- const undecided = unroutable === void 0 ? notReadOnly.filter((p) => containsIntrinsic$1(properties?.[p]) && route.previousProperties != null && typeof route.previousProperties === "object" && Object.hasOwn(route.previousProperties, p)) : [];
34587
- const rest = notReadOnly.filter((p) => !undecided.includes(p));
34588
- const sentences = [];
34589
- const isAre = (names) => names.length === 1 ? "is" : "are";
34590
- if (readOnly.length > 0) sentences.push(`${readOnly.join(", ")} ${isAre(readOnly)} read-only — an attribute AWS computes, which no engine sets (CloudFormation ignores it too); remove it.`);
34591
- if (rest.length > 0 && unroutable !== void 0) sentences.push(`${rest.join(", ")} ${isAre(rest)} not in cdkd's CFn schema snapshot, and this type cannot be routed via Cloud Control API (${unroutable}), so cdkd has no route that applies ${rest.length === 1 ? "it" : "them"}. If it is a property AWS published since the snapshot, please report it: ${unsupportedPropertyIssueUrl(resourceType, rest[0])}.`);
34592
- else if (rest.length > 0) sentences.push(`${rest.join(", ")} ${isAre(rest)} not in cdkd's CFn schema snapshot and unchanged since this resource was deployed on the SDK route, so it stays there and cdkd does not send ${rest.length === 1 ? "it" : "them"}. Changing ${rest.length === 1 ? "it" : "one"} routes the resource via Cloud Control API, which applies a property AWS published since the snapshot and rejects a misspelled one, as CloudFormation does.`);
34593
- if (undecided.length > 0) sentences.push(`${undecided.join(", ")} ${isAre(undecided)} not in cdkd's CFn schema snapshot and ${undecided.length === 1 ? "its value holds" : "their values hold"} an intrinsic, so the route is decided once it resolves: a value unchanged since the SDK-route deploy stays there and is not sent, and a changed one routes via Cloud Control API.`);
34594
- if (sentences.length === 0) return;
34595
- const overrideHint = unrecognized.map((p) => `${resourceType}:${p}`).join(",");
34596
- this.logger.warn(`${logicalId} (${resourceType}): ${unrecognized.length === 1 ? "a property" : "properties"} ${readOnly.length + rest.length > 0 ? "will NOT" : "may not"} reach AWS — the deploy will still report success. ${sentences.join(" ")} If the drop is intended — an addPropertyOverride escape hatch — silence this via --prefer-sdk-route ${overrideHint}.`);
34656
+ return reportUnrecognizedProperties.call(this, logicalId, resourceType, properties, route);
34597
34657
  }
34598
34658
  findAutoRouteHits(resources) {
34599
- const hits = [];
34600
- for (const { logicalId, resourceType, properties, previousProperties } of resources) {
34601
- const actionable = findActionableSdkUnwired(resourceType, properties, this.allowedUnsupportedProperties, previousProperties);
34602
- if (actionable.length === 0) continue;
34603
- hits.push({
34604
- logicalId,
34605
- resourceType,
34606
- properties: actionable.map((d) => d.property)
34607
- });
34608
- }
34609
- return hits;
34659
+ return findAutoRouteHits.call(this, resources);
34610
34660
  }
34611
34661
  };
34612
34662
  function isCustomResource(resourceType) {
@@ -34878,103 +34928,6 @@ function provenanceBaselineOf(state, tokenFree) {
34878
34928
  };
34879
34929
  }
34880
34930
 
34881
- // src/provisioning/secret-physical-id.ts
34882
- const APPSYNC_APIKEY_ARN_RESOURCE_PATH = /^apis\/([^/|]+)\/apikeys?\/([^/|]+)$/;
34883
- const APPSYNC_ARN = /^arn:[^:]+:appsync:[^:]*:[^:]*:(.+)$/;
34884
- const SUBSTRING_FLOOR = 4;
34885
- function maskedSecretSegment(segment) {
34886
- return `****${segment.slice(-4)}`;
34887
- }
34888
- function secretPhysicalIdSegment(resourceType, physicalId) {
34889
- if (resourceType !== "AWS::AppSync::ApiKey") return void 0;
34890
- if (typeof physicalId !== "string" || physicalId === "") return void 0;
34891
- const parts = physicalId.split("|");
34892
- if (parts.length === 2 && parts[0] !== "" && parts[1] !== "") return parts[1];
34893
- const arn = APPSYNC_ARN.exec(physicalId);
34894
- const path = arn ? APPSYNC_APIKEY_ARN_RESOURCE_PATH.exec(arn[1]) : null;
34895
- if (path) return path[2];
34896
- return physicalId;
34897
- }
34898
- function maskSegmentsInText(text, segments) {
34899
- let out = text;
34900
- for (const segment of segments) {
34901
- if (out === segment) return maskedSecretSegment(segment);
34902
- if (segment.length >= SUBSTRING_FLOOR && out.includes(segment)) out = out.split(segment).join(maskedSecretSegment(segment));
34903
- }
34904
- return out;
34905
- }
34906
- function displayPhysicalId(resourceType, physicalId) {
34907
- const segment = secretPhysicalIdSegment(resourceType, physicalId);
34908
- if (segment === void 0 || typeof physicalId !== "string") return physicalId;
34909
- return maskSegmentsInText(physicalId, [segment]);
34910
- }
34911
- function maskSecretSegmentsDeep(value, segments) {
34912
- if (segments.length === 0) return value;
34913
- const ordered = [...new Set(segments)].sort((a, b) => b.length - a.length);
34914
- const walk = (v) => {
34915
- if (typeof v === "string") return maskSegmentsInText(v, ordered);
34916
- if (Array.isArray(v)) return v.map(walk);
34917
- if (v !== null && typeof v === "object") {
34918
- const out = {};
34919
- for (const [k, child] of Object.entries(v)) out[k] = walk(child);
34920
- return out;
34921
- }
34922
- return v;
34923
- };
34924
- return walk(value);
34925
- }
34926
- function segmentOfRecord(record) {
34927
- if (record === null || typeof record !== "object") return void 0;
34928
- const r = record;
34929
- return secretPhysicalIdSegment(r.resourceType, r.physicalId);
34930
- }
34931
- function stringLeavesOf(value, out = []) {
34932
- if (typeof value === "string") out.push(value);
34933
- else if (Array.isArray(value)) for (const v of value) stringLeavesOf(v, out);
34934
- else if (value !== null && typeof value === "object") for (const v of Object.values(value)) stringLeavesOf(v, out);
34935
- return out;
34936
- }
34937
- function secretNamedAttributeLeavesOf$1(record) {
34938
- if (record === null || typeof record !== "object") return [];
34939
- const r = record;
34940
- if (r.resourceType !== "AWS::CloudFormation::Stack") return [];
34941
- const names = r.secretNamedAttributes;
34942
- const attributes = r.attributes;
34943
- if (!Array.isArray(names) || attributes === null || typeof attributes !== "object") return [];
34944
- const leaves = [];
34945
- for (const name of names) {
34946
- if (typeof name !== "string" || !Object.hasOwn(attributes, name)) continue;
34947
- for (const leaf of stringLeavesOf(attributes[name])) if (leaf !== "" && leaf !== "***" && !leaf.includes("{{resolve:")) leaves.push(leaf);
34948
- }
34949
- return leaves;
34950
- }
34951
- function secretSegmentsOfState(state) {
34952
- if (state === null || typeof state !== "object") return [];
34953
- const s = state;
34954
- const segments = [];
34955
- const add = (record) => {
34956
- const segment = segmentOfRecord(record);
34957
- if (segment !== void 0) segments.push(segment);
34958
- };
34959
- if (s.resources !== null && typeof s.resources === "object" && !Array.isArray(s.resources)) for (const record of Object.values(s.resources)) {
34960
- add(record);
34961
- segments.push(...secretNamedAttributeLeavesOf$1(record));
34962
- }
34963
- for (const list of [s.orphans, s.supersededResources]) {
34964
- if (!Array.isArray(list)) continue;
34965
- for (const entry of list) {
34966
- if (entry === null || typeof entry !== "object") continue;
34967
- const record = entry.state;
34968
- add(record);
34969
- segments.push(...secretNamedAttributeLeavesOf$1(record));
34970
- }
34971
- }
34972
- return segments;
34973
- }
34974
- function withSecretPhysicalIdsMaskedInState(state, segments = secretSegmentsOfState(state)) {
34975
- return maskSecretSegmentsDeep(state, segments);
34976
- }
34977
-
34978
34931
  // src/deployment/kept-in-history.ts
34979
34932
  function keptInEarlierRecords(records) {
34980
34933
  const out = [];
@@ -35096,47 +35049,22 @@ async function loadRollbackRetainedCopies(sources, stackName, region) {
35096
35049
  return rollbackRetainedInEventHistory(await readRecentRuns(sources, stackName, region), stackName);
35097
35050
  }
35098
35051
 
35099
- // src/deployment/deploy-engine/masking/remedy.ts
35100
- function maskedRecordRemedyFor(reads, resources, causeScoped = false) {
35101
- const NESTED_STACK_RESOURCE_TYPE = "AWS::CloudFormation::Stack";
35102
- const importCannotClearMask = (type) => type === "AWS::CloudFormation::CustomResource" || (type?.startsWith("Custom::") ?? false);
35103
- const typeOf = (read) => read.logicalId !== void 0 && Object.hasOwn(resources, read.logicalId) ? resources[read.logicalId]?.resourceType : void 0;
35104
- const isLocal = (read) => {
35105
- if (read.logicalId === void 0) return false;
35106
- return typeOf(read) !== NESTED_STACK_RESOURCE_TYPE;
35107
- };
35108
- const isUnclearableLocal = (read) => isLocal(read) && importCannotClearMask(typeOf(read));
35109
- const targetOf = (read) => read.logicalId;
35110
- const localTargets = [...new Set(reads.filter((read) => isLocal(read) && !isUnclearableLocal(read)).map(targetOf).filter((id) => id !== void 0))];
35111
- const unclearableTargets = [...new Set(reads.filter(isUnclearableLocal).map(targetOf).filter((id) => id !== void 0))];
35112
- const foreignReads = reads.filter((read) => !isLocal(read));
35113
- const hasRefStateRead = reads.some((read) => read.kind === "ref-state-key" && isLocal(read));
35114
- const shown = (id) => displayIdent(id);
35115
- const CFN_LOGICAL_ID_MAX_LENGTH = 255;
35116
- const parts = [];
35117
- const commandLines = [];
35118
- if (localTargets.length > 0) {
35119
- const pasteableHere = (id) => isPasteableIdent(id) && id.length <= CFN_LOGICAL_ID_MAX_LENGTH;
35120
- const pasteable = localTargets.filter(pasteableHere);
35121
- const withheld = localTargets.filter((id) => !pasteableHere(id));
35122
- if (pasteable.length > 0) {
35123
- parts.push(causeScoped ? "If cause (3) applies, re-import the record that HOLDS the mask (command(s) below); a re-import does not clear a cause (1) or (2) mask." : `Re-import the record that HOLDS the mask (command(s) below).`);
35124
- for (const id of pasteable) commandLines.push(`Re-import with: ${pasteableCommand("cdkd import", [
35125
- { hole: "stack" },
35126
- { literal: `--resource ${shellQuote(`${id}=<physicalId>`)}` },
35127
- { literal: "--force" }
35128
- ]).command}`);
35129
- }
35130
- if (withheld.length > 0) parts.push(`${causeScoped ? "If cause (3) applies, re-import" : "Re-import"} the record that HOLDS the mask for ${withheld.map(shown).join(", ")}, but the command is withheld: that is not a plain CloudFormation logical id, so a pasted cdkd import line could be reshaped by the shell or name a different resource. Read the id from 'cdkd state show' and quote it yourself, in cdkd import ${commandHole("stack")} --resource ${commandHole("id")}=${commandHole("physicalId")} --force.`);
35131
- }
35132
- if (unclearableTargets.length > 0) parts.push(`Do NOT re-import ${unclearableTargets.map(shown).join(", ")}: a custom resource's import records no attributes, so the masked bag is carried forward unchanged and the refusal repeats.` + (causeScoped ? ` Cause (1) above is the one that applies to it.` : ""));
35133
- if (foreignReads.length > 0) {
35134
- const subject = reads.length === 1 ? "The read above resolves" : foreignReads.length === 1 ? "One of the reads above resolves" : "Some of the reads above resolve";
35135
- parts.push(`${subject} through ANOTHER stack (an Fn::ImportValue, an Fn::GetStackOutput, or a nested stack's Outputs), whose masked record lives in that stack's state — re-importing anything in this stack cannot clear it; act on the producer stack instead.`);
35136
- }
35137
- if (hasRefStateRead) parts.push("A 'Ref <LogicalId> (state key <Key>)' entry above is CDKD's own read, not one the template can stop making: CloudFormation defines that resource type's Ref value as that state key rather than the physical id, so the record must be repaired (re-import it, or let a deploy create or update the resource) — the \"stop reading it\" remedy does not apply to such an entry.");
35138
- return [parts.join(" "), ...commandLines].join("\n");
35139
- }
35052
+ // src/deployment/deploy-engine/replacement/run-state.ts
35053
+ var ReplacementRunState = class {
35054
+ replacedDeleteSkips = /* @__PURE__ */ new Map();
35055
+ deferredReplacedDeletes = void 0;
35056
+ supersededHost = void 0;
35057
+ supersededEntries = /* @__PURE__ */ new Map();
35058
+ retainedOldOnReplacement = /* @__PURE__ */ new Set();
35059
+ replacedOldMaySurvive = /* @__PURE__ */ new Map();
35060
+ recreatedUnderSameId = /* @__PURE__ */ new Set();
35061
+ restoredLostChildren = /* @__PURE__ */ new Set();
35062
+ updatesThatSentNothing = /* @__PURE__ */ new Set();
35063
+ updateWasReplaced = /* @__PURE__ */ new Map();
35064
+ inPlaceCreateOnlyPaths = /* @__PURE__ */ new Map();
35065
+ oldDeletedBeforeCreate = /* @__PURE__ */ new Set();
35066
+ attemptedNameGeneration = /* @__PURE__ */ new Map();
35067
+ };
35140
35068
 
35141
35069
  // src/provisioning/final-snapshot/shared.ts
35142
35070
  function sanitizeSnapshotBase(physicalId) {
@@ -35491,10 +35419,199 @@ function isFinalSnapshotError(error) {
35491
35419
  function ccRoutedFinalSnapshotError(logicalId, resourceType, skipFlagHint) {
35492
35420
  return new CdkdError(`${logicalIdShown(logicalId)} (${resourceTypeShown(resourceType)}) has DeletionPolicy: Snapshot, but the resource is managed via the Cloud Control API route (provisionedBy: cc-api), which has no final-snapshot delete parameter — deleting it now would destroy its data WITHOUT the final snapshot the policy promises. Create a snapshot manually (e.g. aws rds create-db-snapshot / aws elasticache create-snapshot), then re-run with ${skipFlagHint} to delete WITHOUT cdkd's final snapshot (DATA LOSS otherwise), or retain the resource (DeletionPolicy: Retain) and delete it manually.`, "FINAL_SNAPSHOT_UNSUPPORTED");
35493
35421
  }
35422
+ async function ccRoutedInstanceTakesNoSnapshot(input) {
35423
+ const { resourceType, logicalId, physicalId, region, logger } = input;
35424
+ if (resourceType !== "AWS::RDS::DBInstance") return false;
35425
+ if (region === void 0 || region === "") return false;
35426
+ const mask = input.mask ?? ((text) => text);
35427
+ const { describeDBInstanceInRegion, isLiveReadReplica } = await import("./read-replica-BJAUZwWe.js").then((n) => n.i);
35428
+ let reason;
35429
+ try {
35430
+ const live = await describeDBInstanceInRegion(physicalId, region);
35431
+ if (isLiveReadReplica(live)) reason = "it is a read replica";
35432
+ else if ((live?.DBClusterIdentifier ?? "") !== "") reason = "it is a DB cluster member";
35433
+ } catch (error) {
35434
+ logger.warn(mask(`Could not read whether ${logicalIdShown(logicalId)} is a read replica or cluster member, which CloudFormation deletes without a final snapshot, so its delete is refused: ${describeAwsFailure(error).detail}. Fix the read and re-run before reaching for --skip-final-snapshot.`));
35435
+ return false;
35436
+ }
35437
+ if (reason === void 0) return false;
35438
+ logger.info(mask(`Deleting ${logicalIdShown(logicalId)} without a final snapshot: ${reason}, whose Snapshot policy CloudFormation ignores`));
35439
+ return true;
35440
+ }
35494
35441
  function unsupportedFinalSnapshotError(logicalId, resourceType, skipFlagHint) {
35495
35442
  return new CdkdError(`${logicalIdShown(logicalId)} (${resourceTypeShown(resourceType)}) has DeletionPolicy: Snapshot, but cdkd does not implement final snapshots for this type (CloudFormation itself only supports Snapshot on: EC2 Volume, ElastiCache CacheCluster / ReplicationGroup, Neptune / RDS / DocDB clusters, RDS instances, Redshift clusters). Deleting it now would destroy its data WITHOUT the final snapshot the policy promises. Re-run with ${skipFlagHint} to delete WITHOUT a final snapshot (DATA LOSS), or retain the resource (DeletionPolicy: Retain) and delete it manually after snapshotting.`, "FINAL_SNAPSHOT_UNSUPPORTED");
35496
35443
  }
35497
35444
 
35445
+ // src/deployment/deploy-engine/replacement/delete-context.ts
35446
+ function replacementDeleteContext(deps, updateReplacePolicy) {
35447
+ return {
35448
+ deletionPolicy: replacementDeletePolicy(updateReplacePolicy),
35449
+ ...deps.options.skipFinalSnapshot === true && { skipFinalSnapshot: true }
35450
+ };
35451
+ }
35452
+ async function prepareFinalSnapshotForDelete(deps, logicalId, resourceType, currentResource, policy, mask) {
35453
+ if (policy !== "Snapshot" || deps.options.skipFinalSnapshot === true) return void 0;
35454
+ if (ATOMIC_FINAL_SNAPSHOT_TYPES.has(resourceType) && currentResource.provisionedBy !== "cc-api") return buildFinalSnapshotIdentifier(currentResource.physicalId, resourceType);
35455
+ if (ATOMIC_FINAL_SNAPSHOT_TYPES.has(resourceType)) {
35456
+ if (await ccRoutedInstanceTakesNoSnapshot({
35457
+ resourceType,
35458
+ logicalId,
35459
+ physicalId: currentResource.physicalId,
35460
+ region: deps.stackRegion,
35461
+ logger: deps.logger,
35462
+ ...mask !== void 0 && { mask }
35463
+ })) return void 0;
35464
+ throw ccRoutedFinalSnapshotError(logicalId, resourceType, "--skip-final-snapshot");
35465
+ }
35466
+ if (PRE_DELETE_SNAPSHOT_TYPES.has(resourceType)) {
35467
+ await createPreDeleteFinalSnapshot(resourceType, currentResource.physicalId, logicalId, deps.options.finalSnapshotClients ?? getAwsClients(), mask === void 0 ? deps.logger : {
35468
+ info: (message) => deps.logger.info(mask(message)),
35469
+ debug: (message) => deps.logger.debug(mask(message))
35470
+ });
35471
+ return;
35472
+ }
35473
+ throw unsupportedFinalSnapshotError(logicalId, resourceType, "--skip-final-snapshot");
35474
+ }
35475
+
35476
+ // src/deployment/deploy-engine/masking/remedy.ts
35477
+ function maskedRecordRemedyFor(reads, resources, causeScoped = false) {
35478
+ const NESTED_STACK_RESOURCE_TYPE = "AWS::CloudFormation::Stack";
35479
+ const importCannotClearMask = (type) => type === "AWS::CloudFormation::CustomResource" || (type?.startsWith("Custom::") ?? false);
35480
+ const typeOf = (read) => read.logicalId !== void 0 && Object.hasOwn(resources, read.logicalId) ? resources[read.logicalId]?.resourceType : void 0;
35481
+ const isLocal = (read) => {
35482
+ if (read.logicalId === void 0) return false;
35483
+ return typeOf(read) !== NESTED_STACK_RESOURCE_TYPE;
35484
+ };
35485
+ const isUnclearableLocal = (read) => isLocal(read) && importCannotClearMask(typeOf(read));
35486
+ const targetOf = (read) => read.logicalId;
35487
+ const localTargets = [...new Set(reads.filter((read) => isLocal(read) && !isUnclearableLocal(read)).map(targetOf).filter((id) => id !== void 0))];
35488
+ const unclearableTargets = [...new Set(reads.filter(isUnclearableLocal).map(targetOf).filter((id) => id !== void 0))];
35489
+ const foreignReads = reads.filter((read) => !isLocal(read));
35490
+ const hasRefStateRead = reads.some((read) => read.kind === "ref-state-key" && isLocal(read));
35491
+ const shown = (id) => displayIdent(id);
35492
+ const CFN_LOGICAL_ID_MAX_LENGTH = 255;
35493
+ const parts = [];
35494
+ const commandLines = [];
35495
+ if (localTargets.length > 0) {
35496
+ const pasteableHere = (id) => isPasteableIdent(id) && id.length <= CFN_LOGICAL_ID_MAX_LENGTH;
35497
+ const pasteable = localTargets.filter(pasteableHere);
35498
+ const withheld = localTargets.filter((id) => !pasteableHere(id));
35499
+ if (pasteable.length > 0) {
35500
+ parts.push(causeScoped ? "If cause (3) applies, re-import the record that HOLDS the mask (command(s) below); a re-import does not clear a cause (1) or (2) mask." : `Re-import the record that HOLDS the mask (command(s) below).`);
35501
+ for (const id of pasteable) commandLines.push(`Re-import with: ${pasteableCommand("cdkd import", [
35502
+ { hole: "stack" },
35503
+ { literal: `--resource ${shellQuote(`${id}=<physicalId>`)}` },
35504
+ { literal: "--force" }
35505
+ ]).command}`);
35506
+ }
35507
+ if (withheld.length > 0) parts.push(`${causeScoped ? "If cause (3) applies, re-import" : "Re-import"} the record that HOLDS the mask for ${withheld.map(shown).join(", ")}, but the command is withheld: that is not a plain CloudFormation logical id, so a pasted cdkd import line could be reshaped by the shell or name a different resource. Read the id from 'cdkd state show' and quote it yourself, in cdkd import ${commandHole("stack")} --resource ${commandHole("id")}=${commandHole("physicalId")} --force.`);
35508
+ }
35509
+ if (unclearableTargets.length > 0) parts.push(`Do NOT re-import ${unclearableTargets.map(shown).join(", ")}: a custom resource's import records no attributes, so the masked bag is carried forward unchanged and the refusal repeats.` + (causeScoped ? ` Cause (1) above is the one that applies to it.` : ""));
35510
+ if (foreignReads.length > 0) {
35511
+ const subject = reads.length === 1 ? "The read above resolves" : foreignReads.length === 1 ? "One of the reads above resolves" : "Some of the reads above resolve";
35512
+ parts.push(`${subject} through ANOTHER stack (an Fn::ImportValue, an Fn::GetStackOutput, or a nested stack's Outputs), whose masked record lives in that stack's state — re-importing anything in this stack cannot clear it; act on the producer stack instead.`);
35513
+ }
35514
+ if (hasRefStateRead) parts.push("A 'Ref <LogicalId> (state key <Key>)' entry above is CDKD's own read, not one the template can stop making: CloudFormation defines that resource type's Ref value as that state key rather than the physical id, so the record must be repaired (re-import it, or let a deploy create or update the resource) — the \"stop reading it\" remedy does not apply to such an entry.");
35515
+ return [parts.join(" "), ...commandLines].join("\n");
35516
+ }
35517
+
35518
+ // src/provisioning/secret-physical-id.ts
35519
+ const APPSYNC_APIKEY_ARN_RESOURCE_PATH = /^apis\/([^/|]+)\/apikeys?\/([^/|]+)$/;
35520
+ const APPSYNC_ARN = /^arn:[^:]+:appsync:[^:]*:[^:]*:(.+)$/;
35521
+ const SUBSTRING_FLOOR = 4;
35522
+ function maskedSecretSegment(segment) {
35523
+ return `****${segment.slice(-4)}`;
35524
+ }
35525
+ function secretPhysicalIdSegment(resourceType, physicalId) {
35526
+ if (resourceType !== "AWS::AppSync::ApiKey") return void 0;
35527
+ if (typeof physicalId !== "string" || physicalId === "") return void 0;
35528
+ const parts = physicalId.split("|");
35529
+ if (parts.length === 2 && parts[0] !== "" && parts[1] !== "") return parts[1];
35530
+ const arn = APPSYNC_ARN.exec(physicalId);
35531
+ const path = arn ? APPSYNC_APIKEY_ARN_RESOURCE_PATH.exec(arn[1]) : null;
35532
+ if (path) return path[2];
35533
+ return physicalId;
35534
+ }
35535
+ function maskSegmentsInText(text, segments) {
35536
+ let out = text;
35537
+ for (const segment of segments) {
35538
+ if (out === segment) return maskedSecretSegment(segment);
35539
+ if (segment.length >= SUBSTRING_FLOOR && out.includes(segment)) out = out.split(segment).join(maskedSecretSegment(segment));
35540
+ }
35541
+ return out;
35542
+ }
35543
+ function displayPhysicalId(resourceType, physicalId) {
35544
+ const segment = secretPhysicalIdSegment(resourceType, physicalId);
35545
+ if (segment === void 0 || typeof physicalId !== "string") return physicalId;
35546
+ return maskSegmentsInText(physicalId, [segment]);
35547
+ }
35548
+ function maskSecretSegmentsDeep(value, segments) {
35549
+ if (segments.length === 0) return value;
35550
+ const ordered = [...new Set(segments)].sort((a, b) => b.length - a.length);
35551
+ const walk = (v) => {
35552
+ if (typeof v === "string") return maskSegmentsInText(v, ordered);
35553
+ if (Array.isArray(v)) return v.map(walk);
35554
+ if (v !== null && typeof v === "object") {
35555
+ const out = {};
35556
+ for (const [k, child] of Object.entries(v)) out[k] = walk(child);
35557
+ return out;
35558
+ }
35559
+ return v;
35560
+ };
35561
+ return walk(value);
35562
+ }
35563
+ function segmentOfRecord(record) {
35564
+ if (record === null || typeof record !== "object") return void 0;
35565
+ const r = record;
35566
+ return secretPhysicalIdSegment(r.resourceType, r.physicalId);
35567
+ }
35568
+ function stringLeavesOf(value, out = []) {
35569
+ if (typeof value === "string") out.push(value);
35570
+ else if (Array.isArray(value)) for (const v of value) stringLeavesOf(v, out);
35571
+ else if (value !== null && typeof value === "object") for (const v of Object.values(value)) stringLeavesOf(v, out);
35572
+ return out;
35573
+ }
35574
+ function secretNamedAttributeLeavesOf$1(record) {
35575
+ if (record === null || typeof record !== "object") return [];
35576
+ const r = record;
35577
+ if (r.resourceType !== "AWS::CloudFormation::Stack") return [];
35578
+ const names = r.secretNamedAttributes;
35579
+ const attributes = r.attributes;
35580
+ if (!Array.isArray(names) || attributes === null || typeof attributes !== "object") return [];
35581
+ const leaves = [];
35582
+ for (const name of names) {
35583
+ if (typeof name !== "string" || !Object.hasOwn(attributes, name)) continue;
35584
+ for (const leaf of stringLeavesOf(attributes[name])) if (leaf !== "" && leaf !== "***" && !leaf.includes("{{resolve:")) leaves.push(leaf);
35585
+ }
35586
+ return leaves;
35587
+ }
35588
+ function secretSegmentsOfState(state) {
35589
+ if (state === null || typeof state !== "object") return [];
35590
+ const s = state;
35591
+ const segments = [];
35592
+ const add = (record) => {
35593
+ const segment = segmentOfRecord(record);
35594
+ if (segment !== void 0) segments.push(segment);
35595
+ };
35596
+ if (s.resources !== null && typeof s.resources === "object" && !Array.isArray(s.resources)) for (const record of Object.values(s.resources)) {
35597
+ add(record);
35598
+ segments.push(...secretNamedAttributeLeavesOf$1(record));
35599
+ }
35600
+ for (const list of [s.orphans, s.supersededResources]) {
35601
+ if (!Array.isArray(list)) continue;
35602
+ for (const entry of list) {
35603
+ if (entry === null || typeof entry !== "object") continue;
35604
+ const record = entry.state;
35605
+ add(record);
35606
+ segments.push(...secretNamedAttributeLeavesOf$1(record));
35607
+ }
35608
+ }
35609
+ return segments;
35610
+ }
35611
+ function withSecretPhysicalIdsMaskedInState(state, segments = secretSegmentsOfState(state)) {
35612
+ return maskSecretSegmentsDeep(state, segments);
35613
+ }
35614
+
35498
35615
  // src/types/deployment-events.ts
35499
35616
  function extractDeploymentEventError(err) {
35500
35617
  if (!(err instanceof Error)) return {
@@ -35878,7 +35995,16 @@ async function prepareCreateRollbackFinalSnapshot(op, provisionedBy, ctx, mask)
35878
35995
  debug: (message) => ctx.logger.debug(mask(message))
35879
35996
  });
35880
35997
  return;
35881
- case "refuse-cc-routed": throw ccRoutedFinalSnapshotError(logicalId, resourceType, SKIP_FINAL_SNAPSHOT_FLAG);
35998
+ case "refuse-cc-routed":
35999
+ if (await ccRoutedInstanceTakesNoSnapshot({
36000
+ resourceType,
36001
+ logicalId,
36002
+ physicalId,
36003
+ region: ctx.region,
36004
+ logger: ctx.logger,
36005
+ mask
36006
+ })) return;
36007
+ throw ccRoutedFinalSnapshotError(logicalId, resourceType, SKIP_FINAL_SNAPSHOT_FLAG);
35882
36008
  case "refuse-unsupported-type": throw unsupportedFinalSnapshotError(logicalId, resourceType, SKIP_FINAL_SNAPSHOT_FLAG);
35883
36009
  }
35884
36010
  }
@@ -36900,147 +37026,6 @@ function printingSecretsFor(run, logicalId) {
36900
37026
  return unionOfSecretBags([secrets, registry]);
36901
37027
  }
36902
37028
 
36903
- // src/deployment/delete-guard-scope.ts
36904
- const storage$1 = new AsyncLocalStorage();
36905
- function collectDeleteGuards(sink, fn) {
36906
- return storage$1.run(sink, fn);
36907
- }
36908
- function reportDeleteGuards(result, target) {
36909
- const sink = storage$1.getStore();
36910
- if (!sink) return;
36911
- for (const guard of deleteIndeterminateGuards(result)) sink.push({
36912
- guard: guard.guard,
36913
- reason: guard.reason,
36914
- physicalId: target.physicalId,
36915
- resourceType: target.resourceType,
36916
- ...target.provisionedBy && { provisionedBy: target.provisionedBy }
36917
- });
36918
- }
36919
-
36920
- // src/deployment/superseded-resources.ts
36921
- function supersededResourcesOf(state) {
36922
- const rows = state?.supersededResources;
36923
- if (!Array.isArray(rows)) return [];
36924
- return rows.filter(isSupersededResourceRecord);
36925
- }
36926
- function isSupersededResourceRecord(row) {
36927
- if (typeof row !== "object" || row === null) return false;
36928
- const entry = row;
36929
- const record = entry["state"];
36930
- if (typeof entry["logicalId"] !== "string") return false;
36931
- if (typeof record !== "object" || record === null) return false;
36932
- const { physicalId, resourceType, properties } = record;
36933
- return typeof physicalId === "string" && physicalId !== "" && typeof resourceType === "string" && resourceType !== "" && typeof properties === "object" && properties !== null && !Array.isArray(properties);
36934
- }
36935
- function supersededHolderOf(entry, resources) {
36936
- const holders = Object.values(resources).filter((record) => typeof record === "object" && record !== null && record.physicalId === entry.state.physicalId);
36937
- return holders.find((record) => record.resourceType === entry.state.resourceType) ?? holders[0];
36938
- }
36939
- function isSupersededHeldBySameType(entry, resources) {
36940
- return Object.values(resources).some((record) => typeof record === "object" && record !== null && record.physicalId === entry.state.physicalId && record.resourceType === entry.state.resourceType);
36941
- }
36942
- function supersededHeldByOtherTypeWarning(entry, holderType) {
36943
- return `the superseded ${entry.state.resourceType} of ${entry.logicalId} (${entry.state.physicalId}) was not deleted: a ${holderType} record of this stack has the same physical id, and cdkd never deletes an id a record names. If the ${entry.state.resourceType} still exists, delete it by hand; it is no longer tracked in state.`;
36944
- }
36945
- function addSuperseded(host, entry) {
36946
- host.supersededResources = [...(Array.isArray(host.supersededResources) ? host.supersededResources : []).filter((row) => !isSupersededResourceRecord(row) || row.state.physicalId !== entry.state.physicalId || row.state.resourceType !== entry.state.resourceType), entry];
36947
- }
36948
- function canRecordSuperseded(record, deleteContext) {
36949
- if (deleteContext.noEchoDeleteValues !== void 0) return false;
36950
- if (deleteContext.inlinePolicyClaimed !== void 0) return false;
36951
- if (Array.isArray(record.noEchoLeaves) && record.noEchoLeaves.length > 0) return false;
36952
- return !INLINE_POLICY_TYPES.has(record.resourceType);
36953
- }
36954
- const INLINE_POLICY_TYPES = /* @__PURE__ */ new Set([
36955
- "AWS::IAM::Policy",
36956
- "AWS::IAM::RolePolicy",
36957
- "AWS::IAM::UserPolicy",
36958
- "AWS::IAM::GroupPolicy"
36959
- ]);
36960
- function removeSuperseded(host, entry) {
36961
- if (!Array.isArray(host.supersededResources)) return;
36962
- const remaining = host.supersededResources.filter((row) => row !== entry);
36963
- if (remaining.length === 0) delete host.supersededResources;
36964
- else host.supersededResources = remaining;
36965
- }
36966
- function supersededAfterRollback(base, pending) {
36967
- const added = Array.isArray(pending.supersededResources) ? pending.supersededResources : [];
36968
- if (added.length === 0) return {};
36969
- return { supersededResources: [...Array.isArray(base.supersededResources) ? base.supersededResources : [], ...added] };
36970
- }
36971
- const SUPERSEDED_KEPT_REMEDY = "cdkd keeps it in state: the next `cdkd deploy` of this stack retries the delete, and `cdkd destroy` deletes it";
36972
- function withoutSuperseded(state) {
36973
- const { supersededResources: _dropped, ...rest } = state;
36974
- return rest;
36975
- }
36976
- async function deleteSupersededEntry(entry, input) {
36977
- const record = entry.state;
36978
- let result;
36979
- try {
36980
- const send = () => input.provider.delete(entry.logicalId, record.physicalId, record.resourceType, record.properties, {
36981
- expectedRegion: input.region,
36982
- ...entry.forceDataDelete === true && { forceDataDelete: true },
36983
- ...entry.finalSnapshotIdentifier !== void 0 && { finalSnapshotIdentifier: entry.finalSnapshotIdentifier },
36984
- deletionPolicy: replacementDeletePolicy(entry.updateReplacePolicy),
36985
- ...entry.skipFinalSnapshot === true && { skipFinalSnapshot: true },
36986
- ...input.removeProtection === true && { removeProtection: true },
36987
- ...input.stackDestroy === true && { stackDestroy: true },
36988
- recordedAttributes: record.attributes,
36989
- recordedNoEchoLeaves: record.noEchoLeaves,
36990
- maskSecrets: input.maskSecrets
36991
- });
36992
- result = input.once === true ? await send() : await retryWhileInUse(send, input.stop);
36993
- } catch (error) {
36994
- return {
36995
- kind: "failed",
36996
- error
36997
- };
36998
- }
36999
- reportDeleteGuards(result, {
37000
- physicalId: record.physicalId,
37001
- resourceType: record.resourceType,
37002
- provisionedBy: record.provisionedBy
37003
- });
37004
- const reason = deleteSkipReason(result);
37005
- return reason === void 0 ? { kind: "deleted" } : {
37006
- kind: "notDeleted",
37007
- reason
37008
- };
37009
- }
37010
- const supersededInUseRetry = {
37011
- attempts: 6,
37012
- delayMs: 1e4
37013
- };
37014
- const IN_USE_ERROR_NAMES = /* @__PURE__ */ new Set([
37015
- "ResourceInUseException",
37016
- "ResourceInUse",
37017
- "DependencyViolation"
37018
- ]);
37019
- const IN_USE_CONFLICT = /\bare using it\b/;
37020
- function isInUseRefusal(error) {
37021
- for (let current = error, depth = 0; current !== void 0 && depth < 8; depth++) {
37022
- if (typeof current !== "object" || current === null) return false;
37023
- const { name, message } = current;
37024
- if (typeof name === "string" && IN_USE_ERROR_NAMES.has(name)) return true;
37025
- if (name === "ConflictException" && typeof message === "string" && IN_USE_CONFLICT.test(message)) return true;
37026
- current = current.cause;
37027
- }
37028
- return false;
37029
- }
37030
- async function retryWhileInUse(send, stop) {
37031
- for (let attempt = 1;; attempt++) try {
37032
- return await send();
37033
- } catch (error) {
37034
- if (attempt >= supersededInUseRetry.attempts || stop() || !isInUseRefusal(error)) throw error;
37035
- await new Promise((resolve) => setTimeout(resolve, supersededInUseRetry.delayMs));
37036
- if (stop()) throw error;
37037
- }
37038
- }
37039
- function holdsSupersededResources(record) {
37040
- const rows = record.supersededResources;
37041
- return rows !== void 0 && (!Array.isArray(rows) || rows.length > 0);
37042
- }
37043
-
37044
37029
  // src/utils/colors.ts
37045
37030
  const codes = {
37046
37031
  reset: "\x1B[0m",
@@ -37060,110 +37045,21 @@ const cyan = (s) => `${codes.cyan}${s}${codes.reset}`;
37060
37045
  const gray = (s) => `${codes.gray}${s}${codes.reset}`;
37061
37046
  const bold = (s) => `${codes.bright}${s}${codes.reset}`;
37062
37047
 
37063
- // src/deployment/rollback-executor/replay-scope.ts
37064
- function withReplayDeletePrinting(scope, fn) {
37065
- const deployBag = scope.ctx.logOnlyNeedlesFor?.(scope.op.logicalId);
37066
- return withPrintingSecrets(scope.secrets, () => deployBag === void 0 ? fn() : withPrintingSecrets(deployBag, fn));
37067
- }
37068
- function noteRolledBackCreate(scope, op, record) {
37069
- if (op.changeType !== "CREATE") return;
37070
- const create = {
37071
- logicalId: op.logicalId,
37072
- record,
37073
- ...op.nameGeneration !== void 0 && { nameGeneration: op.nameGeneration }
37074
- };
37075
- scope.result.rolledBackCreates.push(create);
37076
- scope.onRolledBackCreate?.(create);
37077
- }
37078
-
37079
- // src/deployment/rollback-executor/replaced-survivor.ts
37080
- function replacedDeleteFailureVerdict(error) {
37081
- if (isDeleteStarted(error)) return "unconfirmed";
37082
- return isRefusedByName(error) ? "kept" : "unconfirmed";
37048
+ // src/deployment/delete-guard-scope.ts
37049
+ const storage$1 = new AsyncLocalStorage();
37050
+ function collectDeleteGuards(sink, fn) {
37051
+ return storage$1.run(sink, fn);
37083
37052
  }
37084
- const REPLACED_SURVIVOR_PROBE_TIMEOUT_MS = 3e4;
37085
- const INTERRUPT_POLL_MS = 250;
37086
- async function probeReplacedSurvivor(s, oldType, timeoutMs = REPLACED_SURVIVOR_PROBE_TIMEOUT_MS) {
37087
- if (s.isInterrupted?.() === true) return "interrupted";
37088
- let timer;
37089
- let poll;
37090
- const stopped = new Promise((resolve) => {
37091
- timer = setTimeout(() => resolve("unknown"), timeoutMs);
37092
- if (s.isInterrupted !== void 0) {
37093
- const interrupted = s.isInterrupted;
37094
- poll = setInterval(() => {
37095
- if (interrupted()) resolve("interrupted");
37096
- }, INTERRUPT_POLL_MS);
37097
- }
37053
+ function reportDeleteGuards(result, target) {
37054
+ const sink = storage$1.getStore();
37055
+ if (!sink) return;
37056
+ for (const guard of deleteIndeterminateGuards(result)) sink.push({
37057
+ guard: guard.guard,
37058
+ reason: guard.reason,
37059
+ physicalId: target.physicalId,
37060
+ resourceType: target.resourceType,
37061
+ ...target.provisionedBy && { provisionedBy: target.provisionedBy }
37098
37062
  });
37099
- try {
37100
- return await Promise.race([readSurvivor(s, oldType), stopped]);
37101
- } finally {
37102
- clearTimeout(timer);
37103
- clearInterval(poll);
37104
- }
37105
- }
37106
- async function readSurvivor(s, oldType) {
37107
- const prev = s.op.previousState;
37108
- const physicalId = prev?.physicalId;
37109
- if (typeof physicalId !== "string" || physicalId === "") return "unknown";
37110
- try {
37111
- const { provider } = s.ctx.providerRegistry.getProviderFor({
37112
- resourceType: oldType,
37113
- provisionedBy: prev?.provisionedBy
37114
- });
37115
- if (typeof provider.readCurrentState !== "function") return "unreadable";
37116
- const read = await withReplayDeletePrinting(s, () => provider.readCurrentState(physicalId, s.op.logicalId, oldType, prev?.properties));
37117
- if (read === RESOURCE_NOT_FOUND) return "gone";
37118
- if (read === void 0) return "unreadable";
37119
- if (typeof read !== "object" || read === null || Array.isArray(read)) return "unknown";
37120
- return Object.keys(read).length > 0 ? "exists" : "unreadable";
37121
- } catch {
37122
- return "unknown";
37123
- }
37124
- }
37125
-
37126
- // src/deployment/stack-records-scope.ts
37127
- async function awaitInFlightSibling(view, self, sibling) {
37128
- const waiting = view.waiting;
37129
- if (waiting === void 0 || waiting.has(sibling.logicalId)) return void 0;
37130
- waiting.add(self);
37131
- try {
37132
- return await sibling.settled;
37133
- } finally {
37134
- waiting.delete(self);
37135
- }
37136
- }
37137
- const stackRecordsStore = new AsyncLocalStorage();
37138
- function withStackRecords(view, fn) {
37139
- return stackRecordsStore.run(view, fn);
37140
- }
37141
- function getStackRecords() {
37142
- return stackRecordsStore.getStore();
37143
- }
37144
- function deployStackRecordsView(records, before, deleting, unsettled = () => false, inFlight) {
37145
- const settled = () => Object.entries(records).filter(([lid]) => !unsettled(lid));
37146
- return {
37147
- ...inFlight && {
37148
- inFlight,
37149
- waiting: /* @__PURE__ */ new Set()
37150
- },
37151
- live: settled,
37152
- survivors: () => [...settled().filter(([lid]) => !deleting.has(lid)), ...Object.entries(before).filter(([lid, record]) => deleting.has(lid) && shouldRetainResource(record.deletionPolicy))]
37153
- };
37154
- }
37155
- function destroyStackRecordsView(records) {
37156
- return {
37157
- live: () => Object.entries(records),
37158
- survivors: () => Object.entries(records).filter(([, record]) => shouldRetainResource(record.deletionPolicy))
37159
- };
37160
- }
37161
- function replayStackRecordsView(records, orphanLogicalIds = /* @__PURE__ */ new Set()) {
37162
- const kept = Object.entries(records).filter(([lid, record]) => record.deletionPolicy === "Retain" || orphanLogicalIds.has(lid));
37163
- return {
37164
- live: () => Object.entries(records),
37165
- survivors: () => [...Object.entries(records), ...kept.filter(([lid]) => !Object.hasOwn(records, lid))]
37166
- };
37167
37063
  }
37168
37064
 
37169
37065
  // src/provisioning/restore-source-guard.ts
@@ -37192,119 +37088,7 @@ function refuseRestoreFromItself(resourceType, properties, physicalId, logicalId
37192
37088
  throw markNonRetryable(new ProvisioningError(safeMsg`${resourceType} ${logicalId}: SourceDBClusterIdentifier must be another cluster than the one this creates or replaces; nothing was changed.`, resourceType, logicalId, physicalId));
37193
37089
  }
37194
37090
 
37195
- // src/deployment/deploy-engine/name-collision.ts
37196
- function replacementNameOrigin(logicalId, physicalId) {
37197
- if (looksLikeCdkdGeneratedName(physicalId, logicalId, getCurrentStackName(), getCurrentStackInstanceId())) return {
37198
- descriptor: `The physical name (${physicalId}) was GENERATED by cdkd from the construct's logical id rather than declared in your template, and that derivation has no random component — so the new resource asks for exactly the name the existing one still holds`,
37199
- remedy: "Either give the resource an explicit physical name in your CDK code, or rename the CONSTRUCT (its id feeds the generated name — note that this replaces the resource rather than renaming it in place)"
37200
- };
37201
- return {
37202
- descriptor: `The resource has a user-supplied physical name (${physicalId})`,
37203
- remedy: "Either rename the resource in your CDK code (a fresh name lets the safe create-first order proceed)"
37204
- };
37205
- }
37206
- function generatedReplacementHolderAdvice(input) {
37207
- if (input.change?.generated !== true) return "";
37208
- const name = displaySafe(input.mask(input.change.desiredName), { asciiOnly: true });
37209
- const old = displaySafe(input.mask(input.oldPhysicalId), { asciiOnly: true });
37210
- const lead = ` The colliding name ${isInertUnquoted(name) ? name : "the generated name"} is the one this replacement generates for its next name generation, so its holder is most likely the new resource an interrupted earlier attempt of this replacement created. If it is, `;
37211
- const tail = `, or delete it and re-run the deploy.`;
37212
- if (input.stackName.includes("~")) return lead + `adopt it through the top-level stack with \`cdkd import\` (then delete ${old} by hand)` + tail;
37213
- const adopt = pasteableCommand("cdkd import", [{
37214
- value: input.stackName,
37215
- hole: "stack"
37216
- }, {
37217
- flag: "--resource",
37218
- value: `${input.logicalId}=${input.change.desiredName}`,
37219
- hole: "logicalId=physicalId"
37220
- }]);
37221
- const command = input.mask(adopt.command) === adopt.command ? adopt.command : void 0;
37222
- return lead + (command === void 0 ? `adopt it with \`cdkd import\`` : `adopt it with \`${command}\` (using its physical id where the type records another)`) + ` and then delete ${old} by hand` + tail;
37223
- }
37224
- function orphanedNameCollisionAdvice(providerRegistry, changeType, logicalId, error) {
37225
- if (changeType !== "CREATE") return void 0;
37226
- if (!(error instanceof ProvisioningError)) return void 0;
37227
- const physicalId = error.physicalId;
37228
- if (!physicalId) return void 0;
37229
- const replayed = isReplayedNameCollisionFrom(error, logicalId, (link) => isAuxiliaryMarkOf(link, RETRY_AUXILIARY_OWNER));
37230
- if (!replayed && !isNameCollisionErrorFrom(error, logicalId)) return void 0;
37231
- const stackName = getCurrentStackName();
37232
- if (!looksLikeCdkdGeneratedName(physicalId, logicalId, stackName, getCurrentStackInstanceId())) return;
37233
- if (!stackName) return void 0;
37234
- const safeId = displaySafe(physicalId, { asciiOnly: true });
37235
- const safeStack = displaySafe(stackName, { asciiOnly: true });
37236
- const safeLogicalId = displaySafe(logicalId, { asciiOnly: true });
37237
- const idShown = isInertUnquoted(safeId);
37238
- const shownId = idShown ? safeId : "a name that cannot be shown safely here";
37239
- const shownLogicalId = isInertUnquoted(safeLogicalId) ? safeLogicalId : "A resource whose logical id cannot be shown safely here";
37240
- const diagnosis = replayed ? `${shownLogicalId}: the name AWS reports as taken (${shownId}) is most likely held by a resource THIS create made. An earlier attempt of it ended without a clear verdict (a server error, a dropped connection or a timeout, or a failure after the create call itself may have succeeded), and the retry then found the name taken. A dropped connection can also happen before the request reached AWS, so the holder may be another resource: confirm it is yours before deleting or importing it. cdkd records a resource only once its create succeeds, so this one is in no state file: no rollback or cdkd destroy will remove it, and re-running collides with it again.` : `${shownLogicalId}: the name AWS reports as taken (${shownId}) is one cdkd DERIVED from the logical id, and that derivation has no random component — so this is most likely a resource an earlier cdkd run left behind. A rollback leaves a resource carrying DeletionPolicy: Retain in AWS and drops it from state, as CloudFormation does; what differs is the name. CloudFormation would generate a fresh one for an unnamed resource and redeploy clean, whereas cdkd asks again for the name the orphan still holds — so re-running does not clear this.`;
37241
- const deleteArm = `If it is not a resource you want to keep, delete ${idShown ? safeId : "it"} in AWS — after confirming it holds nothing you need${replayed ? "" : ", since Retain is what kept it"} — and re-deploy.`;
37242
- let canImport;
37243
- try {
37244
- canImport = typeof providerRegistry.getProvider(error.resourceType).import === "function";
37245
- } catch {
37246
- canImport = false;
37247
- }
37248
- const commandNamesTheRightResource = safeId === physicalId && safeStack === stackName && safeLogicalId === logicalId;
37249
- const importableTarget = !stackName.includes("~");
37250
- if (!canImport || !commandNamesTheRightResource || !importableTarget) return `${diagnosis} ${!canImport ? `cdkd cannot adopt ${displaySafe(error.resourceType, { asciiOnly: true })} back into state (its provider implements no import)` : !importableTarget ? `this is a nested-stack child, whose stack name cdkd import cannot resolve` : `cdkd cannot render an import command that provably names this resource`}, so the way forward is to delete it. ${deleteArm}`;
37251
- const adopt = pasteableCommand("cdkd import", [{
37252
- value: stackName,
37253
- hole: "stack"
37254
- }, {
37255
- flag: "--resource",
37256
- value: `${logicalId}=${physicalId}`,
37257
- hole: "logicalId=physicalId"
37258
- }]);
37259
- return `${diagnosis} To recover, adopt it back into state instead of re-creating it, with the command below (a selective import merges into existing state and needs no --force while the resource is absent from it). CONFIRM IT IS YOURS FIRST — a name cdkd derives is predictable, so for a globally-namespaced type it can belong to another account, and the same stack deployed in another region derives the same name. ${deleteArm}${adopt.withheld.length === 0 ? "" : " The command below prints a quoted hole in place of a value cdkd will not name on a command line; replace it whole, quotes included, with your stack name or '<logicalId>=<name>', shell-quoted."}\nAdopt with: ${adopt.command}`;
37260
- }
37261
- function isReplacementNameRefusal(error, logicalId) {
37262
- let current = error;
37263
- for (let depth = 0; depth < 10 && current != null; depth++) {
37264
- if (typeof current !== "object") return false;
37265
- const linkId = current.logicalId;
37266
- if (typeof linkId === "string" && linkId !== logicalId) return false;
37267
- if (current instanceof CdkdError && current.code === "NAMED_REPLACEMENT_COLLISION") return true;
37268
- current = current.cause;
37269
- }
37270
- return false;
37271
- }
37272
-
37273
- // src/deployment/deploy-engine/replacement.ts
37274
- var ReplacementRunState = class {
37275
- replacedDeleteSkips = /* @__PURE__ */ new Map();
37276
- deferredReplacedDeletes = void 0;
37277
- supersededHost = void 0;
37278
- supersededEntries = /* @__PURE__ */ new Map();
37279
- retainedOldOnReplacement = /* @__PURE__ */ new Set();
37280
- replacedOldMaySurvive = /* @__PURE__ */ new Map();
37281
- recreatedUnderSameId = /* @__PURE__ */ new Set();
37282
- restoredLostChildren = /* @__PURE__ */ new Set();
37283
- updatesThatSentNothing = /* @__PURE__ */ new Set();
37284
- updateWasReplaced = /* @__PURE__ */ new Map();
37285
- inPlaceCreateOnlyPaths = /* @__PURE__ */ new Map();
37286
- oldDeletedBeforeCreate = /* @__PURE__ */ new Set();
37287
- attemptedNameGeneration = /* @__PURE__ */ new Map();
37288
- };
37289
- function replacementDeleteContext(deps, updateReplacePolicy) {
37290
- return {
37291
- deletionPolicy: replacementDeletePolicy(updateReplacePolicy),
37292
- ...deps.options.skipFinalSnapshot === true && { skipFinalSnapshot: true }
37293
- };
37294
- }
37295
- async function prepareFinalSnapshotForDelete(deps, logicalId, resourceType, currentResource, policy, mask) {
37296
- if (policy !== "Snapshot" || deps.options.skipFinalSnapshot === true) return void 0;
37297
- if (ATOMIC_FINAL_SNAPSHOT_TYPES.has(resourceType) && currentResource.provisionedBy !== "cc-api") return buildFinalSnapshotIdentifier(currentResource.physicalId, resourceType);
37298
- if (ATOMIC_FINAL_SNAPSHOT_TYPES.has(resourceType)) throw ccRoutedFinalSnapshotError(logicalId, resourceType, "--skip-final-snapshot");
37299
- if (PRE_DELETE_SNAPSHOT_TYPES.has(resourceType)) {
37300
- await createPreDeleteFinalSnapshot(resourceType, currentResource.physicalId, logicalId, deps.options.finalSnapshotClients ?? getAwsClients(), mask === void 0 ? deps.logger : {
37301
- info: (message) => deps.logger.info(mask(message)),
37302
- debug: (message) => deps.logger.debug(mask(message))
37303
- });
37304
- return;
37305
- }
37306
- throw unsupportedFinalSnapshotError(logicalId, resourceType, "--skip-final-snapshot");
37307
- }
37091
+ // src/deployment/deploy-engine/replacement/delete-first.ts
37308
37092
  async function replaceDeleteFirstAndRecreate(run, deps, logicalId, resourceType, oldResourceType, currentResource, oldDeleteProvider, replaceProvider, replaceProps, secrets, updateReplacePolicy, oldDeleteProvisionedBy, noEchoDeleteValues) {
37309
37093
  refuseRestoreFromItself(resourceType, replaceProps, currentResource.physicalId, logicalId, {
37310
37094
  region: deps.stackRegion,
@@ -37376,6 +37160,8 @@ function fallbackFailureText(deps, error, secrets, build) {
37376
37160
  function stampRedacted$1(error, redacted) {
37377
37161
  return redacted && error.cause instanceof Error ? markRedactedCause(error) : error;
37378
37162
  }
37163
+
37164
+ // src/deployment/deploy-engine/replacement/name-change.ts
37379
37165
  function typeChangeNameQuestion(resourceType, input) {
37380
37166
  const property = explicitNamePropertyFor(resourceType);
37381
37167
  if (property === void 0) return void 0;
@@ -37460,41 +37246,273 @@ async function checkedReplacementNameChange(deps, input) {
37460
37246
  const remedy = (await deps.rollbackRetainedCopies?.(input.stackName).catch(() => []) ?? []).some((copy) => copy.logicalId === logicalId && copy.resourceType === resourceType && probeFoundSameId(resourceType, copy.physicalId, found.physicalId)) ? `This stack's event history records that a rolled-back deploy kept ${displaySafe(logicalId)}'s replacement under this name because of UpdateReplacePolicy: Retain, as CloudFormation also does, untracked by cdkd. If the holder is that copy and you no longer need it, delete it; otherwise choose another name.` : `Choose a name no other resource holds, or delete the resource holding it if it is yours.`;
37461
37247
  throw markNonRetryable(new CdkdError(maskName(`${subject} requires replacement, and another existing resource (${displaySafe(found.physicalId)}) already holds the name it asks for. ${renderReplacementNameChange(change, input.createProps)}. Since ${adoptsText}, creating the replacement would take that resource over and record it as this stack's. Nothing was created or deleted. ${remedy}`), "NAMED_REPLACEMENT_COLLISION"));
37462
37248
  }
37463
- async function createFirstThenDeleteOld(run, deps, input) {
37464
- const { logicalId, resourceType, currentResource, secrets } = input;
37465
- const retainOld = input.retainOld === true;
37466
- const finalSnapshotIdentifier = retainOld ? void 0 : await prepareFinalSnapshotForDelete(deps, logicalId, input.oldResourceType, currentResource, input.snapshotPolicy, createUnionSecretMasker([secrets, secretNameBagFor(deps.secretsRun(), logicalId)]));
37467
- deps.logger.info(retainOld ? safeMsg` ${logicalId}'s new name differs from the one the old resource holds — creating the new resource (the old one is retained)...` : safeMsg` ${logicalId}'s new name differs from the one the old resource holds — creating the new resource before deleting the old one...`);
37468
- const maskName = maskRewrittenSentName(resourceType, input.createProps, logicalId, (text) => maskSecretsInText(text, secrets));
37469
- let createResult;
37249
+
37250
+ // src/deployment/deploy-engine/name-collision.ts
37251
+ function replacementNameOrigin(logicalId, physicalId) {
37252
+ if (looksLikeCdkdGeneratedName(physicalId, logicalId, getCurrentStackName(), getCurrentStackInstanceId())) return {
37253
+ descriptor: `The physical name (${physicalId}) was GENERATED by cdkd from the construct's logical id rather than declared in your template, and that derivation has no random component — so the new resource asks for exactly the name the existing one still holds`,
37254
+ remedy: "Either give the resource an explicit physical name in your CDK code, or rename the CONSTRUCT (its id feeds the generated name — note that this replaces the resource rather than renaming it in place)"
37255
+ };
37256
+ return {
37257
+ descriptor: `The resource has a user-supplied physical name (${physicalId})`,
37258
+ remedy: "Either rename the resource in your CDK code (a fresh name lets the safe create-first order proceed)"
37259
+ };
37260
+ }
37261
+ function generatedReplacementHolderAdvice(input) {
37262
+ if (input.change?.generated !== true) return "";
37263
+ const name = displaySafe(input.mask(input.change.desiredName), { asciiOnly: true });
37264
+ const old = displaySafe(input.mask(input.oldPhysicalId), { asciiOnly: true });
37265
+ const lead = ` The colliding name ${isInertUnquoted(name) ? name : "the generated name"} is the one this replacement generates for its next name generation, so its holder is most likely the new resource an interrupted earlier attempt of this replacement created. If it is, `;
37266
+ const tail = `, or delete it and re-run the deploy.`;
37267
+ if (input.stackName.includes("~")) return lead + `adopt it through the top-level stack with \`cdkd import\` (then delete ${old} by hand)` + tail;
37268
+ const adopt = pasteableCommand("cdkd import", [{
37269
+ value: input.stackName,
37270
+ hole: "stack"
37271
+ }, {
37272
+ flag: "--resource",
37273
+ value: `${input.logicalId}=${input.change.desiredName}`,
37274
+ hole: "logicalId=physicalId"
37275
+ }]);
37276
+ const command = input.mask(adopt.command) === adopt.command ? adopt.command : void 0;
37277
+ return lead + (command === void 0 ? `adopt it with \`cdkd import\`` : `adopt it with \`${command}\` (using its physical id where the type records another)`) + ` and then delete ${old} by hand` + tail;
37278
+ }
37279
+ function orphanedNameCollisionAdvice(providerRegistry, changeType, logicalId, error) {
37280
+ if (changeType !== "CREATE") return void 0;
37281
+ if (!(error instanceof ProvisioningError)) return void 0;
37282
+ const physicalId = error.physicalId;
37283
+ if (!physicalId) return void 0;
37284
+ const replayed = isReplayedNameCollisionFrom(error, logicalId, (link) => isAuxiliaryMarkOf(link, RETRY_AUXILIARY_OWNER));
37285
+ if (!replayed && !isNameCollisionErrorFrom(error, logicalId)) return void 0;
37286
+ const stackName = getCurrentStackName();
37287
+ if (!looksLikeCdkdGeneratedName(physicalId, logicalId, stackName, getCurrentStackInstanceId())) return;
37288
+ if (!stackName) return void 0;
37289
+ const safeId = displaySafe(physicalId, { asciiOnly: true });
37290
+ const safeStack = displaySafe(stackName, { asciiOnly: true });
37291
+ const safeLogicalId = displaySafe(logicalId, { asciiOnly: true });
37292
+ const idShown = isInertUnquoted(safeId);
37293
+ const shownId = idShown ? safeId : "a name that cannot be shown safely here";
37294
+ const shownLogicalId = isInertUnquoted(safeLogicalId) ? safeLogicalId : "A resource whose logical id cannot be shown safely here";
37295
+ const diagnosis = replayed ? `${shownLogicalId}: the name AWS reports as taken (${shownId}) is most likely held by a resource THIS create made. An earlier attempt of it ended without a clear verdict (a server error, a dropped connection or a timeout, or a failure after the create call itself may have succeeded), and the retry then found the name taken. A dropped connection can also happen before the request reached AWS, so the holder may be another resource: confirm it is yours before deleting or importing it. cdkd records a resource only once its create succeeds, so this one is in no state file: no rollback or cdkd destroy will remove it, and re-running collides with it again.` : `${shownLogicalId}: the name AWS reports as taken (${shownId}) is one cdkd DERIVED from the logical id, and that derivation has no random component — so this is most likely a resource an earlier cdkd run left behind. A rollback leaves a resource carrying DeletionPolicy: Retain in AWS and drops it from state, as CloudFormation does; what differs is the name. CloudFormation would generate a fresh one for an unnamed resource and redeploy clean, whereas cdkd asks again for the name the orphan still holds — so re-running does not clear this.`;
37296
+ const deleteArm = `If it is not a resource you want to keep, delete ${idShown ? safeId : "it"} in AWS — after confirming it holds nothing you need${replayed ? "" : ", since Retain is what kept it"} — and re-deploy.`;
37297
+ let canImport;
37470
37298
  try {
37471
- createResult = await deps.guardedReplacementCreate({
37472
- logicalId,
37473
- resourceType,
37474
- stackName: input.stackName,
37475
- createdVia: input.createdVia,
37476
- resolvedProps: input.resolvedProps
37477
- }, () => deps.withRetry(() => withCurrentResourceSecrets(secrets, () => input.createProvider.create(logicalId, resourceType, input.createProps, { maskSecrets: createSecretMasker(secrets) })), logicalId, void 0, void 0, input.createProvider));
37478
- } catch (createError) {
37479
- if (!isNameCollisionErrorFrom(createError, logicalId)) throw createError;
37480
- const createFailure = describeAwsFailure(createError);
37481
- const createAwsMsg = displayAwsMessage(maskName(createFailure.detail));
37482
- const createMsg = createFailure.redacted ? displaySafe(maskName(createFailure.summary)).replace(/\.$/, "") : createAwsMsg;
37483
- if (createFailure.redacted) deps.logger.debug(safeMsg`${maskName(logicalId)}: the create-first attempt collided: ${asIsMessage(createAwsMsg)}`);
37484
- throw markNonRetryable(new CdkdError(maskName(`${displaySafe(logicalId)} (${displaySafe(resourceType)}) requires replacement (${input.trigger}), and cdkd created the new resource first because its name differs, but the create collided: ${createMsg}. If the collision is on the requested name: ${renderReplacementNameChange(input.change, input.createProps)}. Nothing was deleted` + (retainOld ? ` (UpdateReplacePolicy: Retain keeps the old resource in place)` : "") + ". Choose a name no other resource holds, or delete the resource holding it if it is yours." + generatedReplacementHolderAdvice({
37485
- stackName: input.stackName,
37486
- logicalId,
37487
- change: input.change,
37488
- oldPhysicalId: currentResource.physicalId,
37489
- mask: (text) => maskName(maskSecretsInText(text, unionOfSecretBags([secrets, printingSecretsFor(deps.secretsRun(), logicalId)])))
37490
- })), "NAMED_REPLACEMENT_COLLISION", createError instanceof Error ? createError : void 0));
37299
+ canImport = typeof providerRegistry.getProvider(error.resourceType).import === "function";
37300
+ } catch {
37301
+ canImport = false;
37302
+ }
37303
+ const commandNamesTheRightResource = safeId === physicalId && safeStack === stackName && safeLogicalId === logicalId;
37304
+ const importableTarget = !stackName.includes("~");
37305
+ if (!canImport || !commandNamesTheRightResource || !importableTarget) return `${diagnosis} ${!canImport ? `cdkd cannot adopt ${displaySafe(error.resourceType, { asciiOnly: true })} back into state (its provider implements no import)` : !importableTarget ? `this is a nested-stack child, whose stack name cdkd import cannot resolve` : `cdkd cannot render an import command that provably names this resource`}, so the way forward is to delete it. ${deleteArm}`;
37306
+ const adopt = pasteableCommand("cdkd import", [{
37307
+ value: stackName,
37308
+ hole: "stack"
37309
+ }, {
37310
+ flag: "--resource",
37311
+ value: `${logicalId}=${physicalId}`,
37312
+ hole: "logicalId=physicalId"
37313
+ }]);
37314
+ return `${diagnosis} To recover, adopt it back into state instead of re-creating it, with the command below (a selective import merges into existing state and needs no --force while the resource is absent from it). CONFIRM IT IS YOURS FIRST — a name cdkd derives is predictable, so for a globally-namespaced type it can belong to another account, and the same stack deployed in another region derives the same name. ${deleteArm}${adopt.withheld.length === 0 ? "" : " The command below prints a quoted hole in place of a value cdkd will not name on a command line; replace it whole, quotes included, with your stack name or '<logicalId>=<name>', shell-quoted."}\nAdopt with: ${adopt.command}`;
37315
+ }
37316
+ function isReplacementNameRefusal(error, logicalId) {
37317
+ let current = error;
37318
+ for (let depth = 0; depth < 10 && current != null; depth++) {
37319
+ if (typeof current !== "object") return false;
37320
+ const linkId = current.logicalId;
37321
+ if (typeof linkId === "string" && linkId !== logicalId) return false;
37322
+ if (current instanceof CdkdError && current.code === "NAMED_REPLACEMENT_COLLISION") return true;
37323
+ current = current.cause;
37324
+ }
37325
+ return false;
37326
+ }
37327
+
37328
+ // src/deployment/superseded-resources.ts
37329
+ function supersededResourcesOf(state) {
37330
+ const rows = state?.supersededResources;
37331
+ if (!Array.isArray(rows)) return [];
37332
+ return rows.filter(isSupersededResourceRecord);
37333
+ }
37334
+ function isSupersededResourceRecord(row) {
37335
+ if (typeof row !== "object" || row === null) return false;
37336
+ const entry = row;
37337
+ const record = entry["state"];
37338
+ if (typeof entry["logicalId"] !== "string") return false;
37339
+ if (typeof record !== "object" || record === null) return false;
37340
+ const { physicalId, resourceType, properties } = record;
37341
+ return typeof physicalId === "string" && physicalId !== "" && typeof resourceType === "string" && resourceType !== "" && typeof properties === "object" && properties !== null && !Array.isArray(properties);
37342
+ }
37343
+ function supersededHolderOf(entry, resources) {
37344
+ const holders = Object.values(resources).filter((record) => typeof record === "object" && record !== null && record.physicalId === entry.state.physicalId);
37345
+ return holders.find((record) => record.resourceType === entry.state.resourceType) ?? holders[0];
37346
+ }
37347
+ function isSupersededHeldBySameType(entry, resources) {
37348
+ return Object.values(resources).some((record) => typeof record === "object" && record !== null && record.physicalId === entry.state.physicalId && record.resourceType === entry.state.resourceType);
37349
+ }
37350
+ function supersededHeldByOtherTypeWarning(entry, holderType) {
37351
+ return `the superseded ${entry.state.resourceType} of ${entry.logicalId} (${entry.state.physicalId}) was not deleted: a ${holderType} record of this stack has the same physical id, and cdkd never deletes an id a record names. If the ${entry.state.resourceType} still exists, delete it by hand; it is no longer tracked in state.`;
37352
+ }
37353
+ function addSuperseded(host, entry) {
37354
+ host.supersededResources = [...(Array.isArray(host.supersededResources) ? host.supersededResources : []).filter((row) => !isSupersededResourceRecord(row) || row.state.physicalId !== entry.state.physicalId || row.state.resourceType !== entry.state.resourceType), entry];
37355
+ }
37356
+ function canRecordSuperseded(record, deleteContext) {
37357
+ if (deleteContext.noEchoDeleteValues !== void 0) return false;
37358
+ if (deleteContext.inlinePolicyClaimed !== void 0) return false;
37359
+ if (Array.isArray(record.noEchoLeaves) && record.noEchoLeaves.length > 0) return false;
37360
+ return !INLINE_POLICY_TYPES.has(record.resourceType);
37361
+ }
37362
+ const INLINE_POLICY_TYPES = /* @__PURE__ */ new Set([
37363
+ "AWS::IAM::Policy",
37364
+ "AWS::IAM::RolePolicy",
37365
+ "AWS::IAM::UserPolicy",
37366
+ "AWS::IAM::GroupPolicy"
37367
+ ]);
37368
+ function removeSuperseded(host, entry) {
37369
+ if (!Array.isArray(host.supersededResources)) return;
37370
+ const remaining = host.supersededResources.filter((row) => row !== entry);
37371
+ if (remaining.length === 0) delete host.supersededResources;
37372
+ else host.supersededResources = remaining;
37373
+ }
37374
+ function supersededAfterRollback(base, pending) {
37375
+ const added = Array.isArray(pending.supersededResources) ? pending.supersededResources : [];
37376
+ if (added.length === 0) return {};
37377
+ return { supersededResources: [...Array.isArray(base.supersededResources) ? base.supersededResources : [], ...added] };
37378
+ }
37379
+ const SUPERSEDED_KEPT_REMEDY = "cdkd keeps it in state: the next `cdkd deploy` of this stack retries the delete, and `cdkd destroy` deletes it";
37380
+ function withoutSuperseded(state) {
37381
+ const { supersededResources: _dropped, ...rest } = state;
37382
+ return rest;
37383
+ }
37384
+ async function deleteSupersededEntry(entry, input) {
37385
+ const record = entry.state;
37386
+ let result;
37387
+ try {
37388
+ const send = () => input.provider.delete(entry.logicalId, record.physicalId, record.resourceType, record.properties, {
37389
+ expectedRegion: input.region,
37390
+ ...entry.forceDataDelete === true && { forceDataDelete: true },
37391
+ ...entry.finalSnapshotIdentifier !== void 0 && { finalSnapshotIdentifier: entry.finalSnapshotIdentifier },
37392
+ deletionPolicy: replacementDeletePolicy(entry.updateReplacePolicy),
37393
+ ...entry.skipFinalSnapshot === true && { skipFinalSnapshot: true },
37394
+ ...input.removeProtection === true && { removeProtection: true },
37395
+ ...input.stackDestroy === true && { stackDestroy: true },
37396
+ recordedAttributes: record.attributes,
37397
+ recordedNoEchoLeaves: record.noEchoLeaves,
37398
+ maskSecrets: input.maskSecrets
37399
+ });
37400
+ result = input.once === true ? await send() : await retryWhileInUse(send, input.stop);
37401
+ } catch (error) {
37402
+ return {
37403
+ kind: "failed",
37404
+ error
37405
+ };
37406
+ }
37407
+ reportDeleteGuards(result, {
37408
+ physicalId: record.physicalId,
37409
+ resourceType: record.resourceType,
37410
+ provisionedBy: record.provisionedBy
37411
+ });
37412
+ const reason = deleteSkipReason(result);
37413
+ return reason === void 0 ? { kind: "deleted" } : {
37414
+ kind: "notDeleted",
37415
+ reason
37416
+ };
37417
+ }
37418
+ const supersededInUseRetry = {
37419
+ attempts: 6,
37420
+ delayMs: 1e4
37421
+ };
37422
+ const IN_USE_ERROR_NAMES = /* @__PURE__ */ new Set([
37423
+ "ResourceInUseException",
37424
+ "ResourceInUse",
37425
+ "DependencyViolation"
37426
+ ]);
37427
+ const IN_USE_CONFLICT = /\bare using it\b/;
37428
+ function isInUseRefusal(error) {
37429
+ for (let current = error, depth = 0; current !== void 0 && depth < 8; depth++) {
37430
+ if (typeof current !== "object" || current === null) return false;
37431
+ const { name, message } = current;
37432
+ if (typeof name === "string" && IN_USE_ERROR_NAMES.has(name)) return true;
37433
+ if (name === "ConflictException" && typeof message === "string" && IN_USE_CONFLICT.test(message)) return true;
37434
+ current = current.cause;
37435
+ }
37436
+ return false;
37437
+ }
37438
+ async function retryWhileInUse(send, stop) {
37439
+ for (let attempt = 1;; attempt++) try {
37440
+ return await send();
37441
+ } catch (error) {
37442
+ if (attempt >= supersededInUseRetry.attempts || stop() || !isInUseRefusal(error)) throw error;
37443
+ await new Promise((resolve) => setTimeout(resolve, supersededInUseRetry.delayMs));
37444
+ if (stop()) throw error;
37445
+ }
37446
+ }
37447
+ function holdsSupersededResources(record) {
37448
+ const rows = record.supersededResources;
37449
+ return rows !== void 0 && (!Array.isArray(rows) || rows.length > 0);
37450
+ }
37451
+
37452
+ // src/deployment/rollback-executor/replay-scope.ts
37453
+ function withReplayDeletePrinting(scope, fn) {
37454
+ const deployBag = scope.ctx.logOnlyNeedlesFor?.(scope.op.logicalId);
37455
+ return withPrintingSecrets(scope.secrets, () => deployBag === void 0 ? fn() : withPrintingSecrets(deployBag, fn));
37456
+ }
37457
+ function noteRolledBackCreate(scope, op, record) {
37458
+ if (op.changeType !== "CREATE") return;
37459
+ const create = {
37460
+ logicalId: op.logicalId,
37461
+ record,
37462
+ ...op.nameGeneration !== void 0 && { nameGeneration: op.nameGeneration }
37463
+ };
37464
+ scope.result.rolledBackCreates.push(create);
37465
+ scope.onRolledBackCreate?.(create);
37466
+ }
37467
+
37468
+ // src/deployment/rollback-executor/replaced-survivor.ts
37469
+ function replacedDeleteFailureVerdict(error) {
37470
+ if (isDeleteStarted(error)) return "unconfirmed";
37471
+ return isRefusedByName(error) ? "kept" : "unconfirmed";
37472
+ }
37473
+ const REPLACED_SURVIVOR_PROBE_TIMEOUT_MS = 3e4;
37474
+ const INTERRUPT_POLL_MS = 250;
37475
+ async function probeReplacedSurvivor(s, oldType, timeoutMs = REPLACED_SURVIVOR_PROBE_TIMEOUT_MS) {
37476
+ if (s.isInterrupted?.() === true) return "interrupted";
37477
+ let timer;
37478
+ let poll;
37479
+ const stopped = new Promise((resolve) => {
37480
+ timer = setTimeout(() => resolve("unknown"), timeoutMs);
37481
+ if (s.isInterrupted !== void 0) {
37482
+ const interrupted = s.isInterrupted;
37483
+ poll = setInterval(() => {
37484
+ if (interrupted()) resolve("interrupted");
37485
+ }, INTERRUPT_POLL_MS);
37486
+ }
37487
+ });
37488
+ try {
37489
+ return await Promise.race([readSurvivor(s, oldType), stopped]);
37490
+ } finally {
37491
+ clearTimeout(timer);
37492
+ clearInterval(poll);
37493
+ }
37494
+ }
37495
+ async function readSurvivor(s, oldType) {
37496
+ const prev = s.op.previousState;
37497
+ const physicalId = prev?.physicalId;
37498
+ if (typeof physicalId !== "string" || physicalId === "") return "unknown";
37499
+ try {
37500
+ const { provider } = s.ctx.providerRegistry.getProviderFor({
37501
+ resourceType: oldType,
37502
+ provisionedBy: prev?.provisionedBy
37503
+ });
37504
+ if (typeof provider.readCurrentState !== "function") return "unreadable";
37505
+ const read = await withReplayDeletePrinting(s, () => provider.readCurrentState(physicalId, s.op.logicalId, oldType, prev?.properties));
37506
+ if (read === RESOURCE_NOT_FOUND) return "gone";
37507
+ if (read === void 0) return "unreadable";
37508
+ if (typeof read !== "object" || read === null || Array.isArray(read)) return "unknown";
37509
+ return Object.keys(read).length > 0 ? "exists" : "unreadable";
37510
+ } catch {
37511
+ return "unknown";
37491
37512
  }
37492
- if (input.equalIdIsSameResource && createResult.physicalId === currentResource.physicalId) throw markNonRetryable(new CdkdError(maskName(`${displaySafe(logicalId)} (${displaySafe(resourceType)}) requires replacement (${input.trigger}) under a new name, but the create returned the resource being replaced (${displaySafe(currentResource.physicalId)}) instead of a new one, so cdkd cannot tell which name it holds. Nothing was deleted. Delete that resource by hand if it is yours, then re-run the deploy.`), "NAMED_REPLACEMENT_IDEMPOTENT_CREATE"));
37493
- if (retainOld) return createResult;
37494
- deps.logger.info(safeMsg` Deleting old ${logicalId} (${displayPhysicalId(currentResource.resourceType, currentResource.physicalId)})...`);
37495
- await deleteReplacedAfterCreate(run, deps, logicalId, input.oldResourceType, currentResource, input.deleteProvider, input.deleteProperties, finalSnapshotIdentifier, input.deletePolicy, secrets, input.deleteProvisionedBy, input.noEchoDeleteValues);
37496
- return createResult;
37497
37513
  }
37514
+
37515
+ // src/deployment/deploy-engine/replacement/delete-replaced.ts
37498
37516
  async function deleteReplacedAfterCreate(run, deps, logicalId, oldResourceType, currentResource, deleteProvider, deleteProperties, finalSnapshotIdentifier, updateReplacePolicy, secrets, deleteProvisionedBy, noEchoDeleteValues, isRetry = false) {
37499
37517
  let deleteResult = void 0;
37500
37518
  let deleteFailed = false;
@@ -37568,6 +37586,88 @@ async function deleteReplacedAfterCreate(run, deps, logicalId, oldResourceType,
37568
37586
  deps.logger.info(isRetry ? safeMsg` ${green("✓")} Old ${logicalId} (${currentResource.physicalId}) deleted` : safeMsg` ${green("✓")} Old resource deleted`);
37569
37587
  }
37570
37588
  }
37589
+
37590
+ // src/deployment/deploy-engine/replacement/create-first.ts
37591
+ async function createFirstThenDeleteOld(run, deps, input) {
37592
+ const { logicalId, resourceType, currentResource, secrets } = input;
37593
+ const retainOld = input.retainOld === true;
37594
+ const finalSnapshotIdentifier = retainOld ? void 0 : await prepareFinalSnapshotForDelete(deps, logicalId, input.oldResourceType, currentResource, input.snapshotPolicy, createUnionSecretMasker([secrets, secretNameBagFor(deps.secretsRun(), logicalId)]));
37595
+ deps.logger.info(retainOld ? safeMsg` ${logicalId}'s new name differs from the one the old resource holds — creating the new resource (the old one is retained)...` : safeMsg` ${logicalId}'s new name differs from the one the old resource holds — creating the new resource before deleting the old one...`);
37596
+ const maskName = maskRewrittenSentName(resourceType, input.createProps, logicalId, (text) => maskSecretsInText(text, secrets));
37597
+ let createResult;
37598
+ try {
37599
+ createResult = await deps.guardedReplacementCreate({
37600
+ logicalId,
37601
+ resourceType,
37602
+ stackName: input.stackName,
37603
+ createdVia: input.createdVia,
37604
+ resolvedProps: input.resolvedProps
37605
+ }, () => deps.withRetry(() => withCurrentResourceSecrets(secrets, () => input.createProvider.create(logicalId, resourceType, input.createProps, { maskSecrets: createSecretMasker(secrets) })), logicalId, void 0, void 0, input.createProvider));
37606
+ } catch (createError) {
37607
+ if (!isNameCollisionErrorFrom(createError, logicalId)) throw createError;
37608
+ const createFailure = describeAwsFailure(createError);
37609
+ const createAwsMsg = displayAwsMessage(maskName(createFailure.detail));
37610
+ const createMsg = createFailure.redacted ? displaySafe(maskName(createFailure.summary)).replace(/\.$/, "") : createAwsMsg;
37611
+ if (createFailure.redacted) deps.logger.debug(safeMsg`${maskName(logicalId)}: the create-first attempt collided: ${asIsMessage(createAwsMsg)}`);
37612
+ throw markNonRetryable(new CdkdError(maskName(`${displaySafe(logicalId)} (${displaySafe(resourceType)}) requires replacement (${input.trigger}), and cdkd created the new resource first because its name differs, but the create collided: ${createMsg}. If the collision is on the requested name: ${renderReplacementNameChange(input.change, input.createProps)}. Nothing was deleted` + (retainOld ? ` (UpdateReplacePolicy: Retain keeps the old resource in place)` : "") + ". Choose a name no other resource holds, or delete the resource holding it if it is yours." + generatedReplacementHolderAdvice({
37613
+ stackName: input.stackName,
37614
+ logicalId,
37615
+ change: input.change,
37616
+ oldPhysicalId: currentResource.physicalId,
37617
+ mask: (text) => maskName(maskSecretsInText(text, unionOfSecretBags([secrets, printingSecretsFor(deps.secretsRun(), logicalId)])))
37618
+ })), "NAMED_REPLACEMENT_COLLISION", createError instanceof Error ? createError : void 0));
37619
+ }
37620
+ if (input.equalIdIsSameResource && createResult.physicalId === currentResource.physicalId) throw markNonRetryable(new CdkdError(maskName(`${displaySafe(logicalId)} (${displaySafe(resourceType)}) requires replacement (${input.trigger}) under a new name, but the create returned the resource being replaced (${displaySafe(currentResource.physicalId)}) instead of a new one, so cdkd cannot tell which name it holds. Nothing was deleted. Delete that resource by hand if it is yours, then re-run the deploy.`), "NAMED_REPLACEMENT_IDEMPOTENT_CREATE"));
37621
+ if (retainOld) return createResult;
37622
+ deps.logger.info(safeMsg` Deleting old ${logicalId} (${displayPhysicalId(currentResource.resourceType, currentResource.physicalId)})...`);
37623
+ await deleteReplacedAfterCreate(run, deps, logicalId, input.oldResourceType, currentResource, input.deleteProvider, input.deleteProperties, finalSnapshotIdentifier, input.deletePolicy, secrets, input.deleteProvisionedBy, input.noEchoDeleteValues);
37624
+ return createResult;
37625
+ }
37626
+
37627
+ // src/deployment/stack-records-scope.ts
37628
+ async function awaitInFlightSibling(view, self, sibling) {
37629
+ const waiting = view.waiting;
37630
+ if (waiting === void 0 || waiting.has(sibling.logicalId)) return void 0;
37631
+ waiting.add(self);
37632
+ try {
37633
+ return await sibling.settled;
37634
+ } finally {
37635
+ waiting.delete(self);
37636
+ }
37637
+ }
37638
+ const stackRecordsStore = new AsyncLocalStorage();
37639
+ function withStackRecords(view, fn) {
37640
+ return stackRecordsStore.run(view, fn);
37641
+ }
37642
+ function getStackRecords() {
37643
+ return stackRecordsStore.getStore();
37644
+ }
37645
+ function deployStackRecordsView(records, before, deleting, unsettled = () => false, inFlight) {
37646
+ const settled = () => Object.entries(records).filter(([lid]) => !unsettled(lid));
37647
+ return {
37648
+ ...inFlight && {
37649
+ inFlight,
37650
+ waiting: /* @__PURE__ */ new Set()
37651
+ },
37652
+ live: settled,
37653
+ survivors: () => [...settled().filter(([lid]) => !deleting.has(lid)), ...Object.entries(before).filter(([lid, record]) => deleting.has(lid) && shouldRetainResource(record.deletionPolicy))]
37654
+ };
37655
+ }
37656
+ function destroyStackRecordsView(records) {
37657
+ return {
37658
+ live: () => Object.entries(records),
37659
+ survivors: () => Object.entries(records).filter(([, record]) => shouldRetainResource(record.deletionPolicy))
37660
+ };
37661
+ }
37662
+ function replayStackRecordsView(records, orphanLogicalIds = /* @__PURE__ */ new Set()) {
37663
+ const kept = Object.entries(records).filter(([lid, record]) => record.deletionPolicy === "Retain" || orphanLogicalIds.has(lid));
37664
+ return {
37665
+ live: () => Object.entries(records),
37666
+ survivors: () => [...Object.entries(records), ...kept.filter(([lid]) => !Object.hasOwn(records, lid))]
37667
+ };
37668
+ }
37669
+
37670
+ // src/deployment/deploy-engine/replacement/deferred-deletes.ts
37571
37671
  async function retryDeferredReplacedDeletes(run, deps, stackName, counts) {
37572
37672
  const deferred = run.deferredReplacedDeletes;
37573
37673
  run.deferredReplacedDeletes = void 0;
@@ -37645,31 +37745,69 @@ const DEFAULT_UNSETTLED_REVERT_WAIT = {
37645
37745
  pollMs: 1e4
37646
37746
  };
37647
37747
 
37648
- // src/analyzer/skipped-outputs.ts
37649
- function canonicalJson$3(value) {
37650
- return JSON.stringify(value, (_key, v) => {
37651
- if (v !== null && typeof v === "object" && !Array.isArray(v)) {
37652
- const sorted = Object.create(null);
37653
- for (const k of Object.keys(v).sort()) sorted[k] = v[k];
37654
- return sorted;
37655
- }
37656
- return v;
37657
- });
37658
- }
37659
- const NO_ECHO_DEFAULT_MASK = "<cdkd:noecho-default>";
37660
- function withNoEchoDefaultsMasked(parameters) {
37661
- if (parameters === null || typeof parameters !== "object" || Array.isArray(parameters)) return parameters;
37662
- const masked = Object.create(null);
37663
- for (const [name, decl] of Object.entries(parameters)) {
37664
- const body = decl;
37665
- masked[name] = typeof body === "object" && body !== null && declaresNoEcho(body) && "Default" in body ? {
37666
- ...body,
37667
- Default: NO_ECHO_DEFAULT_MASK
37668
- } : decl;
37669
- }
37670
- return masked;
37671
- }
37672
- function skippedOutputDigest(template, outputKey) {
37748
+ // src/deployment/deploy-engine/outputs/run-state.ts
37749
+ var OutputsRunState = class {
37750
+ outputSecrets = /* @__PURE__ */ new Map();
37751
+ outputsPassSecretMaps = [];
37752
+ outputsTemplateSource = Object.create(null);
37753
+ resolvedExportNames = [];
37754
+ carriedExportAliasRefusal;
37755
+ skippedOutputs;
37756
+ outputsSourceUsable = true;
37757
+ outputProvenanceSinks = /* @__PURE__ */ new Map();
37758
+ outputsResolvedThisRun = /* @__PURE__ */ new WeakSet();
37759
+ resolvedOutputsBag = void 0;
37760
+ };
37761
+
37762
+ // src/deployment/deploy-engine/outputs/failure.ts
37763
+ const EXPORT_NAME_SCOPE = {
37764
+ pairs: "withhold",
37765
+ "log-only": "carry",
37766
+ "mask-only-marks": "withhold",
37767
+ "reference-provenance": "withhold",
37768
+ "physical-name-copies": "withhold",
37769
+ "public-proofs": "withhold"
37770
+ };
37771
+ function handleOutputResolutionFailure(deps, error, outputKey, outputs, secrets, inheritedSecrets) {
37772
+ const union = unionOfSecretBags([inheritedSecrets, secrets]);
37773
+ const detail = maskSecretsInText(error instanceof Error ? error.message || error.name : safeStringify$1(error), union);
37774
+ if (deps.options.strictGetAtt) {
37775
+ const cause = typeof error === "string" ? maskSecretsInText(error, union) : maskSecretsInError(error, union);
37776
+ const failure = error instanceof Error ? describeAwsFailure(error) : void 0;
37777
+ const refusalText = (text) => safeMsg`Failed to resolve output ${outputKey} ` + `(--strict-getatt promotes output resolution failures to deploy errors; ` + safeMsg`drop the flag to skip the output instead): ${asIsMessage(text)}`;
37778
+ if (failure?.redacted === true) deps.logger.debug(refusalText(detail));
37779
+ const refusal = new Error(refusalText(failure?.redacted === true ? failure.summary : detail), cause instanceof Error || typeof cause === "string" ? { cause } : {});
37780
+ throw failure?.redacted === true && cause instanceof Error ? markRedactedCause(refusal) : refusal;
37781
+ }
37782
+ deps.logger.warn(safeMsg`Failed to resolve output ${outputKey}: ${asIsMessage(detail)}`);
37783
+ outputs[outputKey] = void 0;
37784
+ }
37785
+
37786
+ // src/analyzer/skipped-outputs.ts
37787
+ function canonicalJson$3(value) {
37788
+ return JSON.stringify(value, (_key, v) => {
37789
+ if (v !== null && typeof v === "object" && !Array.isArray(v)) {
37790
+ const sorted = Object.create(null);
37791
+ for (const k of Object.keys(v).sort()) sorted[k] = v[k];
37792
+ return sorted;
37793
+ }
37794
+ return v;
37795
+ });
37796
+ }
37797
+ const NO_ECHO_DEFAULT_MASK = "<cdkd:noecho-default>";
37798
+ function withNoEchoDefaultsMasked(parameters) {
37799
+ if (parameters === null || typeof parameters !== "object" || Array.isArray(parameters)) return parameters;
37800
+ const masked = Object.create(null);
37801
+ for (const [name, decl] of Object.entries(parameters)) {
37802
+ const body = decl;
37803
+ masked[name] = typeof body === "object" && body !== null && declaresNoEcho(body) && "Default" in body ? {
37804
+ ...body,
37805
+ Default: NO_ECHO_DEFAULT_MASK
37806
+ } : decl;
37807
+ }
37808
+ return masked;
37809
+ }
37810
+ function skippedOutputDigest(template, outputKey) {
37673
37811
  const sections = Object.create(null);
37674
37812
  for (const [section, body] of Object.entries(template)) {
37675
37813
  if (section === "Resources" || section === "Outputs") continue;
@@ -37972,41 +38110,7 @@ function exportAliasCollisionScrubWarning(outputKey, exportName, secrets) {
37972
38110
  return `Output ${ownerDisplay.kind === "withheld" && exportDisplay.kind === "withheld" ? "<the owning output, name withheld: contains a secret>" : displayTextOrWithheld(ownerDisplay)} exports as ${exportDisplay.kind === "withheld" ? shown : `"${shown}"`}, which is also the name of another output in this stack — state cannot say which of the two ${storedUnder} came from, so that key is redacted by value match instead of by template position, and two references resolving to the same value could still collapse there. Rename the export, or the colliding output, and redeploy.`;
37973
38111
  }
37974
38112
 
37975
- // src/deployment/deploy-engine/outputs.ts
37976
- var OutputsRunState = class {
37977
- outputSecrets = /* @__PURE__ */ new Map();
37978
- outputsPassSecretMaps = [];
37979
- outputsTemplateSource = Object.create(null);
37980
- resolvedExportNames = [];
37981
- carriedExportAliasRefusal;
37982
- skippedOutputs;
37983
- outputsSourceUsable = true;
37984
- outputProvenanceSinks = /* @__PURE__ */ new Map();
37985
- outputsResolvedThisRun = /* @__PURE__ */ new WeakSet();
37986
- resolvedOutputsBag = void 0;
37987
- };
37988
- const EXPORT_NAME_SCOPE = {
37989
- pairs: "withhold",
37990
- "log-only": "carry",
37991
- "mask-only-marks": "withhold",
37992
- "reference-provenance": "withhold",
37993
- "physical-name-copies": "withhold",
37994
- "public-proofs": "withhold"
37995
- };
37996
- function handleOutputResolutionFailure(deps, error, outputKey, outputs, secrets, inheritedSecrets) {
37997
- const union = unionOfSecretBags([inheritedSecrets, secrets]);
37998
- const detail = maskSecretsInText(error instanceof Error ? error.message || error.name : safeStringify$1(error), union);
37999
- if (deps.options.strictGetAtt) {
38000
- const cause = typeof error === "string" ? maskSecretsInText(error, union) : maskSecretsInError(error, union);
38001
- const failure = error instanceof Error ? describeAwsFailure(error) : void 0;
38002
- const refusalText = (text) => safeMsg`Failed to resolve output ${outputKey} ` + `(--strict-getatt promotes output resolution failures to deploy errors; ` + safeMsg`drop the flag to skip the output instead): ${asIsMessage(text)}`;
38003
- if (failure?.redacted === true) deps.logger.debug(refusalText(detail));
38004
- const refusal = new Error(refusalText(failure?.redacted === true ? failure.summary : detail), cause instanceof Error || typeof cause === "string" ? { cause } : {});
38005
- throw failure?.redacted === true && cause instanceof Error ? markRedactedCause(refusal) : refusal;
38006
- }
38007
- deps.logger.warn(safeMsg`Failed to resolve output ${outputKey}: ${asIsMessage(detail)}`);
38008
- outputs[outputKey] = void 0;
38009
- }
38113
+ // src/deployment/deploy-engine/outputs/resolve.ts
38010
38114
  async function resolveOutputs(run, deps, template, resources, stackName, digestSource, parameterValues, conditions) {
38011
38115
  run.resolvedExportNames = [];
38012
38116
  run.carriedExportAliasRefusal = void 0;
@@ -43136,349 +43240,236 @@ function preparePropertiesForCcApi(providerRegistry, resourceType, resolvedProps
43136
43240
  return applyDefaultNameForFallback(logicalId, resourceType, resolvedProps, underivable);
43137
43241
  }
43138
43242
 
43139
- // src/provisioning/nested-stack-context.ts
43140
- const storage = new AsyncLocalStorage();
43141
- function withNestedStackContext(ctx, fn) {
43142
- return storage.run(ctx, fn);
43143
- }
43144
- function getCurrentNestedStackContext() {
43145
- return storage.getStore();
43243
+ // src/deployment/orphan-adoption.ts
43244
+ function templateStillDeclares(template, record, nameProperties) {
43245
+ const declared = template.Resources?.[record.logicalId];
43246
+ if (!declared) return false;
43247
+ if (declared.Type !== record.state.resourceType) return false;
43248
+ const properties = declared.Properties ?? {};
43249
+ return ![...nameProperties, ...alternateNamePropertiesFor(declared.Type)].some((p) => properties[p] !== void 0 && properties[p] !== null);
43146
43250
  }
43147
- async function collectNestedChildUnaddressed(fn) {
43148
- const ctx = storage.getStore();
43149
- if (!ctx) return {
43150
- value: await fn(),
43151
- unaddressed: void 0
43152
- };
43153
- const slot = {};
43154
- return {
43155
- value: await storage.run({
43156
- ...ctx,
43157
- childUnaddressed: slot
43158
- }, fn),
43159
- unaddressed: slot.last
43251
+ const ADOPTION_REFUSED_TYPES = /* @__PURE__ */ new Set(["AWS::Lambda::LayerVersion", "AWS::ECS::TaskDefinition"]);
43252
+ async function planOrphanAdoption(params) {
43253
+ const outcome = {
43254
+ adopted: {},
43255
+ remaining: [],
43256
+ refusals: [],
43257
+ notices: [],
43258
+ warnings: []
43160
43259
  };
43161
- }
43162
-
43163
- // src/deployment/nested-child-journal.ts
43164
- const NESTED_PENDING_PARENT_REASON = "nested-pending-parent";
43165
- const NESTED_STACK_TYPE$2 = "AWS::CloudFormation::Stack";
43166
- const MAX_NESTED_WALK_DEPTH = 32;
43167
- function nestedChildStackName(parentStackName, logicalId) {
43168
- return `${parentStackName}~${logicalId}`;
43169
- }
43170
- function nestedPendingSnapshot(state, refusesExportName) {
43171
- const outputs = { ...isPlainRecord(state.outputs) ? state.outputs : {} };
43172
- let exportNames = Array.isArray(state.exportNames) ? [...state.exportNames] : void 0;
43173
- const refused = new Set(importableOutputKeys(state).filter((name) => refusesExportName(name)));
43174
- if (refused.size > 0) {
43175
- for (const name of refused) Reflect.deleteProperty(outputs, name);
43176
- if (exportNames !== void 0) exportNames = exportNames.filter((name) => !refused.has(name));
43177
- }
43178
- return {
43179
- previousOutputs: {
43180
- outputs,
43181
- ...exportNames !== void 0 && { exportNames }
43182
- },
43183
- previousCrossStackReads: {
43184
- ...Array.isArray(state.imports) && { imports: [...state.imports] },
43185
- ...Array.isArray(state.outputReads) && { outputReads: [...state.outputReads] }
43260
+ if (params.records.length === 0) return outcome;
43261
+ if (params.newScheme === true) {
43262
+ for (const record of params.records) {
43263
+ if (params.managedLogicalIds.has(record.logicalId)) continue;
43264
+ outcome.remaining.push(record);
43265
+ if ((params.template.Resources?.[record.logicalId])?.Type !== record.state.resourceType) continue;
43266
+ outcome.warnings.push(`${displayIdent(record.logicalId)} (${displayIdent(record.state.resourceType)}) was left in AWS by an earlier rollback as ${displaySafe(record.state.physicalId)} (DeletionPolicy: Retain). This deploy does not take it back: it creates a new resource under a new name, as CloudFormation does. To manage the kept resource again, adopt it with 'cdkd import'.`);
43186
43267
  }
43187
- };
43188
- }
43189
- function displacedPhysicalIdShown(op, logger, physicalId = journalOpPhysicalId(op)) {
43190
- if (physicalId === void 0) return void 0;
43191
- const masker = createOpMasker(logger, /* @__PURE__ */ new Map());
43192
- for (const properties of [
43193
- op.properties,
43194
- op.attemptedProperties,
43195
- op.previousState?.properties
43196
- ]) {
43197
- if (properties === void 0) continue;
43198
- masker.addNamed({
43199
- resourceType: op.resourceType,
43200
- properties,
43201
- logicalId: op.logicalId,
43202
- physicalIds: [physicalId]
43203
- });
43204
- }
43205
- return displaySafe(String(masker.mask(physicalId)));
43206
- }
43207
- function displacedOpClause(op, marks, logger) {
43208
- const retainedOld = retainedOldPhysicalId(op);
43209
- if (retainedOld !== void 0 && marks.some((m) => isMarkFor(m, op))) {
43210
- const shownOld = displacedPhysicalIdShown(op, logger, retainedOld);
43211
- return `replaced ${shownOld} ${op.oldResourceRetained === true ? "but kept it (UpdateReplacePolicy: Retain)" : op.oldResourceMaySurvive !== void 0 ? "and may have kept it (its delete was not confirmed)" : "and may have kept it (the journal records no verdict)"}; cdkd import adopted the replacement, so ${shownOld} is left untracked`;
43268
+ return outcome;
43212
43269
  }
43213
- const shownId = displacedPhysicalIdShown(op, logger);
43214
- return shownId !== void 0 ? `recorded ${shownId}, which cdkd import has since replaced under this id` : "recorded no physical id, and cdkd import has since put another resource under this id";
43215
- }
43216
- function recordDisplacedSkips(recordEvent, stackName, ops) {
43217
- for (const op of ops) recordEvent?.({
43218
- eventType: "ROLLBACK_RESOURCE_SKIPPED",
43219
- stackName,
43220
- operation: op.changeType,
43221
- logicalId: op.logicalId,
43222
- resourceType: op.resourceType,
43223
- ...op.provisionedBy && { provisionedBy: op.provisionedBy },
43224
- reason: "cdkd import has since put another resource under this logical id, so the op was not reverted; check the resource it recorded by hand"
43225
- });
43226
- }
43227
- function revertedNestedRowIds(ops) {
43228
- return ops.filter((op) => op.resourceType === NESTED_STACK_TYPE$2 && op.changeType === "UPDATE").map((op) => op.logicalId);
43229
- }
43230
- const revertRunStorage = new AsyncLocalStorage();
43231
- function withNestedRevertRun(runId, fn) {
43232
- const run = {
43233
- runId,
43234
- settled: /* @__PURE__ */ new Map(),
43235
- warnings: 0
43236
- };
43237
- return revertRunStorage.run(run, () => fn(run));
43238
- }
43239
- function getNestedRevertRun() {
43240
- return revertRunStorage.getStore();
43241
- }
43242
- function errorText(error) {
43243
- return displaySafe(describeAwsFailure(error).detail);
43244
- }
43245
- function isPlainRecord(value) {
43246
- return typeof value === "object" && value !== null && !Array.isArray(value);
43247
- }
43248
- async function dropNestedChildJournals(args) {
43249
- const { stateBackend, parentStackName, region, resources, logger } = args;
43250
- const depth = args.depth ?? 0;
43251
- if (!isPlainRecord(resources)) return;
43252
- if (depthExceeded(depth, parentStackName, logger)) return;
43253
- for (const [logicalId, record] of Object.entries(resources)) {
43254
- if (!isPlainRecord(record) || record["resourceType"] !== NESTED_STACK_TYPE$2) continue;
43255
- const child = nestedChildStackName(parentStackName, logicalId);
43270
+ let siblingClaims;
43271
+ const claims = async () => siblingClaims ??= await params.readSiblingClaims();
43272
+ for (const record of params.records) {
43273
+ const { logicalId, state } = record;
43274
+ const shownId = displayIdent(logicalId);
43275
+ const shownType = displayIdent(state.resourceType);
43276
+ const shownPhysicalId = displaySafe(state.physicalId);
43277
+ if (params.managedLogicalIds.has(logicalId)) {
43278
+ params.logger.debug(`orphan ${shownId}: already present in state.resources — dropping the stale record`);
43279
+ continue;
43280
+ }
43281
+ let provider;
43256
43282
  try {
43257
- const data = await stateBackend.getState(child, region);
43258
- if (data && isPlainRecord(data.state) && isPlainRecord(data.state.resources) && (data.state.stackName === void 0 || data.state.stackName === child)) await dropNestedChildJournals({
43259
- ...args,
43260
- parentStackName: child,
43261
- resources: data.state.resources,
43262
- depth: depth + 1
43263
- });
43283
+ provider = params.getProvider(state.resourceType, state.provisionedBy);
43264
43284
  } catch (error) {
43265
- warnUncleared(logger, child, error);
43285
+ outcome.remaining.push(record);
43286
+ outcome.notices.push(`${shownId} (${shownType}) is still in AWS as ${shownPhysicalId} from an earlier rollback, but this build cannot route that type (${displayAwsMessage(describeAwsFailure(error).detail)}) — cdkd is not adopting it.`);
43287
+ continue;
43288
+ }
43289
+ if (!provider.import) {
43290
+ outcome.remaining.push(record);
43291
+ outcome.notices.push(`${shownId} (${shownType}) was left in AWS by an earlier rollback as ${shownPhysicalId}, but its provider cannot verify it — cdkd is not adopting it.`);
43292
+ continue;
43266
43293
  }
43294
+ let found;
43267
43295
  try {
43268
- if (await withChildLock(args.lockManager, child, region, logger, async () => {
43269
- if (args.beforeDelete) {
43270
- if (!await args.beforeDelete(child, await readOwnRecord(stateBackend, child, region))) return false;
43271
- }
43272
- let gone;
43273
- try {
43274
- gone = await stateBackend.deleteRollbackJournal(child, region);
43275
- } catch (error) {
43276
- await args.onDeleteFailed?.(child);
43277
- throw error;
43278
- }
43279
- if (gone === false) {
43280
- await args.onDeleteFailed?.(child);
43281
- return false;
43282
- }
43283
- return true;
43284
- })) logger.debug(safeMsg`Deleted the rollback journal of nested stack ${displaySafe(child)}`);
43296
+ found = await provider.import({
43297
+ logicalId,
43298
+ resourceType: state.resourceType,
43299
+ stackName: params.stackName,
43300
+ region: params.region,
43301
+ properties: state.properties,
43302
+ knownPhysicalId: state.physicalId
43303
+ });
43285
43304
  } catch (error) {
43286
- warnUncleared(logger, child, error);
43305
+ outcome.notices.push(`${shownId} (${shownType}) is recorded as left in AWS as ${shownPhysicalId}, but cdkd could not confirm it exists (${displayAwsMessage(describeAwsFailure(error).detail)}) — keeping the record and not adopting it this run.`);
43306
+ outcome.remaining.push(record);
43307
+ continue;
43308
+ }
43309
+ if (found !== null && found.physicalId !== state.physicalId) {
43310
+ outcome.remaining.push(record);
43311
+ outcome.notices.push(`${shownId} (${shownType}): cdkd asked about ${shownPhysicalId} and its provider answered for ${displaySafe(found.physicalId)} — not adopting.`);
43312
+ continue;
43313
+ }
43314
+ if (found === null) {
43315
+ params.logger.debug(`orphan ${shownId}: ${shownPhysicalId} no longer exists in AWS — dropping the record`);
43316
+ continue;
43317
+ }
43318
+ if (params.nameProperties(state.resourceType).length === 0 || ADOPTION_REFUSED_TYPES.has(state.resourceType)) {
43319
+ outcome.remaining.push(record);
43320
+ const why = ADOPTION_REFUSED_TYPES.has(state.resourceType) ? "a new deploy of it mints a new resource rather than colliding, and cdkd cannot update one in place — so adopting it would end in a replacement that destroys what DeletionPolicy: Retain preserved" : "cdkd does not derive that resource's physical name, so a new deploy mints a new resource instead of colliding";
43321
+ outcome.notices.push(`${shownId} (${shownType}) is still in AWS as ${shownPhysicalId} from an earlier rollback. cdkd does not re-adopt this type: ${why}. Delete it yourself when you no longer need it.`);
43322
+ continue;
43323
+ }
43324
+ if (!templateStillDeclares(params.template, record, params.nameProperties(state.resourceType))) {
43325
+ outcome.remaining.push(record);
43326
+ outcome.notices.push(`${shownId} (${shownType}) is still in AWS as ${shownPhysicalId} from an earlier rollback. This deploy does not create it under that name, so cdkd is leaving it alone.`);
43327
+ continue;
43328
+ }
43329
+ if ((await claims()).has(state.physicalId)) {
43330
+ outcome.refusals.push(`${shownId}: ${shownPhysicalId} is already recorded by another cdkd stack. cdkd will not adopt a resource another stack manages.`);
43331
+ outcome.remaining.push(record);
43332
+ continue;
43333
+ }
43334
+ const refreshed = Object.create(null);
43335
+ for (const [key, value] of Object.entries(found.attributes ?? {})) {
43336
+ if (carriesSecretMask(value)) continue;
43337
+ refreshed[key] = value;
43287
43338
  }
43339
+ const mergedAttributes = Object.create(null);
43340
+ for (const [key, value] of Object.entries(refreshed)) mergedAttributes[key] = value;
43341
+ for (const [key, value] of Object.entries(state.attributes ?? {})) mergedAttributes[key] = value;
43342
+ outcome.adopted[logicalId] = {
43343
+ ...state,
43344
+ ...Object.keys(mergedAttributes).length > 0 || state.attributes ? { attributes: mergedAttributes } : {}
43345
+ };
43288
43346
  }
43347
+ return outcome;
43289
43348
  }
43290
- async function readOwnRecord(stateBackend, child, region) {
43291
- try {
43292
- const data = await stateBackend.getState(child, region);
43293
- if (data && isPlainRecord(data.state) && isPlainRecord(data.state.resources) && (data.state.stackName === void 0 || data.state.stackName === child)) return data.state;
43294
- } catch {}
43295
- }
43296
- async function dropSettledNestedJournals(args) {
43297
- const { stateBackend, parentStackName, region, runId, logger } = args;
43298
- const depth = args.depth ?? 0;
43299
- if (runId === void 0) return;
43300
- if (depthExceeded(depth, parentStackName, logger)) return;
43301
- const isSettled = (segment) => segment.runId === runId && segment.reason === "nested-pending-parent";
43302
- for (const [logicalId, grandchildren] of args.settled) {
43303
- const child = nestedChildStackName(parentStackName, logicalId);
43304
- if (grandchildren.size > 0) await dropSettledNestedJournals({
43305
- ...args,
43306
- parentStackName: child,
43307
- settled: grandchildren,
43308
- depth: depth + 1
43309
- });
43349
+ const NAMED_UNREADABLE_SIBLING_ROWS = 5;
43350
+ function makeSiblingClaimReader(params) {
43351
+ const { stateBackend, selfStackName, selfRegion, logger } = params;
43352
+ return async () => {
43353
+ const claimed = /* @__PURE__ */ new Set();
43354
+ let refs;
43310
43355
  try {
43311
- const removed = await withChildLock(args.lockManager, child, region, logger, () => stateBackend.dropRollbackJournalSegments(child, region, isSettled));
43312
- if (removed > 0) logger.debug(safeMsg`Dropped ${removed} settled rollback journal segment(s) of ${displaySafe(child)}`);
43356
+ refs = await stateBackend.listStacks();
43313
43357
  } catch (error) {
43314
- warnUncleared(logger, child, error);
43358
+ logger.debug(`orphan adoption: could not list sibling stacks — ${displayAwsMessage(describeAwsFailure(error).detail)}`);
43359
+ return claimed;
43315
43360
  }
43316
- }
43317
- }
43318
- async function withChildLock(lockManager, child, region, logger, fn) {
43319
- await lockManager.acquireLockWithRetry(child, region, void 0, "rollback");
43320
- try {
43321
- return await fn();
43322
- } finally {
43323
- await lockManager.releaseLock(child, region).catch((error) => {
43324
- logger.warn(safeMsg`Failed to release the lock of nested stack ${displayIdent(child)}: ${errorText(error)}`);
43325
- });
43326
- }
43327
- }
43328
- function depthExceeded(depth, parentStackName, logger) {
43329
- if (depth < MAX_NESTED_WALK_DEPTH) return false;
43330
- logger.warn(safeMsg`Stopped clearing nested rollback journals below ${displayIdent(parentStackName)}: ` + safeMsg`the nesting is deeper than ${MAX_NESTED_WALK_DEPTH} levels.`);
43331
- return true;
43332
- }
43333
- function warnUncleared(logger, child, error) {
43334
- logger.warn(safeMsg`Could not clear the rollback journal of nested stack ${displayIdent(child)}: ${errorText(error)}. ` + "It is inert to every parent revert (they select segments by run) and the next successful deploy of the top-level stack removes it.");
43335
- }
43336
- async function revertNestedChildFromJournal(args) {
43337
- const { ctx, logicalId, childStackName, region, run, logger } = args;
43338
- const runId = run.runId;
43339
- const shownChild = displayIdent(childStackName);
43340
- const refuse = (detail) => {
43341
- throw markNonRetryable(/* @__PURE__ */ new Error(`Cannot revert nested stack ${shownChild} (row ${displayIdent(logicalId)}): ${detail} The child was NOT (fully) reverted and may still hold the failed deploy's configuration. Inspect it with 'cdkd state show'; re-run the rollback once the cause is fixed (its journal is kept), or re-deploy the parent to converge.`));
43342
- };
43343
- if (runId === void 0) refuse("the rollback carries no deploy run id to select its journal segments by.");
43344
- await ctx.lockManager.acquireLockWithRetry(childStackName, region, void 0, "rollback");
43345
- try {
43346
- const stateData = await ctx.stateBackend.getState(childStackName, region);
43347
- if (!stateData) refuse("its state.json is missing.");
43348
- if (stateData.divergentBodyRegion !== void 0) refuse("its state record's region field disagrees with the key it is stored under.");
43349
- const base = stateData.state;
43350
- const refusalRecovery = {
43351
- profile: ctx.destroyOptions?.profile,
43352
- stateBucket: ctx.stateBucket,
43353
- statePrefix: ctx.destroyOptions?.statePrefix
43354
- };
43355
- refuseMalformedState(base, childStackName, region, refusalRecovery);
43356
- refuseMalformedOrphans(base, childStackName, region, refusalRecovery);
43357
- refuseMalformedOrphanRecords(base, childStackName, region, refusalRecovery);
43358
- const childNamingScope = nameScopeOf(childStackName, stackInstanceIdOf(base, displayStackName(childStackName)), base);
43359
- const segments = ((await ctx.stateBackend.loadRollbackJournal(childStackName, region))?.segments ?? []).filter((segment) => segment.runId === runId);
43360
- if (segments.length === 0) refuse("its rollback journal holds no segment for this deploy run, so there is no record of what it held before.");
43361
- const stateResources = { ...base.resources };
43362
- const mintedOrphans = [];
43363
- const rolledBackCreates = [];
43364
- const supersededHost = {};
43365
- const restoredOutputs = segments.find((s) => s.previousOutputs)?.previousOutputs;
43366
- const restoredReads = segments.find((s) => s.previousCrossStackReads)?.previousCrossStackReads;
43367
- let currentEtag = stateData.etag;
43368
- let persisted = false;
43369
- let restoring = false;
43370
- const { skippedOutputs: _dropped, ...carried } = base;
43371
- const next = () => ({
43372
- ...carried,
43373
- ...stackInstanceIdCarriedFrom(base),
43374
- ...supersededAfterRollback(base, supersededHost),
43375
- version: 15,
43376
- region,
43377
- resources: { ...stateResources },
43378
- ...orphansAfterRollback(base, mintedOrphans),
43379
- ...retiredAfterRollback(base, mintedOrphans, rolledBackCreates),
43380
- ...restoring && restoredOutputs && { outputs: { ...restoredOutputs.outputs } },
43381
- ...restoring && restoredReads && {
43382
- ...restoredReads.imports && { imports: [...restoredReads.imports] },
43383
- ...restoredReads.outputReads && { outputReads: [...restoredReads.outputReads] }
43384
- },
43385
- ...restoring && restoredOutputs?.exportNames && { exportNames: [...restoredOutputs.exportNames] },
43386
- lastModified: Date.now()
43387
- });
43388
- const nextState = () => {
43389
- const state = next();
43390
- if (!restoring) return state;
43391
- if (restoredOutputs && !restoredOutputs.exportNames) delete state.exportNames;
43392
- if (restoredOutputs) delete state.outputReferenceProvenance;
43393
- if (restoredReads && !restoredReads.imports) delete state.imports;
43394
- if (restoredReads && !restoredReads.outputReads) delete state.outputReads;
43395
- return state;
43396
- };
43397
- const save = async () => {
43398
- persisted = false;
43361
+ for (const ref of refs) {
43362
+ if (ref.stackName === selfStackName && ref.region === selfRegion) continue;
43363
+ if (ref.region === void 0) continue;
43399
43364
  try {
43400
- currentEtag = await ctx.stateBackend.saveState(childStackName, region, nextState(), { ...currentEtag !== void 0 && { expectedEtag: currentEtag } });
43401
- persisted = true;
43402
- } catch {
43403
- try {
43404
- const fresh = await ctx.stateBackend.getState(childStackName, region);
43405
- currentEtag = await ctx.stateBackend.saveState(childStackName, region, nextState(), { ...fresh?.etag !== void 0 && { expectedEtag: fresh.etag } });
43406
- persisted = true;
43407
- } catch (retryError) {
43408
- logger.warn(safeMsg`Failed to persist the state of nested stack ${shownChild} after reverting it: ` + safeMsg`${errorText(retryError)}. The resources were reverted in AWS.`);
43365
+ const sibling = await stateBackend.getState(ref.stackName, ref.region);
43366
+ if (!sibling) continue;
43367
+ const bag = sibling.state.resources;
43368
+ if (typeof bag !== "object" || bag === null) {
43369
+ logger.debug(safeMsg`orphan adoption: skipping ${displayStackName(ref.stackName)} — its state record ` + `has no readable 'resources' map, so nothing it claims can be read`);
43370
+ continue;
43371
+ }
43372
+ const unreadable = [];
43373
+ for (const [logicalId, record] of Object.entries(bag)) {
43374
+ const physicalId = isReadableBag(record) ? record.physicalId : void 0;
43375
+ if (typeof physicalId === "string" && physicalId !== "") claimed.add(physicalId);
43376
+ else unreadable.push(logicalId);
43377
+ }
43378
+ if (unreadable.length > 0) {
43379
+ const named = unreadable.slice(0, NAMED_UNREADABLE_SIBLING_ROWS).map((id) => displayIdent(id)).join(", ");
43380
+ const rest = unreadable.length - NAMED_UNREADABLE_SIBLING_ROWS;
43381
+ logger.debug(safeMsg`orphan adoption: ${displayStackName(ref.stackName)} holds ${unreadable.length} ` + safeMsg`resource record(s) with no readable physical id — ${named}` + safeMsg`${rest > 0 ? ` and ${rest} more` : ""} — skipped; the claim set is a lower ` + `bound without them`);
43409
43382
  }
43383
+ } catch (error) {
43384
+ logger.debug(`orphan adoption: skipping unreadable state for ${displayStackName(ref.stackName)} — ${displayAwsMessage(describeAwsFailure(error).detail)}`);
43410
43385
  }
43411
- };
43412
- const producerRegions = inheritProducerRegions(producerRegionsFromState({
43413
- imports: [...base.imports ?? [], ...restoredReads?.imports ?? []],
43414
- outputReads: [...base.outputReads ?? [], ...restoredReads?.outputReads ?? []]
43415
- }), args.inheritedProducerRegions);
43416
- const execCtx = {
43417
- providerRegistry: ctx.providerRegistry,
43418
- region,
43419
- logger,
43420
- ...ctx.options?.eventRecorder && { recordEvent: (event) => ctx.options.eventRecorder.record(maskEventTextWithBoundBags(event)) },
43421
- finalSnapshotClients: ctx.options?.finalSnapshotClients,
43422
- skipFinalSnapshot: ctx.options?.skipFinalSnapshot === true || ctx.destroyOptions?.skipFinalSnapshot === true,
43423
- ...ctx.destroyOptions?.removeProtection === true && {
43424
- removeProtection: true,
43425
- foreignHolder: makeForeignHolderScan(ctx.stateBackend)({
43426
- stackName: childStackName,
43427
- region
43428
- })
43429
- },
43430
- importedProducerRegions: producerRegions.regions,
43431
- producerRegionsIncomplete: !producerRegions.complete,
43432
- nestedChildRevert: true
43433
- };
43434
- const childCtx = {
43435
- ...ctx,
43436
- parentStackName: childStackName,
43437
- parentRegion: region,
43438
- nestedTemplates: void 0
43439
- };
43440
- let failures = 0;
43441
- let warnings = 0;
43442
- const inlinePolicyWriters = new RollbackInlinePolicyWriters();
43443
- const settledBelow = /* @__PURE__ */ new Map();
43444
- for (let s = segments.length - 1; s >= 0; s--) {
43445
- const segment = segments[s];
43446
- const skipPrefix = segment.skipPrefix ?? getCurrentSkipPrefix();
43447
- const split = splitImportedOps(segment.operations, segment);
43448
- const result = await withNestedStackContext(childCtx, () => withSkipPrefix(skipPrefix, () => withStackScope(childNamingScope, () => withCreateTokenLedger(ledgerForStack(ctx.stateBackend, childStackName, region), () => withNestedRevertRun(runId, async (inner) => {
43449
- const replayed = await withPrintingSecrets(journaledOrphanPrintingBag(completedReplayEntries(split.replay), stateResources), () => replayRollback(split.replay, stateResources, childStackName, execCtx, {
43450
- afterOp: save,
43451
- onOrphan: (record) => mintedOrphans.push(record),
43452
- onRolledBackCreate: (create) => rolledBackCreates.push(create),
43453
- inlinePolicyWriters,
43454
- failedOperations: segment.failedOperations,
43455
- onSuperseded: (entry) => addSuperseded(supersededHost, entry),
43456
- onSupersededSettled: (entry) => removeSuperseded(supersededHost, entry)
43457
- }));
43458
- for (const [id, below] of inner.settled) settledBelow.set(id, below);
43459
- return {
43460
- ...replayed,
43461
- warnings: replayed.warnings + inner.warnings
43462
- };
43463
- })))));
43464
- failures += result.failures;
43465
- warnings += result.warnings + split.displaced.length;
43466
- recordDisplacedSkips(execCtx.recordEvent, childStackName, split.displaced);
43467
- for (const op of split.displaced) logger.warn(safeMsg`Nested stack ${childStackName}: ${op.logicalId} ` + safeMsg`${displacedOpClause(op, segment.importedResources ?? [], logger)}; ` + "not reverted, check that resource by hand");
43468
43386
  }
43469
- restoring = failures === 0;
43470
- await save();
43471
- if (restoring && persisted && restoredOutputs && ctx.exportIndexStore) await ctx.exportIndexStore.updateForStack(childStackName, region, importableOutputs(nextState()));
43472
- if (warnings > 0) logger.warn(safeMsg`Nested stack ${shownChild}: ${warnings} operation(s) were skipped with a warning during ` + `its revert (see above); they may need attention by hand.`);
43473
- if (failures > 0) refuse(`${failures} of its operation(s) failed to revert (see the warnings above).`);
43474
- if (warnings > 0) run.warnings += warnings;
43475
- else run.settled.set(logicalId, settledBelow);
43476
- return { warnings };
43477
- } finally {
43478
- await ctx.lockManager.releaseLock(childStackName, region).catch((error) => {
43479
- logger.warn(safeMsg`Failed to release the lock of nested stack ${shownChild}: ${errorText(error)}`);
43480
- });
43387
+ return claimed;
43388
+ };
43389
+ }
43390
+
43391
+ // src/deployment/deploy-engine/rollback/adopt-orphans.ts
43392
+ function redactOperationsForJournal(deps, operations) {
43393
+ return operations.map((op) => {
43394
+ const secrets = deps.secretsRun().perResourceSecrets.get(op.logicalId);
43395
+ const templateProps = deps.secretsRun().perResourceTemplateProps.get(op.logicalId);
43396
+ const sources = templateProps === void 0 ? void 0 : noEchoPositionSources(deps.noEchoRun());
43397
+ const byPosition = (bag) => sources === void 0 || templateProps === void 0 ? bag : maskAtCoordinates(bag, noEchoCoordinatesOf(templateProps, bag, sources));
43398
+ if ((!secrets || secrets.size === 0) && !op.previousState && sources === void 0) return op;
43399
+ const ownSecrets = secrets ?? /* @__PURE__ */ new Map();
43400
+ const next = { ...op };
43401
+ if (next.properties) {
43402
+ const properties = next.properties;
43403
+ next.properties = byPosition(templateProps === void 0 ? redactForState(properties, {
43404
+ provenance: "value-scan",
43405
+ secrets: ownSecrets
43406
+ }) : redactForState(properties, {
43407
+ provenance: "template-derived",
43408
+ secrets: ownSecrets,
43409
+ source: templateProps,
43410
+ generation: redactionClaimOf(properties)
43411
+ }));
43412
+ }
43413
+ if (next.attemptedProperties) {
43414
+ const attempted = next.attemptedProperties;
43415
+ next.attemptedProperties = byPosition(templateProps === void 0 ? redactForState(attempted, {
43416
+ provenance: "value-scan",
43417
+ secrets: ownSecrets
43418
+ }) : redactForState(attempted, {
43419
+ provenance: "template-derived",
43420
+ secrets: ownSecrets,
43421
+ source: templateProps,
43422
+ generation: "same-generation"
43423
+ }));
43424
+ }
43425
+ if (next.previousState) {
43426
+ const previous = next.previousState;
43427
+ const adopted = adoptedOrphanRecords.get(deps.owner);
43428
+ const loaded = adopted?.has(op.logicalId) ? adopted.get(op.logicalId) : previous;
43429
+ next.previousState = applyNoEchoPersist(deps.noEchoRun(), deps.noEchoDeps(), op.logicalId, previous, keepPersistedPlainRecordLeaves(scrubResourceRecord(previous, ownSecrets, void 0, "state-readback", { observed: isSameGenerationBag(previous.observedProperties) ? "same-generation" : "unproven" }), previous, loaded ?? {}), void 0, {}, void 0, true);
43430
+ }
43431
+ return next;
43432
+ });
43433
+ }
43434
+ const adoptedOrphanRecords = /* @__PURE__ */ new WeakMap();
43435
+ async function adoptRollbackOrphans(deps, currentState, effectiveTemplate) {
43436
+ const records = currentState.orphans ?? [];
43437
+ const named = orphanRecordsPrintingBag(records);
43438
+ const plan = await withPrintingSecrets(named, () => planOrphanAdoption({
43439
+ records,
43440
+ managedLogicalIds: new Set(Object.keys(currentState.resources)),
43441
+ template: effectiveTemplate,
43442
+ stackName: currentState.stackName,
43443
+ region: deps.stackRegion,
43444
+ getProvider: (type, provisionedBy) => deps.providerRegistry.getProviderFor({
43445
+ resourceType: type,
43446
+ ...provisionedBy !== void 0 && { provisionedBy }
43447
+ }).provider,
43448
+ nameProperties: (type) => {
43449
+ const property = explicitNamePropertyFor(type);
43450
+ return property === void 0 ? [] : [property];
43451
+ },
43452
+ readSiblingClaims: makeSiblingClaimReader({
43453
+ stateBackend: deps.stateBackend,
43454
+ selfStackName: currentState.stackName,
43455
+ selfRegion: deps.stackRegion,
43456
+ logger: deps.logger
43457
+ }),
43458
+ logger: { debug: (m) => deps.logger.debug(m) },
43459
+ newScheme: currentState.stackInstanceId !== void 0
43460
+ }));
43461
+ for (const notice of plan.notices) deps.logger.info(maskSecretsInText(notice, named));
43462
+ for (const warning of plan.warnings) deps.logger.warn(maskSecretsInText(warning, named));
43463
+ const adoptedFrom = /* @__PURE__ */ new Map();
43464
+ adoptedOrphanRecords.set(deps.owner, adoptedFrom);
43465
+ if (plan.refusals.length > 0) throw new Error(safeMsg`Deploy refused — cdkd left ${plan.refusals.length} resource(s) in AWS that it cannot ` + "safely re-adopt:" + plan.refusals.map((r) => safeMsg`\n ${maskSecretsInText(r, named)}`).join(""));
43466
+ for (const [logicalId, record] of Object.entries(plan.adopted)) {
43467
+ adoptedFrom.set(logicalId, records.findLast((r) => r.logicalId === logicalId)?.state);
43468
+ currentState.resources[logicalId] = record;
43469
+ deps.logger.info(safeMsg`Adopting ${displayIdent(logicalId)} (${displayIdent(record.resourceType)}) left in AWS ` + safeMsg`by an earlier rollback as ${displaySafe(maskSecretsInText(record.physicalId, named))}`);
43481
43470
  }
43471
+ if (records.length > 0) currentState.orphans = plan.remaining;
43472
+ return plan;
43482
43473
  }
43483
43474
 
43484
43475
  // src/deployment/rollback-executor/journaled-orphans/success-rule.ts
@@ -43935,400 +43926,352 @@ function sameJournaledOrphans(a, b) {
43935
43926
  return ka.length === kb.length && ka.every((k, i) => k === kb[i]);
43936
43927
  }
43937
43928
 
43938
- // src/deployment/cc-pending-requests.ts
43939
- function hasPendingCloudControlRequest(op) {
43940
- return op.pendingCloudControlRequest !== void 0;
43929
+ // src/provisioning/nested-stack-context.ts
43930
+ const storage = new AsyncLocalStorage();
43931
+ function withNestedStackContext(ctx, fn) {
43932
+ return storage.run(ctx, fn);
43941
43933
  }
43942
- function pendingRequestCount(journal) {
43943
- return pendingRequests(journal ?? null).size;
43934
+ function getCurrentNestedStackContext() {
43935
+ return storage.getStore();
43944
43936
  }
43945
- async function resolvePendingCloudControlRequests(params) {
43946
- const { journal, stackName, region } = params;
43947
- if (pendingRequests(params.loaded).size === 0) return false;
43948
- const settle = async () => {
43949
- await params.beforeSettle?.();
43950
- let current = params.loaded;
43951
- if (params.underLock) try {
43952
- current = await journal.loadRollbackJournal(stackName, region);
43953
- } catch (error) {
43954
- throw new CdkdError(safeMsg`cdkd ${params.command} of ${displayStackName(stackName)} refused: its rollback ` + "journal recorded an unsettled Cloud Control CREATE when this run started and cannot " + safeMsg`be read now (${displaySafe(describeAwsFailure(error).summary)}). Nothing was ` + "changed; re-run once it can be read.", "CC_PENDING_REQUEST_UNREADABLE");
43955
- }
43956
- const pending = pendingRequests(current);
43957
- if (pending.size > 0) await settlePending(params, pending);
43958
- return params.underLock !== void 0 || pending.size > 0;
43937
+ async function collectNestedChildUnaddressed(fn) {
43938
+ const ctx = storage.getStore();
43939
+ if (!ctx) return {
43940
+ value: await fn(),
43941
+ unaddressed: void 0
43942
+ };
43943
+ const slot = {};
43944
+ return {
43945
+ value: await storage.run({
43946
+ ...ctx,
43947
+ childUnaddressed: slot
43948
+ }, fn),
43949
+ unaddressed: slot.last
43959
43950
  };
43960
- return params.underLock ? params.underLock(settle) : settle();
43961
43951
  }
43962
- function pendingRequests(loaded) {
43963
- const pending = /* @__PURE__ */ new Map();
43964
- for (const segment of loaded?.segments ?? []) for (const op of segment.failedOperations ?? []) if (hasPendingCloudControlRequest(op)) pending.set(op.pendingCloudControlRequest.requestToken, op);
43965
- return pending;
43952
+
43953
+ // src/deployment/nested-child-journal.ts
43954
+ const NESTED_PENDING_PARENT_REASON = "nested-pending-parent";
43955
+ const NESTED_STACK_TYPE$2 = "AWS::CloudFormation::Stack";
43956
+ const MAX_NESTED_WALK_DEPTH = 32;
43957
+ function nestedChildStackName(parentStackName, logicalId) {
43958
+ return `${parentStackName}~${logicalId}`;
43966
43959
  }
43967
- async function settlePending(params, pending) {
43968
- const { journal, stackName, region, command, logger } = params;
43969
- const reader = params.reader();
43970
- const isUnique = params.identifierUnique ?? ccIdentifierIsUnique;
43971
- const stackShown = displayStackName(stackName);
43972
- const source = params.stackInstanceId;
43973
- let resolvedId;
43974
- const stackInstanceId = () => resolvedId ??= typeof source === "function" ? source() : Promise.resolve(source);
43975
- const settlements = /* @__PURE__ */ new Map();
43976
- const unresolved = [];
43977
- for (const [token, op] of pending) {
43978
- const named = `${logicalIdShown(op.logicalId)} (${resourceTypeShown(op.resourceType)})`;
43979
- logger.info(safeMsg`A previous run of ${stackShown} stopped waiting for the Cloud Control CREATE of ${named}; ` + "checking how it ended...");
43980
- const outcome = await reader.resumeAbandonedRequest(token, op.logicalId, op.resourceType);
43981
- switch (outcome.status) {
43982
- case "succeeded":
43983
- case "failed":
43984
- case "cancelled": {
43985
- const made = outcome.status === "succeeded" ? outcome.identifier : outcome.remnant;
43986
- if (made === void 0) {
43987
- logger.info(safeMsg`The CREATE of ${named} ${outcome.status === "cancelled" ? "was cancelled" : "failed"} ` + "in AWS and made nothing.");
43988
- settlements.set(token, { kind: "drop" });
43989
- break;
43990
- }
43991
- const madeShown = displacedPhysicalIdShown({
43992
- ...op,
43993
- physicalId: made
43994
- }, logger, made) ?? "a resource";
43995
- const held = params.stateResources?.[op.logicalId];
43996
- if (held !== void 0 && held.physicalId === made) {
43997
- logger.info(safeMsg`The CREATE of ${named} made ${madeShown}, which state already records.`);
43998
- settlements.set(token, { kind: "drop" });
43999
- break;
44000
- }
44001
- const unique = await isUnique({
44002
- resourceType: op.resourceType,
44003
- identifier: made,
44004
- attemptedProperties: op.attemptedProperties,
44005
- logicalId: op.logicalId,
44006
- stackName,
44007
- stackInstanceId: await stackInstanceId(),
44008
- nameGenerationsThrough: generationsThrough(op, held)
44009
- });
44010
- const ended = outcome.status === "succeeded" ? "completed" : outcome.status === "cancelled" ? "was cancelled" : "failed";
44011
- if (outcome.status === "succeeded" && unique && held === void 0 && params.resume?.(op, made)) {
44012
- logger.info(safeMsg`The CREATE of ${named} completed in AWS after cdkd stopped waiting, and made ` + safeMsg`${madeShown}; this deploy's CREATE of it takes that resource over when it sends ` + "the same properties.");
44013
- settlements.set(token, { kind: "resume" });
44014
- break;
44015
- }
44016
- if (params.resume !== void 0 && !unique) logger.warn(safeMsg`The CREATE of ${named} ${ended} in AWS after cdkd stopped waiting, and made ` + safeMsg`${madeShown}. cdkd cannot prove its id is unique (it may be a name, which can ` + safeMsg`since belong to another resource), so this deploy does not take it over, and creating ${logicalIdShown(op.logicalId)} ` + "again will ask for the name it holds. Adopt it with cdkd import (--resource " + safeMsg`${logicalIdShown(op.logicalId)}=<its id>), or delete it, then re-run. It is kept in the ` + "rollback journal as a resource the failed deploy created.");
44017
- else logger.warn(safeMsg`The CREATE of ${named} ${ended} in AWS after cdkd stopped waiting, and made ` + safeMsg`${madeShown}. It is now recorded in the rollback journal as a resource the failed ` + "deploy created: cdkd destroy, cdkd rollback --revert-failed and the next successful deploy delete it as its DeletionPolicy directs when cdkd can prove it is still the resource that create made, and otherwise name it in a warning for you to delete by hand.");
44018
- settlements.set(token, {
44019
- kind: "orphan",
44020
- physicalId: made,
44021
- unique
44022
- });
44023
- break;
44024
- }
44025
- case "not-found":
44026
- logger.warn(safeMsg`Cloud Control no longer has the CREATE request of ${named}: requests expire after ` + "seven days, and a request is not visible from another account or region. cdkd cannot tell whether it created the resource and stops tracking the request. If it exists, adopt it with cdkd import or delete it by hand.");
44027
- settlements.set(token, { kind: "drop" });
44028
- break;
44029
- case "unresolved": {
44030
- settlements.set(token, { kind: "keep" });
44031
- const reason = holdsSecretReference(op.attemptedProperties) ? "details withheld: its properties carry a secret" : displaySafe(describeAwsFailure(outcome.error).summary);
44032
- unresolved.push(safeMsg` - ${named}${reason === "" ? "" : ` (${reason})`}\n` + ` Check it with: ${await reader.buildResumeCommand(token)}`);
44033
- break;
44034
- }
43960
+ function nestedPendingSnapshot(state, refusesExportName) {
43961
+ const outputs = { ...isPlainRecord(state.outputs) ? state.outputs : {} };
43962
+ let exportNames = Array.isArray(state.exportNames) ? [...state.exportNames] : void 0;
43963
+ const refused = new Set(importableOutputKeys(state).filter((name) => refusesExportName(name)));
43964
+ if (refused.size > 0) {
43965
+ for (const name of refused) Reflect.deleteProperty(outputs, name);
43966
+ if (exportNames !== void 0) exportNames = exportNames.filter((name) => !refused.has(name));
43967
+ }
43968
+ return {
43969
+ previousOutputs: {
43970
+ outputs,
43971
+ ...exportNames !== void 0 && { exportNames }
43972
+ },
43973
+ previousCrossStackReads: {
43974
+ ...Array.isArray(state.imports) && { imports: [...state.imports] },
43975
+ ...Array.isArray(state.outputReads) && { outputReads: [...state.outputReads] }
44035
43976
  }
43977
+ };
43978
+ }
43979
+ function displacedPhysicalIdShown(op, logger, physicalId = journalOpPhysicalId(op)) {
43980
+ if (physicalId === void 0) return void 0;
43981
+ const masker = createOpMasker(logger, /* @__PURE__ */ new Map());
43982
+ for (const properties of [
43983
+ op.properties,
43984
+ op.attemptedProperties,
43985
+ op.previousState?.properties
43986
+ ]) {
43987
+ if (properties === void 0) continue;
43988
+ masker.addNamed({
43989
+ resourceType: op.resourceType,
43990
+ properties,
43991
+ logicalId: op.logicalId,
43992
+ physicalIds: [physicalId]
43993
+ });
44036
43994
  }
44037
- if ([...settlements.values()].some((s) => s.kind === "orphan" || s.kind === "drop")) await journal.rewriteRollbackJournalFailedOperations(stackName, region, (op) => {
44038
- if (!hasPendingCloudControlRequest(op)) return op;
44039
- const settlement = settlements.get(op.pendingCloudControlRequest.requestToken);
44040
- if (settlement?.kind === "drop") return withoutPendingRequest(op);
44041
- if (settlement?.kind !== "orphan") return op;
44042
- return {
44043
- ...withoutPendingRequest(op),
44044
- provisionedBy: "cc-api",
44045
- physicalId: settlement.physicalId,
44046
- physicalIdRecoveredFromError: true,
44047
- ...settlement.unique && { createdIdentifierUnique: true }
44048
- };
44049
- });
44050
- if (unresolved.length > 0) {
44051
- const kept = [...pending.values()].filter((op) => settlements.get(op.pendingCloudControlRequest.requestToken)?.kind === "keep");
44052
- const drop = dropFailedCommands(stackName, region, kept.map((op) => op.logicalId));
44053
- const withheld = drop?.commands.some((c) => c.includes("<")) === true;
44054
- throw new CdkdError(safeMsg`cdkd ${command} of ${stackShown} refused: a previous run stopped waiting for a Cloud ` + `Control CREATE, and cdkd still cannot tell whether it made its resource. Proceeding could leave that resource untracked. Nothing was changed.
44055
- ${unresolved.join("\n")}\nRe-run once the request has finished and can be read. If you have reconciled it by hand (cdkd import, or deleted the resource), drop its journal entry with:` + (drop === void 0 ? "" : drop.commands.map((c) => `\n ${c}`).join("")) + (withheld ? "\nA value that is not a plain identifier is shown as a <hole>; read it from the stack's state record and rollback-journal.json." : ""), "CC_PENDING_REQUEST_UNRESOLVED");
43995
+ return displaySafe(String(masker.mask(physicalId)));
43996
+ }
43997
+ function displacedOpClause(op, marks, logger) {
43998
+ const retainedOld = retainedOldPhysicalId(op);
43999
+ if (retainedOld !== void 0 && marks.some((m) => isMarkFor(m, op))) {
44000
+ const shownOld = displacedPhysicalIdShown(op, logger, retainedOld);
44001
+ return `replaced ${shownOld} ${op.oldResourceRetained === true ? "but kept it (UpdateReplacePolicy: Retain)" : op.oldResourceMaySurvive !== void 0 ? "and may have kept it (its delete was not confirmed)" : "and may have kept it (the journal records no verdict)"}; cdkd import adopted the replacement, so ${shownOld} is left untracked`;
44056
44002
  }
44003
+ const shownId = displacedPhysicalIdShown(op, logger);
44004
+ return shownId !== void 0 ? `recorded ${shownId}, which cdkd import has since replaced under this id` : "recorded no physical id, and cdkd import has since put another resource under this id";
44057
44005
  }
44058
- function holdsSecretReference(properties) {
44059
- if (properties === void 0) return false;
44060
- return carriesSecretMask(properties) || JSON.stringify(properties).includes("{{resolve:");
44006
+ function recordDisplacedSkips(recordEvent, stackName, ops) {
44007
+ for (const op of ops) recordEvent?.({
44008
+ eventType: "ROLLBACK_RESOURCE_SKIPPED",
44009
+ stackName,
44010
+ operation: op.changeType,
44011
+ logicalId: op.logicalId,
44012
+ resourceType: op.resourceType,
44013
+ ...op.provisionedBy && { provisionedBy: op.provisionedBy },
44014
+ reason: "cdkd import has since put another resource under this logical id, so the op was not reverted; check the resource it recorded by hand"
44015
+ });
44061
44016
  }
44062
- const ccIdentifierIsUnique = async ({ resourceType, identifier, attemptedProperties, logicalId, stackName, stackInstanceId, nameGenerationsThrough }) => {
44063
- if (attemptedProperties === void 0 || holdsSecretReference(attemptedProperties)) return false;
44064
- const [fields, readOnly] = await Promise.all([getPrimaryIdentifierFields(resourceType), getTopLevelReadOnlyProperties(resourceType)]);
44065
- if (fields === void 0 || readOnly === void 0) return false;
44066
- const parts = identifier.split("|");
44067
- if (parts.length !== fields.length) return false;
44068
- const sent = /* @__PURE__ */ new Set();
44069
- const collect = (value) => {
44070
- if (typeof value === "string" || typeof value === "number") for (const piece of nameSegments(String(value))) sent.add(piece);
44071
- else if (Array.isArray(value)) value.forEach(collect);
44072
- else if (value !== null && typeof value === "object") Object.values(value).forEach(collect);
44017
+ function revertedNestedRowIds(ops) {
44018
+ return ops.filter((op) => op.resourceType === NESTED_STACK_TYPE$2 && op.changeType === "UPDATE").map((op) => op.logicalId);
44019
+ }
44020
+ const revertRunStorage = new AsyncLocalStorage();
44021
+ function withNestedRevertRun(runId, fn) {
44022
+ const run = {
44023
+ runId,
44024
+ settled: /* @__PURE__ */ new Map(),
44025
+ warnings: 0
44073
44026
  };
44074
- collect(attemptedProperties);
44075
- return parts.some((part, i) => {
44076
- if (part === "" || !readOnly.has(fields[i])) return false;
44077
- return !nameSegments(part).some((segment) => sent.has(segment) || looksLikeCdkdGeneratedName(segment, logicalId, stackName, stackInstanceId, nameGenerationsThrough === void 0 ? void 0 : { through: nameGenerationsThrough }));
44078
- });
44079
- };
44080
- function generationsThrough(op, held) {
44081
- const own = isNameGeneration(op.nameGeneration) ? op.nameGeneration : 0;
44082
- let recorded = 0;
44083
- for (const value of [held?.nameGeneration, held?.nameGenerationHigh]) if (isNameGeneration(value)) recorded = Math.max(recorded, value);
44084
- return Math.max(own, recorded) + 1;
44027
+ return revertRunStorage.run(run, () => fn(run));
44085
44028
  }
44086
- function nameSegments(value) {
44087
- const text = value.toLowerCase();
44088
- const arn = /^arn:[^:]*:[^:]*:[^:]*:[^:]*:(.*)$/.exec(text);
44089
- const body = arn ? arn[1] : text;
44090
- return [
44091
- text,
44092
- body,
44093
- ...body.split(/[:/]/)
44094
- ].filter((piece) => piece !== "");
44029
+ function getNestedRevertRun() {
44030
+ return revertRunStorage.getStore();
44095
44031
  }
44096
- function withoutPendingRequest(op) {
44097
- const { pendingCloudControlRequest: _settled, ...rest } = op;
44098
- return rest;
44032
+ function errorText(error) {
44033
+ return displaySafe(describeAwsFailure(error).detail);
44099
44034
  }
44100
-
44101
- // src/deployment/orphan-adoption.ts
44102
- function templateStillDeclares(template, record, nameProperties) {
44103
- const declared = template.Resources?.[record.logicalId];
44104
- if (!declared) return false;
44105
- if (declared.Type !== record.state.resourceType) return false;
44106
- const properties = declared.Properties ?? {};
44107
- return ![...nameProperties, ...alternateNamePropertiesFor(declared.Type)].some((p) => properties[p] !== void 0 && properties[p] !== null);
44035
+ function isPlainRecord(value) {
44036
+ return typeof value === "object" && value !== null && !Array.isArray(value);
44108
44037
  }
44109
- const ADOPTION_REFUSED_TYPES = /* @__PURE__ */ new Set(["AWS::Lambda::LayerVersion", "AWS::ECS::TaskDefinition"]);
44110
- async function planOrphanAdoption(params) {
44111
- const outcome = {
44112
- adopted: {},
44113
- remaining: [],
44114
- refusals: [],
44115
- notices: [],
44116
- warnings: []
44117
- };
44118
- if (params.records.length === 0) return outcome;
44119
- if (params.newScheme === true) {
44120
- for (const record of params.records) {
44121
- if (params.managedLogicalIds.has(record.logicalId)) continue;
44122
- outcome.remaining.push(record);
44123
- if ((params.template.Resources?.[record.logicalId])?.Type !== record.state.resourceType) continue;
44124
- outcome.warnings.push(`${displayIdent(record.logicalId)} (${displayIdent(record.state.resourceType)}) was left in AWS by an earlier rollback as ${displaySafe(record.state.physicalId)} (DeletionPolicy: Retain). This deploy does not take it back: it creates a new resource under a new name, as CloudFormation does. To manage the kept resource again, adopt it with 'cdkd import'.`);
44125
- }
44126
- return outcome;
44127
- }
44128
- let siblingClaims;
44129
- const claims = async () => siblingClaims ??= await params.readSiblingClaims();
44130
- for (const record of params.records) {
44131
- const { logicalId, state } = record;
44132
- const shownId = displayIdent(logicalId);
44133
- const shownType = displayIdent(state.resourceType);
44134
- const shownPhysicalId = displaySafe(state.physicalId);
44135
- if (params.managedLogicalIds.has(logicalId)) {
44136
- params.logger.debug(`orphan ${shownId}: already present in state.resources — dropping the stale record`);
44137
- continue;
44138
- }
44139
- let provider;
44038
+ async function dropNestedChildJournals(args) {
44039
+ const { stateBackend, parentStackName, region, resources, logger } = args;
44040
+ const depth = args.depth ?? 0;
44041
+ if (!isPlainRecord(resources)) return;
44042
+ if (depthExceeded(depth, parentStackName, logger)) return;
44043
+ for (const [logicalId, record] of Object.entries(resources)) {
44044
+ if (!isPlainRecord(record) || record["resourceType"] !== NESTED_STACK_TYPE$2) continue;
44045
+ const child = nestedChildStackName(parentStackName, logicalId);
44140
44046
  try {
44141
- provider = params.getProvider(state.resourceType, state.provisionedBy);
44047
+ const data = await stateBackend.getState(child, region);
44048
+ if (data && isPlainRecord(data.state) && isPlainRecord(data.state.resources) && (data.state.stackName === void 0 || data.state.stackName === child)) await dropNestedChildJournals({
44049
+ ...args,
44050
+ parentStackName: child,
44051
+ resources: data.state.resources,
44052
+ depth: depth + 1
44053
+ });
44142
44054
  } catch (error) {
44143
- outcome.remaining.push(record);
44144
- outcome.notices.push(`${shownId} (${shownType}) is still in AWS as ${shownPhysicalId} from an earlier rollback, but this build cannot route that type (${displayAwsMessage(describeAwsFailure(error).detail)}) — cdkd is not adopting it.`);
44145
- continue;
44146
- }
44147
- if (!provider.import) {
44148
- outcome.remaining.push(record);
44149
- outcome.notices.push(`${shownId} (${shownType}) was left in AWS by an earlier rollback as ${shownPhysicalId}, but its provider cannot verify it — cdkd is not adopting it.`);
44150
- continue;
44055
+ warnUncleared(logger, child, error);
44151
44056
  }
44152
- let found;
44153
44057
  try {
44154
- found = await provider.import({
44155
- logicalId,
44156
- resourceType: state.resourceType,
44157
- stackName: params.stackName,
44158
- region: params.region,
44159
- properties: state.properties,
44160
- knownPhysicalId: state.physicalId
44161
- });
44058
+ if (await withChildLock(args.lockManager, child, region, logger, async () => {
44059
+ if (args.beforeDelete) {
44060
+ if (!await args.beforeDelete(child, await readOwnRecord(stateBackend, child, region))) return false;
44061
+ }
44062
+ let gone;
44063
+ try {
44064
+ gone = await stateBackend.deleteRollbackJournal(child, region);
44065
+ } catch (error) {
44066
+ await args.onDeleteFailed?.(child);
44067
+ throw error;
44068
+ }
44069
+ if (gone === false) {
44070
+ await args.onDeleteFailed?.(child);
44071
+ return false;
44072
+ }
44073
+ return true;
44074
+ })) logger.debug(safeMsg`Deleted the rollback journal of nested stack ${displaySafe(child)}`);
44162
44075
  } catch (error) {
44163
- outcome.notices.push(`${shownId} (${shownType}) is recorded as left in AWS as ${shownPhysicalId}, but cdkd could not confirm it exists (${displayAwsMessage(describeAwsFailure(error).detail)}) — keeping the record and not adopting it this run.`);
44164
- outcome.remaining.push(record);
44165
- continue;
44166
- }
44167
- if (found !== null && found.physicalId !== state.physicalId) {
44168
- outcome.remaining.push(record);
44169
- outcome.notices.push(`${shownId} (${shownType}): cdkd asked about ${shownPhysicalId} and its provider answered for ${displaySafe(found.physicalId)} — not adopting.`);
44170
- continue;
44171
- }
44172
- if (found === null) {
44173
- params.logger.debug(`orphan ${shownId}: ${shownPhysicalId} no longer exists in AWS — dropping the record`);
44174
- continue;
44175
- }
44176
- if (params.nameProperties(state.resourceType).length === 0 || ADOPTION_REFUSED_TYPES.has(state.resourceType)) {
44177
- outcome.remaining.push(record);
44178
- const why = ADOPTION_REFUSED_TYPES.has(state.resourceType) ? "a new deploy of it mints a new resource rather than colliding, and cdkd cannot update one in place — so adopting it would end in a replacement that destroys what DeletionPolicy: Retain preserved" : "cdkd does not derive that resource's physical name, so a new deploy mints a new resource instead of colliding";
44179
- outcome.notices.push(`${shownId} (${shownType}) is still in AWS as ${shownPhysicalId} from an earlier rollback. cdkd does not re-adopt this type: ${why}. Delete it yourself when you no longer need it.`);
44180
- continue;
44181
- }
44182
- if (!templateStillDeclares(params.template, record, params.nameProperties(state.resourceType))) {
44183
- outcome.remaining.push(record);
44184
- outcome.notices.push(`${shownId} (${shownType}) is still in AWS as ${shownPhysicalId} from an earlier rollback. This deploy does not create it under that name, so cdkd is leaving it alone.`);
44185
- continue;
44186
- }
44187
- if ((await claims()).has(state.physicalId)) {
44188
- outcome.refusals.push(`${shownId}: ${shownPhysicalId} is already recorded by another cdkd stack. cdkd will not adopt a resource another stack manages.`);
44189
- outcome.remaining.push(record);
44190
- continue;
44191
- }
44192
- const refreshed = Object.create(null);
44193
- for (const [key, value] of Object.entries(found.attributes ?? {})) {
44194
- if (carriesSecretMask(value)) continue;
44195
- refreshed[key] = value;
44076
+ warnUncleared(logger, child, error);
44196
44077
  }
44197
- const mergedAttributes = Object.create(null);
44198
- for (const [key, value] of Object.entries(refreshed)) mergedAttributes[key] = value;
44199
- for (const [key, value] of Object.entries(state.attributes ?? {})) mergedAttributes[key] = value;
44200
- outcome.adopted[logicalId] = {
44201
- ...state,
44202
- ...Object.keys(mergedAttributes).length > 0 || state.attributes ? { attributes: mergedAttributes } : {}
44203
- };
44204
44078
  }
44205
- return outcome;
44206
44079
  }
44207
- const NAMED_UNREADABLE_SIBLING_ROWS = 5;
44208
- function makeSiblingClaimReader(params) {
44209
- const { stateBackend, selfStackName, selfRegion, logger } = params;
44210
- return async () => {
44211
- const claimed = /* @__PURE__ */ new Set();
44212
- let refs;
44213
- try {
44214
- refs = await stateBackend.listStacks();
44215
- } catch (error) {
44216
- logger.debug(`orphan adoption: could not list sibling stacks — ${displayAwsMessage(describeAwsFailure(error).detail)}`);
44217
- return claimed;
44218
- }
44219
- for (const ref of refs) {
44220
- if (ref.stackName === selfStackName && ref.region === selfRegion) continue;
44221
- if (ref.region === void 0) continue;
44222
- try {
44223
- const sibling = await stateBackend.getState(ref.stackName, ref.region);
44224
- if (!sibling) continue;
44225
- const bag = sibling.state.resources;
44226
- if (typeof bag !== "object" || bag === null) {
44227
- logger.debug(safeMsg`orphan adoption: skipping ${displayStackName(ref.stackName)} — its state record ` + `has no readable 'resources' map, so nothing it claims can be read`);
44228
- continue;
44229
- }
44230
- const unreadable = [];
44231
- for (const [logicalId, record] of Object.entries(bag)) {
44232
- const physicalId = isReadableBag(record) ? record.physicalId : void 0;
44233
- if (typeof physicalId === "string" && physicalId !== "") claimed.add(physicalId);
44234
- else unreadable.push(logicalId);
44235
- }
44236
- if (unreadable.length > 0) {
44237
- const named = unreadable.slice(0, NAMED_UNREADABLE_SIBLING_ROWS).map((id) => displayIdent(id)).join(", ");
44238
- const rest = unreadable.length - NAMED_UNREADABLE_SIBLING_ROWS;
44239
- logger.debug(safeMsg`orphan adoption: ${displayStackName(ref.stackName)} holds ${unreadable.length} ` + safeMsg`resource record(s) with no readable physical id — ${named}` + safeMsg`${rest > 0 ? ` and ${rest} more` : ""} — skipped; the claim set is a lower ` + `bound without them`);
44240
- }
44241
- } catch (error) {
44242
- logger.debug(`orphan adoption: skipping unreadable state for ${displayStackName(ref.stackName)} — ${displayAwsMessage(describeAwsFailure(error).detail)}`);
44243
- }
44244
- }
44245
- return claimed;
44246
- };
44080
+ async function readOwnRecord(stateBackend, child, region) {
44081
+ try {
44082
+ const data = await stateBackend.getState(child, region);
44083
+ if (data && isPlainRecord(data.state) && isPlainRecord(data.state.resources) && (data.state.stackName === void 0 || data.state.stackName === child)) return data.state;
44084
+ } catch {}
44247
44085
  }
44248
-
44249
- // src/deployment/deploy-engine/rollback.ts
44250
- function redactOperationsForJournal(deps, operations) {
44251
- return operations.map((op) => {
44252
- const secrets = deps.secretsRun().perResourceSecrets.get(op.logicalId);
44253
- const templateProps = deps.secretsRun().perResourceTemplateProps.get(op.logicalId);
44254
- const sources = templateProps === void 0 ? void 0 : noEchoPositionSources(deps.noEchoRun());
44255
- const byPosition = (bag) => sources === void 0 || templateProps === void 0 ? bag : maskAtCoordinates(bag, noEchoCoordinatesOf(templateProps, bag, sources));
44256
- if ((!secrets || secrets.size === 0) && !op.previousState && sources === void 0) return op;
44257
- const ownSecrets = secrets ?? /* @__PURE__ */ new Map();
44258
- const next = { ...op };
44259
- if (next.properties) {
44260
- const properties = next.properties;
44261
- next.properties = byPosition(templateProps === void 0 ? redactForState(properties, {
44262
- provenance: "value-scan",
44263
- secrets: ownSecrets
44264
- }) : redactForState(properties, {
44265
- provenance: "template-derived",
44266
- secrets: ownSecrets,
44267
- source: templateProps,
44268
- generation: redactionClaimOf(properties)
44269
- }));
44270
- }
44271
- if (next.attemptedProperties) {
44272
- const attempted = next.attemptedProperties;
44273
- next.attemptedProperties = byPosition(templateProps === void 0 ? redactForState(attempted, {
44274
- provenance: "value-scan",
44275
- secrets: ownSecrets
44276
- }) : redactForState(attempted, {
44277
- provenance: "template-derived",
44278
- secrets: ownSecrets,
44279
- source: templateProps,
44280
- generation: "same-generation"
44281
- }));
44282
- }
44283
- if (next.previousState) {
44284
- const previous = next.previousState;
44285
- const adopted = adoptedOrphanRecords.get(deps.owner);
44286
- const loaded = adopted?.has(op.logicalId) ? adopted.get(op.logicalId) : previous;
44287
- next.previousState = applyNoEchoPersist(deps.noEchoRun(), deps.noEchoDeps(), op.logicalId, previous, keepPersistedPlainRecordLeaves(scrubResourceRecord(previous, ownSecrets, void 0, "state-readback", { observed: isSameGenerationBag(previous.observedProperties) ? "same-generation" : "unproven" }), previous, loaded ?? {}), void 0, {}, void 0, true);
44086
+ async function dropSettledNestedJournals(args) {
44087
+ const { stateBackend, parentStackName, region, runId, logger } = args;
44088
+ const depth = args.depth ?? 0;
44089
+ if (runId === void 0) return;
44090
+ if (depthExceeded(depth, parentStackName, logger)) return;
44091
+ const isSettled = (segment) => segment.runId === runId && segment.reason === "nested-pending-parent";
44092
+ for (const [logicalId, grandchildren] of args.settled) {
44093
+ const child = nestedChildStackName(parentStackName, logicalId);
44094
+ if (grandchildren.size > 0) await dropSettledNestedJournals({
44095
+ ...args,
44096
+ parentStackName: child,
44097
+ settled: grandchildren,
44098
+ depth: depth + 1
44099
+ });
44100
+ try {
44101
+ const removed = await withChildLock(args.lockManager, child, region, logger, () => stateBackend.dropRollbackJournalSegments(child, region, isSettled));
44102
+ if (removed > 0) logger.debug(safeMsg`Dropped ${removed} settled rollback journal segment(s) of ${displaySafe(child)}`);
44103
+ } catch (error) {
44104
+ warnUncleared(logger, child, error);
44288
44105
  }
44289
- return next;
44290
- });
44106
+ }
44291
44107
  }
44292
- const adoptedOrphanRecords = /* @__PURE__ */ new WeakMap();
44293
- async function adoptRollbackOrphans(deps, currentState, effectiveTemplate) {
44294
- const records = currentState.orphans ?? [];
44295
- const named = orphanRecordsPrintingBag(records);
44296
- const plan = await withPrintingSecrets(named, () => planOrphanAdoption({
44297
- records,
44298
- managedLogicalIds: new Set(Object.keys(currentState.resources)),
44299
- template: effectiveTemplate,
44300
- stackName: currentState.stackName,
44301
- region: deps.stackRegion,
44302
- getProvider: (type, provisionedBy) => deps.providerRegistry.getProviderFor({
44303
- resourceType: type,
44304
- ...provisionedBy !== void 0 && { provisionedBy }
44305
- }).provider,
44306
- nameProperties: (type) => {
44307
- const property = explicitNamePropertyFor(type);
44308
- return property === void 0 ? [] : [property];
44309
- },
44310
- readSiblingClaims: makeSiblingClaimReader({
44311
- stateBackend: deps.stateBackend,
44312
- selfStackName: currentState.stackName,
44313
- selfRegion: deps.stackRegion,
44314
- logger: deps.logger
44315
- }),
44316
- logger: { debug: (m) => deps.logger.debug(m) },
44317
- newScheme: currentState.stackInstanceId !== void 0
44318
- }));
44319
- for (const notice of plan.notices) deps.logger.info(maskSecretsInText(notice, named));
44320
- for (const warning of plan.warnings) deps.logger.warn(maskSecretsInText(warning, named));
44321
- const adoptedFrom = /* @__PURE__ */ new Map();
44322
- adoptedOrphanRecords.set(deps.owner, adoptedFrom);
44323
- if (plan.refusals.length > 0) throw new Error(safeMsg`Deploy refused — cdkd left ${plan.refusals.length} resource(s) in AWS that it cannot ` + "safely re-adopt:" + plan.refusals.map((r) => safeMsg`\n ${maskSecretsInText(r, named)}`).join(""));
44324
- for (const [logicalId, record] of Object.entries(plan.adopted)) {
44325
- adoptedFrom.set(logicalId, records.findLast((r) => r.logicalId === logicalId)?.state);
44326
- currentState.resources[logicalId] = record;
44327
- deps.logger.info(safeMsg`Adopting ${displayIdent(logicalId)} (${displayIdent(record.resourceType)}) left in AWS ` + safeMsg`by an earlier rollback as ${displaySafe(maskSecretsInText(record.physicalId, named))}`);
44108
+ async function withChildLock(lockManager, child, region, logger, fn) {
44109
+ await lockManager.acquireLockWithRetry(child, region, void 0, "rollback");
44110
+ try {
44111
+ return await fn();
44112
+ } finally {
44113
+ await lockManager.releaseLock(child, region).catch((error) => {
44114
+ logger.warn(safeMsg`Failed to release the lock of nested stack ${displayIdent(child)}: ${errorText(error)}`);
44115
+ });
44328
44116
  }
44329
- if (records.length > 0) currentState.orphans = plan.remaining;
44330
- return plan;
44331
44117
  }
44118
+ function depthExceeded(depth, parentStackName, logger) {
44119
+ if (depth < MAX_NESTED_WALK_DEPTH) return false;
44120
+ logger.warn(safeMsg`Stopped clearing nested rollback journals below ${displayIdent(parentStackName)}: ` + safeMsg`the nesting is deeper than ${MAX_NESTED_WALK_DEPTH} levels.`);
44121
+ return true;
44122
+ }
44123
+ function warnUncleared(logger, child, error) {
44124
+ logger.warn(safeMsg`Could not clear the rollback journal of nested stack ${displayIdent(child)}: ${errorText(error)}. ` + "It is inert to every parent revert (they select segments by run) and the next successful deploy of the top-level stack removes it.");
44125
+ }
44126
+ async function revertNestedChildFromJournal(args) {
44127
+ const { ctx, logicalId, childStackName, region, run, logger } = args;
44128
+ const runId = run.runId;
44129
+ const shownChild = displayIdent(childStackName);
44130
+ const refuse = (detail) => {
44131
+ throw markNonRetryable(/* @__PURE__ */ new Error(`Cannot revert nested stack ${shownChild} (row ${displayIdent(logicalId)}): ${detail} The child was NOT (fully) reverted and may still hold the failed deploy's configuration. Inspect it with 'cdkd state show'; re-run the rollback once the cause is fixed (its journal is kept), or re-deploy the parent to converge.`));
44132
+ };
44133
+ if (runId === void 0) refuse("the rollback carries no deploy run id to select its journal segments by.");
44134
+ await ctx.lockManager.acquireLockWithRetry(childStackName, region, void 0, "rollback");
44135
+ try {
44136
+ const stateData = await ctx.stateBackend.getState(childStackName, region);
44137
+ if (!stateData) refuse("its state.json is missing.");
44138
+ if (stateData.divergentBodyRegion !== void 0) refuse("its state record's region field disagrees with the key it is stored under.");
44139
+ const base = stateData.state;
44140
+ const refusalRecovery = {
44141
+ profile: ctx.destroyOptions?.profile,
44142
+ stateBucket: ctx.stateBucket,
44143
+ statePrefix: ctx.destroyOptions?.statePrefix
44144
+ };
44145
+ refuseMalformedState(base, childStackName, region, refusalRecovery);
44146
+ refuseMalformedOrphans(base, childStackName, region, refusalRecovery);
44147
+ refuseMalformedOrphanRecords(base, childStackName, region, refusalRecovery);
44148
+ const childNamingScope = nameScopeOf(childStackName, stackInstanceIdOf(base, displayStackName(childStackName)), base);
44149
+ const segments = ((await ctx.stateBackend.loadRollbackJournal(childStackName, region))?.segments ?? []).filter((segment) => segment.runId === runId);
44150
+ if (segments.length === 0) refuse("its rollback journal holds no segment for this deploy run, so there is no record of what it held before.");
44151
+ const stateResources = { ...base.resources };
44152
+ const mintedOrphans = [];
44153
+ const rolledBackCreates = [];
44154
+ const supersededHost = {};
44155
+ const restoredOutputs = segments.find((s) => s.previousOutputs)?.previousOutputs;
44156
+ const restoredReads = segments.find((s) => s.previousCrossStackReads)?.previousCrossStackReads;
44157
+ let currentEtag = stateData.etag;
44158
+ let persisted = false;
44159
+ let restoring = false;
44160
+ const { skippedOutputs: _dropped, ...carried } = base;
44161
+ const next = () => ({
44162
+ ...carried,
44163
+ ...stackInstanceIdCarriedFrom(base),
44164
+ ...supersededAfterRollback(base, supersededHost),
44165
+ version: 15,
44166
+ region,
44167
+ resources: { ...stateResources },
44168
+ ...orphansAfterRollback(base, mintedOrphans),
44169
+ ...retiredAfterRollback(base, mintedOrphans, rolledBackCreates),
44170
+ ...restoring && restoredOutputs && { outputs: { ...restoredOutputs.outputs } },
44171
+ ...restoring && restoredReads && {
44172
+ ...restoredReads.imports && { imports: [...restoredReads.imports] },
44173
+ ...restoredReads.outputReads && { outputReads: [...restoredReads.outputReads] }
44174
+ },
44175
+ ...restoring && restoredOutputs?.exportNames && { exportNames: [...restoredOutputs.exportNames] },
44176
+ lastModified: Date.now()
44177
+ });
44178
+ const nextState = () => {
44179
+ const state = next();
44180
+ if (!restoring) return state;
44181
+ if (restoredOutputs && !restoredOutputs.exportNames) delete state.exportNames;
44182
+ if (restoredOutputs) delete state.outputReferenceProvenance;
44183
+ if (restoredReads && !restoredReads.imports) delete state.imports;
44184
+ if (restoredReads && !restoredReads.outputReads) delete state.outputReads;
44185
+ return state;
44186
+ };
44187
+ const save = async () => {
44188
+ persisted = false;
44189
+ try {
44190
+ currentEtag = await ctx.stateBackend.saveState(childStackName, region, nextState(), { ...currentEtag !== void 0 && { expectedEtag: currentEtag } });
44191
+ persisted = true;
44192
+ } catch {
44193
+ try {
44194
+ const fresh = await ctx.stateBackend.getState(childStackName, region);
44195
+ currentEtag = await ctx.stateBackend.saveState(childStackName, region, nextState(), { ...fresh?.etag !== void 0 && { expectedEtag: fresh.etag } });
44196
+ persisted = true;
44197
+ } catch (retryError) {
44198
+ logger.warn(safeMsg`Failed to persist the state of nested stack ${shownChild} after reverting it: ` + safeMsg`${errorText(retryError)}. The resources were reverted in AWS.`);
44199
+ }
44200
+ }
44201
+ };
44202
+ const producerRegions = inheritProducerRegions(producerRegionsFromState({
44203
+ imports: [...base.imports ?? [], ...restoredReads?.imports ?? []],
44204
+ outputReads: [...base.outputReads ?? [], ...restoredReads?.outputReads ?? []]
44205
+ }), args.inheritedProducerRegions);
44206
+ const execCtx = {
44207
+ providerRegistry: ctx.providerRegistry,
44208
+ region,
44209
+ logger,
44210
+ ...ctx.options?.eventRecorder && { recordEvent: (event) => ctx.options.eventRecorder.record(maskEventTextWithBoundBags(event)) },
44211
+ finalSnapshotClients: ctx.options?.finalSnapshotClients,
44212
+ skipFinalSnapshot: ctx.options?.skipFinalSnapshot === true || ctx.destroyOptions?.skipFinalSnapshot === true,
44213
+ ...ctx.destroyOptions?.removeProtection === true && {
44214
+ removeProtection: true,
44215
+ foreignHolder: makeForeignHolderScan(ctx.stateBackend)({
44216
+ stackName: childStackName,
44217
+ region
44218
+ })
44219
+ },
44220
+ importedProducerRegions: producerRegions.regions,
44221
+ producerRegionsIncomplete: !producerRegions.complete,
44222
+ nestedChildRevert: true
44223
+ };
44224
+ const childCtx = {
44225
+ ...ctx,
44226
+ parentStackName: childStackName,
44227
+ parentRegion: region,
44228
+ nestedTemplates: void 0
44229
+ };
44230
+ let failures = 0;
44231
+ let warnings = 0;
44232
+ const inlinePolicyWriters = new RollbackInlinePolicyWriters();
44233
+ const settledBelow = /* @__PURE__ */ new Map();
44234
+ for (let s = segments.length - 1; s >= 0; s--) {
44235
+ const segment = segments[s];
44236
+ const skipPrefix = segment.skipPrefix ?? getCurrentSkipPrefix();
44237
+ const split = splitImportedOps(segment.operations, segment);
44238
+ const result = await withNestedStackContext(childCtx, () => withSkipPrefix(skipPrefix, () => withStackScope(childNamingScope, () => withCreateTokenLedger(ledgerForStack(ctx.stateBackend, childStackName, region), () => withNestedRevertRun(runId, async (inner) => {
44239
+ const replayed = await withPrintingSecrets(journaledOrphanPrintingBag(completedReplayEntries(split.replay), stateResources), () => replayRollback(split.replay, stateResources, childStackName, execCtx, {
44240
+ afterOp: save,
44241
+ onOrphan: (record) => mintedOrphans.push(record),
44242
+ onRolledBackCreate: (create) => rolledBackCreates.push(create),
44243
+ inlinePolicyWriters,
44244
+ failedOperations: segment.failedOperations,
44245
+ onSuperseded: (entry) => addSuperseded(supersededHost, entry),
44246
+ onSupersededSettled: (entry) => removeSuperseded(supersededHost, entry)
44247
+ }));
44248
+ for (const [id, below] of inner.settled) settledBelow.set(id, below);
44249
+ return {
44250
+ ...replayed,
44251
+ warnings: replayed.warnings + inner.warnings
44252
+ };
44253
+ })))));
44254
+ failures += result.failures;
44255
+ warnings += result.warnings + split.displaced.length;
44256
+ recordDisplacedSkips(execCtx.recordEvent, childStackName, split.displaced);
44257
+ for (const op of split.displaced) logger.warn(safeMsg`Nested stack ${childStackName}: ${op.logicalId} ` + safeMsg`${displacedOpClause(op, segment.importedResources ?? [], logger)}; ` + "not reverted, check that resource by hand");
44258
+ }
44259
+ restoring = failures === 0;
44260
+ await save();
44261
+ if (restoring && persisted && restoredOutputs && ctx.exportIndexStore) await ctx.exportIndexStore.updateForStack(childStackName, region, importableOutputs(nextState()));
44262
+ if (warnings > 0) logger.warn(safeMsg`Nested stack ${shownChild}: ${warnings} operation(s) were skipped with a warning during ` + `its revert (see above); they may need attention by hand.`);
44263
+ if (failures > 0) refuse(`${failures} of its operation(s) failed to revert (see the warnings above).`);
44264
+ if (warnings > 0) run.warnings += warnings;
44265
+ else run.settled.set(logicalId, settledBelow);
44266
+ return { warnings };
44267
+ } finally {
44268
+ await ctx.lockManager.releaseLock(childStackName, region).catch((error) => {
44269
+ logger.warn(safeMsg`Failed to release the lock of nested stack ${shownChild}: ${errorText(error)}`);
44270
+ });
44271
+ }
44272
+ }
44273
+
44274
+ // src/deployment/deploy-engine/rollback/printing-bag.ts
44332
44275
  function replayPrintingBag(deps, entries, stateResources) {
44333
44276
  const read = /* @__PURE__ */ new Map();
44334
44277
  for (const entry of entries) {
@@ -44353,70 +44296,8 @@ function replayPrintingBag(deps, entries, stateResources) {
44353
44296
  read
44354
44297
  ]);
44355
44298
  }
44356
- async function performRollback(deps, completedOperations, stateResources, stackName, previousState, failedOperations = [], priorOrphans = [], unsettledRevert) {
44357
- const orphanIndexes = [];
44358
- const orphanOps = [];
44359
- failedOperations.forEach((op, i) => {
44360
- if (!isJournaledOrphan(op) && !(op.changeType === "UPDATE" && replacementNeverSwapped(op, failedOperations))) return;
44361
- orphanIndexes.push(i);
44362
- orphanOps.push({ ...op });
44363
- });
44364
- demoteSupersededOrphans([{
44365
- operations: completedOperations,
44366
- failedOperations: orphanOps
44367
- }], priorOrphans);
44368
- const crossPrefixHolder = deps.options.crossPrefixHolder;
44369
- let crossPrefixAnswer;
44370
- const ctx = {
44371
- ...rollbackExecutorContext(deps, previousState, stackName),
44372
- createdResourceRetryCommand: pasteableCommand("cdkd rollback", [{
44373
- value: (deps.options.parentStackInfo?.parentStack ?? stackName).split("~")[0],
44374
- hole: "stack"
44375
- }], recoveryCommandFlags(deps.options.refusalRecovery).flags).command,
44376
- createdResourceHolder: crossPrefixHolder === void 0 ? void 0 : () => crossPrefixAnswer ??= crossPrefixHolder(stackName)
44377
- };
44378
- const inlinePolicyWriters = new RollbackInlinePolicyWriters();
44379
- const supersededHost = {};
44380
- const runId = deps.options.eventRecorder?.runId;
44381
- const { result, failed, unsettled, run } = await withNestedRevertRun(runId, async (scope) => {
44382
- return {
44383
- failed: orphanOps.length > 0 ? await withPrintingSecrets(replayPrintingBag(deps, orphanOps.map((op) => ({
44384
- ...op,
44385
- properties: op.attemptedProperties
44386
- })), stateResources), () => replayFailedOperations(orphanOps, stateResources, stackName, ctx, {
44387
- emitEnvelope: completedOperations.length === 0,
44388
- inlinePolicyWriters
44389
- })) : void 0,
44390
- unsettled: await revertUnsettledFailedUpdates(deps, ctx, stackName, stateResources, failedOperations, new Set(orphanIndexes), {
44391
- emitEnvelope: completedOperations.length === 0 && orphanOps.length === 0,
44392
- inlinePolicyWriters,
44393
- hooks: unsettledRevert
44394
- }),
44395
- result: await withPrintingSecrets(replayPrintingBag(deps, completedReplayEntries(completedOperations), stateResources), () => replayRollback(completedOperations, stateResources, stackName, ctx, {
44396
- inlinePolicyWriters,
44397
- failedOperations,
44398
- isInterrupted: () => deps.userInterrupted(),
44399
- onSuperseded: (entry) => addSuperseded(supersededHost, entry),
44400
- onSupersededSettled: (entry) => removeSuperseded(supersededHost, entry)
44401
- })),
44402
- run: scope
44403
- };
44404
- });
44405
- const pendingOrphans = new Set(failed?.remainingFailedOps ?? []);
44406
- const handled = new Set(orphanIndexes.filter((_, k) => !pendingOrphans.has(orphanOps[k])));
44407
- for (const index of unsettled.handled) handled.add(index);
44408
- return {
44409
- failures: result.failures + (failed?.failures ?? 0),
44410
- warnings: result.warnings + run.warnings + (failed?.warnings ?? 0) + unsettled.warnings,
44411
- skipped: result.skipped + (failed?.skipped ?? 0),
44412
- interrupted: result.interrupted || unsettled.interrupted,
44413
- orphaned: [...failed?.orphaned ?? [], ...result.orphaned],
44414
- rolledBackCreates: [...failed?.rolledBackCreates ?? [], ...result.rolledBackCreates],
44415
- superseded: supersededHost.supersededResources ?? [],
44416
- settledNested: run.settled,
44417
- remainingFailedOps: failedOperations.filter((_, i) => !handled.has(i))
44418
- };
44419
- }
44299
+
44300
+ // src/deployment/deploy-engine/rollback/unsettled-revert.ts
44420
44301
  function waitText(ms) {
44421
44302
  return ms >= 6e4 ? `${Math.round(ms / 6e4)} min` : `${Math.max(1, Math.round(ms / 1e3))}s`;
44422
44303
  }
@@ -44563,155 +44444,8 @@ async function revertUnsettledFailedUpdates(deps, ctx, stackName, stateResources
44563
44444
  });
44564
44445
  return out;
44565
44446
  }
44566
- function foreignHolderResolver(deps) {
44567
- const sameBucketHolderFor = makeForeignHolderScan(deps.stateBackend);
44568
- const crossPrefixHolder = deps.options.crossPrefixHolder;
44569
- const crossPrefixAnswers = /* @__PURE__ */ new Map();
44570
- return (self) => async (resourceType, physicalId) => {
44571
- const held = await sameBucketHolderFor(self)(resourceType, physicalId);
44572
- if (held !== void 0 || crossPrefixHolder === void 0) return held;
44573
- let answer = crossPrefixAnswers.get(self.stackName);
44574
- if (answer === void 0) {
44575
- answer = crossPrefixHolder(self.stackName);
44576
- crossPrefixAnswers.set(self.stackName, answer);
44577
- }
44578
- return answer;
44579
- };
44580
- }
44581
- async function settleJournalAfterSuccess(deps, stackName, completedOperations, previousState, finalResources, initialDeploy) {
44582
- if (deps.options.parentStackInfo) {
44583
- await writeRollbackJournalSegment(deps, stackName, completedOperations, [], NESTED_PENDING_PARENT_REASON, initialDeploy, nestedPendingSnapshot(previousState, (name) => {
44584
- const verdict = deps.outputsRun().carriedExportAliasRefusal;
44585
- const dropped = verdict === void 0 || verdict(name, name) !== void 0;
44586
- if (dropped) deps.logger.warn(verdict === void 0 ? "An export alias the previous record published was not kept for a revert of this nested stack: no export-name verdict is available." : "An export alias the previous record published was not kept for a revert of this nested stack: its name contains a NoEcho value.");
44587
- return dropped;
44588
- }));
44589
- return 0;
44590
- }
44591
- let nestedLeft = 0;
44592
- const foreignHolderFor = foreignHolderResolver(deps);
44593
- const deployRunId = deps.options.eventRecorder?.runId;
44594
- const stripOnFailure = /* @__PURE__ */ new Map();
44595
- const [ownLeft] = await Promise.all([(async () => {
44596
- await orphanUntakenResumes(deps, stackName, finalResources);
44597
- if (deps.absentJournalVersionPurge() !== void 0 && deps.stateBackend.rollbackJournalReadAbsent(stackName, deps.stackRegion)) {
44598
- await deps.absentJournalVersionPurge();
44599
- return 0;
44600
- }
44601
- const own = await settleJournaledOrphansOnSuccess({
44602
- stateBackend: deps.stateBackend,
44603
- stackName,
44604
- stackInstanceId: stackInstanceIdOf(previousState, displayStackName(stackName)),
44605
- region: deps.stackRegion,
44606
- stateResources: finalResources,
44607
- rollbackOrphans: previousState.orphans,
44608
- retiredNameGenerations: previousState.retiredNameGenerations,
44609
- newerOperations: completedOperations,
44610
- ...deployRunId !== void 0 && { deployRunId },
44611
- foreignHolder: foreignHolderFor({
44612
- stackName,
44613
- region: deps.stackRegion
44614
- }),
44615
- ctx: rollbackExecutorContext(deps, previousState, stackName),
44616
- isInterrupted: () => deps.interrupted(),
44617
- logger: deps.logger
44618
- });
44619
- if (own.keepJournal) return own.unaddressed;
44620
- if (!await deleteRollbackJournalBestEffort(deps, stackName, completedOperations.map((op) => op.logicalId))) await own.stripCleared?.();
44621
- return own.unaddressed;
44622
- })(), dropNestedChildJournals({
44623
- stateBackend: deps.stateBackend,
44624
- lockManager: deps.lockManager,
44625
- parentStackName: stackName,
44626
- region: deps.stackRegion,
44627
- resources: finalResources,
44628
- logger: deps.logger,
44629
- beforeDelete: async (child, childRecord) => {
44630
- const childState = childRecord !== void 0 && hasReadableOrphans(childRecord) ? childRecord : void 0;
44631
- const settled = await settleJournaledOrphansOnSuccess({
44632
- stateBackend: deps.stateBackend,
44633
- stackName: child,
44634
- stackInstanceId: stackInstanceIdOf(childState, displayStackName(child)),
44635
- region: deps.stackRegion,
44636
- stateResources: childState?.resources,
44637
- rollbackOrphans: childState?.orphans,
44638
- retiredNameGenerations: childState?.retiredNameGenerations,
44639
- newerOperations: [],
44640
- ...deployRunId !== void 0 && { deployRunId },
44641
- foreignHolder: foreignHolderFor({
44642
- stackName: child,
44643
- region: deps.stackRegion
44644
- }),
44645
- isInterrupted: () => deps.interrupted(),
44646
- ctx: {
44647
- ...rollbackExecutorContext(deps, childState ?? previousState, child),
44648
- producerRegionsIncomplete: true,
44649
- nestedChildStack: child
44650
- },
44651
- logger: deps.logger
44652
- });
44653
- nestedLeft += settled.unaddressed;
44654
- if (settled.stripCleared) stripOnFailure.set(child, settled.stripCleared);
44655
- return !settled.keepJournal;
44656
- },
44657
- onDeleteFailed: async (child) => {
44658
- await stripOnFailure.get(child)?.();
44659
- }
44660
- })]);
44661
- return ownLeft + nestedLeft;
44662
- }
44663
- async function deleteRollbackJournalBestEffort(deps, stackName, supersededLogicalIds = []) {
44664
- let deleted;
44665
- try {
44666
- deleted = await deps.stateBackend.deleteRollbackJournal(stackName, deps.stackRegion);
44667
- } catch (err) {
44668
- deps.logger.debug(safeMsg`Failed to delete rollback journal for ${displayStackName(stackName)}: ${describeAwsFailure(err).detail}`);
44669
- deleted = false;
44670
- }
44671
- if (deleted !== false) return true;
44672
- if (supersededLogicalIds.length === 0) return false;
44673
- try {
44674
- await deps.stateBackend.markRollbackJournalSuperseded(stackName, deps.stackRegion, supersededLogicalIds);
44675
- } catch (markErr) {
44676
- deps.logger.debug(safeMsg`Failed to record superseded logical ids on the rollback journal for ${displayStackName(stackName)}: ${describeAwsFailure(markErr).detail}`);
44677
- }
44678
- return false;
44679
- }
44680
- async function settleJournalAfterCleanRollback(deps, stackName, failedOperations, initialDeploy) {
44681
- if (failedOperations.length === 0) {
44682
- try {
44683
- await deps.stateBackend.popRollbackJournalSegment(stackName, deps.stackRegion);
44684
- } catch (err) {
44685
- deps.logger.debug(safeMsg`Failed to pop the rollback journal segment after the clean rollback: ${asIsMessage(describeAwsFailure(err).detail)}`);
44686
- return false;
44687
- }
44688
- return true;
44689
- }
44690
- try {
44691
- await deps.stateBackend.popRollbackJournalSegment(stackName, deps.stackRegion);
44692
- } catch (err) {
44693
- deps.logger.warn(safeMsg`Failed to settle the rollback journal after the clean rollback: ${describeAwsFailure(err).detail}. ` + `The journal keeps the full segment; a later rollback replay is idempotent.`);
44694
- return false;
44695
- }
44696
- if (!await writeRollbackJournalSegment(deps, stackName, [], failedOperations, "auto-rollback-clean", initialDeploy)) return true;
44697
- deps.logger.info("The automatic rollback restored the pre-deploy state. The failed resource's pre-failure record was kept — if it was left partially applied, revert it." + safeMsg`\nRevert it with: ${pasteableCommand("cdkd rollback", [{
44698
- value: stackName,
44699
- hole: "stack"
44700
- }, { literal: "--revert-failed" }]).command}`);
44701
- return true;
44702
- }
44703
- async function settleNestedChildrenAfterCleanRollback(deps, stackName, settledNested, settled) {
44704
- if (!settled) return;
44705
- await dropSettledNestedJournals({
44706
- stateBackend: deps.stateBackend,
44707
- lockManager: deps.lockManager,
44708
- parentStackName: stackName,
44709
- region: deps.stackRegion,
44710
- settled: settledNested,
44711
- runId: deps.options.eventRecorder?.runId,
44712
- logger: deps.logger
44713
- });
44714
- }
44447
+
44448
+ // src/deployment/deploy-engine/rollback/context.ts
44715
44449
  function recoveryHint(deps, topLevel) {
44716
44450
  const parent = deps.options.parentStackInfo;
44717
44451
  if (parent === void 0) return topLevel;
@@ -44740,6 +44474,237 @@ function producerRegionEvidence(deps, previousState) {
44740
44474
  };
44741
44475
  return inheritProducerRegions(own, deps.options.inheritedProducerRegions?.());
44742
44476
  }
44477
+
44478
+ // src/deployment/deploy-engine/rollback/perform.ts
44479
+ async function performRollback(deps, completedOperations, stateResources, stackName, previousState, failedOperations = [], priorOrphans = [], unsettledRevert) {
44480
+ const orphanIndexes = [];
44481
+ const orphanOps = [];
44482
+ failedOperations.forEach((op, i) => {
44483
+ if (!isJournaledOrphan(op) && !(op.changeType === "UPDATE" && replacementNeverSwapped(op, failedOperations))) return;
44484
+ orphanIndexes.push(i);
44485
+ orphanOps.push({ ...op });
44486
+ });
44487
+ demoteSupersededOrphans([{
44488
+ operations: completedOperations,
44489
+ failedOperations: orphanOps
44490
+ }], priorOrphans);
44491
+ const crossPrefixHolder = deps.options.crossPrefixHolder;
44492
+ let crossPrefixAnswer;
44493
+ const ctx = {
44494
+ ...rollbackExecutorContext(deps, previousState, stackName),
44495
+ createdResourceRetryCommand: pasteableCommand("cdkd rollback", [{
44496
+ value: (deps.options.parentStackInfo?.parentStack ?? stackName).split("~")[0],
44497
+ hole: "stack"
44498
+ }], recoveryCommandFlags(deps.options.refusalRecovery).flags).command,
44499
+ createdResourceHolder: crossPrefixHolder === void 0 ? void 0 : () => crossPrefixAnswer ??= crossPrefixHolder(stackName)
44500
+ };
44501
+ const inlinePolicyWriters = new RollbackInlinePolicyWriters();
44502
+ const supersededHost = {};
44503
+ const runId = deps.options.eventRecorder?.runId;
44504
+ const { result, failed, unsettled, run } = await withNestedRevertRun(runId, async (scope) => {
44505
+ return {
44506
+ failed: orphanOps.length > 0 ? await withPrintingSecrets(replayPrintingBag(deps, orphanOps.map((op) => ({
44507
+ ...op,
44508
+ properties: op.attemptedProperties
44509
+ })), stateResources), () => replayFailedOperations(orphanOps, stateResources, stackName, ctx, {
44510
+ emitEnvelope: completedOperations.length === 0,
44511
+ inlinePolicyWriters
44512
+ })) : void 0,
44513
+ unsettled: await revertUnsettledFailedUpdates(deps, ctx, stackName, stateResources, failedOperations, new Set(orphanIndexes), {
44514
+ emitEnvelope: completedOperations.length === 0 && orphanOps.length === 0,
44515
+ inlinePolicyWriters,
44516
+ hooks: unsettledRevert
44517
+ }),
44518
+ result: await withPrintingSecrets(replayPrintingBag(deps, completedReplayEntries(completedOperations), stateResources), () => replayRollback(completedOperations, stateResources, stackName, ctx, {
44519
+ inlinePolicyWriters,
44520
+ failedOperations,
44521
+ isInterrupted: () => deps.userInterrupted(),
44522
+ onSuperseded: (entry) => addSuperseded(supersededHost, entry),
44523
+ onSupersededSettled: (entry) => removeSuperseded(supersededHost, entry)
44524
+ })),
44525
+ run: scope
44526
+ };
44527
+ });
44528
+ const pendingOrphans = new Set(failed?.remainingFailedOps ?? []);
44529
+ const handled = new Set(orphanIndexes.filter((_, k) => !pendingOrphans.has(orphanOps[k])));
44530
+ for (const index of unsettled.handled) handled.add(index);
44531
+ return {
44532
+ failures: result.failures + (failed?.failures ?? 0),
44533
+ warnings: result.warnings + run.warnings + (failed?.warnings ?? 0) + unsettled.warnings,
44534
+ skipped: result.skipped + (failed?.skipped ?? 0),
44535
+ interrupted: result.interrupted || unsettled.interrupted,
44536
+ orphaned: [...failed?.orphaned ?? [], ...result.orphaned],
44537
+ rolledBackCreates: [...failed?.rolledBackCreates ?? [], ...result.rolledBackCreates],
44538
+ superseded: supersededHost.supersededResources ?? [],
44539
+ settledNested: run.settled,
44540
+ remainingFailedOps: failedOperations.filter((_, i) => !handled.has(i))
44541
+ };
44542
+ }
44543
+
44544
+ // src/deployment/cc-pending-requests.ts
44545
+ function hasPendingCloudControlRequest(op) {
44546
+ return op.pendingCloudControlRequest !== void 0;
44547
+ }
44548
+ function pendingRequestCount(journal) {
44549
+ return pendingRequests(journal ?? null).size;
44550
+ }
44551
+ async function resolvePendingCloudControlRequests(params) {
44552
+ const { journal, stackName, region } = params;
44553
+ if (pendingRequests(params.loaded).size === 0) return false;
44554
+ const settle = async () => {
44555
+ await params.beforeSettle?.();
44556
+ let current = params.loaded;
44557
+ if (params.underLock) try {
44558
+ current = await journal.loadRollbackJournal(stackName, region);
44559
+ } catch (error) {
44560
+ throw new CdkdError(safeMsg`cdkd ${params.command} of ${displayStackName(stackName)} refused: its rollback ` + "journal recorded an unsettled Cloud Control CREATE when this run started and cannot " + safeMsg`be read now (${displaySafe(describeAwsFailure(error).summary)}). Nothing was ` + "changed; re-run once it can be read.", "CC_PENDING_REQUEST_UNREADABLE");
44561
+ }
44562
+ const pending = pendingRequests(current);
44563
+ if (pending.size > 0) await settlePending(params, pending);
44564
+ return params.underLock !== void 0 || pending.size > 0;
44565
+ };
44566
+ return params.underLock ? params.underLock(settle) : settle();
44567
+ }
44568
+ function pendingRequests(loaded) {
44569
+ const pending = /* @__PURE__ */ new Map();
44570
+ for (const segment of loaded?.segments ?? []) for (const op of segment.failedOperations ?? []) if (hasPendingCloudControlRequest(op)) pending.set(op.pendingCloudControlRequest.requestToken, op);
44571
+ return pending;
44572
+ }
44573
+ async function settlePending(params, pending) {
44574
+ const { journal, stackName, region, command, logger } = params;
44575
+ const reader = params.reader();
44576
+ const isUnique = params.identifierUnique ?? ccIdentifierIsUnique;
44577
+ const stackShown = displayStackName(stackName);
44578
+ const source = params.stackInstanceId;
44579
+ let resolvedId;
44580
+ const stackInstanceId = () => resolvedId ??= typeof source === "function" ? source() : Promise.resolve(source);
44581
+ const settlements = /* @__PURE__ */ new Map();
44582
+ const unresolved = [];
44583
+ for (const [token, op] of pending) {
44584
+ const named = `${logicalIdShown(op.logicalId)} (${resourceTypeShown(op.resourceType)})`;
44585
+ logger.info(safeMsg`A previous run of ${stackShown} stopped waiting for the Cloud Control CREATE of ${named}; ` + "checking how it ended...");
44586
+ const outcome = await reader.resumeAbandonedRequest(token, op.logicalId, op.resourceType);
44587
+ switch (outcome.status) {
44588
+ case "succeeded":
44589
+ case "failed":
44590
+ case "cancelled": {
44591
+ const made = outcome.status === "succeeded" ? outcome.identifier : outcome.remnant;
44592
+ if (made === void 0) {
44593
+ logger.info(safeMsg`The CREATE of ${named} ${outcome.status === "cancelled" ? "was cancelled" : "failed"} ` + "in AWS and made nothing.");
44594
+ settlements.set(token, { kind: "drop" });
44595
+ break;
44596
+ }
44597
+ const madeShown = displacedPhysicalIdShown({
44598
+ ...op,
44599
+ physicalId: made
44600
+ }, logger, made) ?? "a resource";
44601
+ const held = params.stateResources?.[op.logicalId];
44602
+ if (held !== void 0 && held.physicalId === made) {
44603
+ logger.info(safeMsg`The CREATE of ${named} made ${madeShown}, which state already records.`);
44604
+ settlements.set(token, { kind: "drop" });
44605
+ break;
44606
+ }
44607
+ const unique = await isUnique({
44608
+ resourceType: op.resourceType,
44609
+ identifier: made,
44610
+ attemptedProperties: op.attemptedProperties,
44611
+ logicalId: op.logicalId,
44612
+ stackName,
44613
+ stackInstanceId: await stackInstanceId(),
44614
+ nameGenerationsThrough: generationsThrough(op, held)
44615
+ });
44616
+ const ended = outcome.status === "succeeded" ? "completed" : outcome.status === "cancelled" ? "was cancelled" : "failed";
44617
+ if (outcome.status === "succeeded" && unique && held === void 0 && params.resume?.(op, made)) {
44618
+ logger.info(safeMsg`The CREATE of ${named} completed in AWS after cdkd stopped waiting, and made ` + safeMsg`${madeShown}; this deploy's CREATE of it takes that resource over when it sends ` + "the same properties.");
44619
+ settlements.set(token, { kind: "resume" });
44620
+ break;
44621
+ }
44622
+ if (params.resume !== void 0 && !unique) logger.warn(safeMsg`The CREATE of ${named} ${ended} in AWS after cdkd stopped waiting, and made ` + safeMsg`${madeShown}. cdkd cannot prove its id is unique (it may be a name, which can ` + safeMsg`since belong to another resource), so this deploy does not take it over, and creating ${logicalIdShown(op.logicalId)} ` + "again will ask for the name it holds. Adopt it with cdkd import (--resource " + safeMsg`${logicalIdShown(op.logicalId)}=<its id>), or delete it, then re-run. It is kept in the ` + "rollback journal as a resource the failed deploy created.");
44623
+ else logger.warn(safeMsg`The CREATE of ${named} ${ended} in AWS after cdkd stopped waiting, and made ` + safeMsg`${madeShown}. It is now recorded in the rollback journal as a resource the failed ` + "deploy created: cdkd destroy, cdkd rollback --revert-failed and the next successful deploy delete it as its DeletionPolicy directs when cdkd can prove it is still the resource that create made, and otherwise name it in a warning for you to delete by hand.");
44624
+ settlements.set(token, {
44625
+ kind: "orphan",
44626
+ physicalId: made,
44627
+ unique
44628
+ });
44629
+ break;
44630
+ }
44631
+ case "not-found":
44632
+ logger.warn(safeMsg`Cloud Control no longer has the CREATE request of ${named}: requests expire after ` + "seven days, and a request is not visible from another account or region. cdkd cannot tell whether it created the resource and stops tracking the request. If it exists, adopt it with cdkd import or delete it by hand.");
44633
+ settlements.set(token, { kind: "drop" });
44634
+ break;
44635
+ case "unresolved": {
44636
+ settlements.set(token, { kind: "keep" });
44637
+ const reason = holdsSecretReference(op.attemptedProperties) ? "details withheld: its properties carry a secret" : displaySafe(describeAwsFailure(outcome.error).summary);
44638
+ unresolved.push(safeMsg` - ${named}${reason === "" ? "" : ` (${reason})`}\n` + ` Check it with: ${await reader.buildResumeCommand(token)}`);
44639
+ break;
44640
+ }
44641
+ }
44642
+ }
44643
+ if ([...settlements.values()].some((s) => s.kind === "orphan" || s.kind === "drop")) await journal.rewriteRollbackJournalFailedOperations(stackName, region, (op) => {
44644
+ if (!hasPendingCloudControlRequest(op)) return op;
44645
+ const settlement = settlements.get(op.pendingCloudControlRequest.requestToken);
44646
+ if (settlement?.kind === "drop") return withoutPendingRequest(op);
44647
+ if (settlement?.kind !== "orphan") return op;
44648
+ return {
44649
+ ...withoutPendingRequest(op),
44650
+ provisionedBy: "cc-api",
44651
+ physicalId: settlement.physicalId,
44652
+ physicalIdRecoveredFromError: true,
44653
+ ...settlement.unique && { createdIdentifierUnique: true }
44654
+ };
44655
+ });
44656
+ if (unresolved.length > 0) {
44657
+ const kept = [...pending.values()].filter((op) => settlements.get(op.pendingCloudControlRequest.requestToken)?.kind === "keep");
44658
+ const drop = dropFailedCommands(stackName, region, kept.map((op) => op.logicalId));
44659
+ const withheld = drop?.commands.some((c) => c.includes("<")) === true;
44660
+ throw new CdkdError(safeMsg`cdkd ${command} of ${stackShown} refused: a previous run stopped waiting for a Cloud ` + `Control CREATE, and cdkd still cannot tell whether it made its resource. Proceeding could leave that resource untracked. Nothing was changed.
44661
+ ${unresolved.join("\n")}\nRe-run once the request has finished and can be read. If you have reconciled it by hand (cdkd import, or deleted the resource), drop its journal entry with:` + (drop === void 0 ? "" : drop.commands.map((c) => `\n ${c}`).join("")) + (withheld ? "\nA value that is not a plain identifier is shown as a <hole>; read it from the stack's state record and rollback-journal.json." : ""), "CC_PENDING_REQUEST_UNRESOLVED");
44662
+ }
44663
+ }
44664
+ function holdsSecretReference(properties) {
44665
+ if (properties === void 0) return false;
44666
+ return carriesSecretMask(properties) || JSON.stringify(properties).includes("{{resolve:");
44667
+ }
44668
+ const ccIdentifierIsUnique = async ({ resourceType, identifier, attemptedProperties, logicalId, stackName, stackInstanceId, nameGenerationsThrough }) => {
44669
+ if (attemptedProperties === void 0 || holdsSecretReference(attemptedProperties)) return false;
44670
+ const [fields, readOnly] = await Promise.all([getPrimaryIdentifierFields(resourceType), getTopLevelReadOnlyProperties(resourceType)]);
44671
+ if (fields === void 0 || readOnly === void 0) return false;
44672
+ const parts = identifier.split("|");
44673
+ if (parts.length !== fields.length) return false;
44674
+ const sent = /* @__PURE__ */ new Set();
44675
+ const collect = (value) => {
44676
+ if (typeof value === "string" || typeof value === "number") for (const piece of nameSegments(String(value))) sent.add(piece);
44677
+ else if (Array.isArray(value)) value.forEach(collect);
44678
+ else if (value !== null && typeof value === "object") Object.values(value).forEach(collect);
44679
+ };
44680
+ collect(attemptedProperties);
44681
+ return parts.some((part, i) => {
44682
+ if (part === "" || !readOnly.has(fields[i])) return false;
44683
+ return !nameSegments(part).some((segment) => sent.has(segment) || looksLikeCdkdGeneratedName(segment, logicalId, stackName, stackInstanceId, nameGenerationsThrough === void 0 ? void 0 : { through: nameGenerationsThrough }));
44684
+ });
44685
+ };
44686
+ function generationsThrough(op, held) {
44687
+ const own = isNameGeneration(op.nameGeneration) ? op.nameGeneration : 0;
44688
+ let recorded = 0;
44689
+ for (const value of [held?.nameGeneration, held?.nameGenerationHigh]) if (isNameGeneration(value)) recorded = Math.max(recorded, value);
44690
+ return Math.max(own, recorded) + 1;
44691
+ }
44692
+ function nameSegments(value) {
44693
+ const text = value.toLowerCase();
44694
+ const arn = /^arn:[^:]*:[^:]*:[^:]*:[^:]*:(.*)$/.exec(text);
44695
+ const body = arn ? arn[1] : text;
44696
+ return [
44697
+ text,
44698
+ body,
44699
+ ...body.split(/[:/]/)
44700
+ ].filter((piece) => piece !== "");
44701
+ }
44702
+ function withoutPendingRequest(op) {
44703
+ const { pendingCloudControlRequest: _settled, ...rest } = op;
44704
+ return rest;
44705
+ }
44706
+
44707
+ // src/deployment/deploy-engine/rollback/journal-write.ts
44743
44708
  async function writeRollbackJournalSegment(deps, stackName, completedOperations, failedOperations, reason, initialDeploy, nestedPending) {
44744
44709
  if (!nestedPending && completedOperations.length === 0 && failedOperations.length === 0) return false;
44745
44710
  const redactedCompleted = redactOperationsForJournal(deps, completedOperations);
@@ -44769,6 +44734,157 @@ async function writeRollbackJournalSegment(deps, stackName, completedOperations,
44769
44734
  return false;
44770
44735
  }
44771
44736
  }
44737
+
44738
+ // src/deployment/deploy-engine/rollback/settle.ts
44739
+ function foreignHolderResolver(deps) {
44740
+ const sameBucketHolderFor = makeForeignHolderScan(deps.stateBackend);
44741
+ const crossPrefixHolder = deps.options.crossPrefixHolder;
44742
+ const crossPrefixAnswers = /* @__PURE__ */ new Map();
44743
+ return (self) => async (resourceType, physicalId) => {
44744
+ const held = await sameBucketHolderFor(self)(resourceType, physicalId);
44745
+ if (held !== void 0 || crossPrefixHolder === void 0) return held;
44746
+ let answer = crossPrefixAnswers.get(self.stackName);
44747
+ if (answer === void 0) {
44748
+ answer = crossPrefixHolder(self.stackName);
44749
+ crossPrefixAnswers.set(self.stackName, answer);
44750
+ }
44751
+ return answer;
44752
+ };
44753
+ }
44754
+ async function settleJournalAfterSuccess(deps, stackName, completedOperations, previousState, finalResources, initialDeploy) {
44755
+ if (deps.options.parentStackInfo) {
44756
+ await writeRollbackJournalSegment(deps, stackName, completedOperations, [], NESTED_PENDING_PARENT_REASON, initialDeploy, nestedPendingSnapshot(previousState, (name) => {
44757
+ const verdict = deps.outputsRun().carriedExportAliasRefusal;
44758
+ const dropped = verdict === void 0 || verdict(name, name) !== void 0;
44759
+ if (dropped) deps.logger.warn(verdict === void 0 ? "An export alias the previous record published was not kept for a revert of this nested stack: no export-name verdict is available." : "An export alias the previous record published was not kept for a revert of this nested stack: its name contains a NoEcho value.");
44760
+ return dropped;
44761
+ }));
44762
+ return 0;
44763
+ }
44764
+ let nestedLeft = 0;
44765
+ const foreignHolderFor = foreignHolderResolver(deps);
44766
+ const deployRunId = deps.options.eventRecorder?.runId;
44767
+ const stripOnFailure = /* @__PURE__ */ new Map();
44768
+ const [ownLeft] = await Promise.all([(async () => {
44769
+ await orphanUntakenResumes(deps, stackName, finalResources);
44770
+ if (deps.absentJournalVersionPurge() !== void 0 && deps.stateBackend.rollbackJournalReadAbsent(stackName, deps.stackRegion)) {
44771
+ await deps.absentJournalVersionPurge();
44772
+ return 0;
44773
+ }
44774
+ const own = await settleJournaledOrphansOnSuccess({
44775
+ stateBackend: deps.stateBackend,
44776
+ stackName,
44777
+ stackInstanceId: stackInstanceIdOf(previousState, displayStackName(stackName)),
44778
+ region: deps.stackRegion,
44779
+ stateResources: finalResources,
44780
+ rollbackOrphans: previousState.orphans,
44781
+ retiredNameGenerations: previousState.retiredNameGenerations,
44782
+ newerOperations: completedOperations,
44783
+ ...deployRunId !== void 0 && { deployRunId },
44784
+ foreignHolder: foreignHolderFor({
44785
+ stackName,
44786
+ region: deps.stackRegion
44787
+ }),
44788
+ ctx: rollbackExecutorContext(deps, previousState, stackName),
44789
+ isInterrupted: () => deps.interrupted(),
44790
+ logger: deps.logger
44791
+ });
44792
+ if (own.keepJournal) return own.unaddressed;
44793
+ if (!await deleteRollbackJournalBestEffort(deps, stackName, completedOperations.map((op) => op.logicalId))) await own.stripCleared?.();
44794
+ return own.unaddressed;
44795
+ })(), dropNestedChildJournals({
44796
+ stateBackend: deps.stateBackend,
44797
+ lockManager: deps.lockManager,
44798
+ parentStackName: stackName,
44799
+ region: deps.stackRegion,
44800
+ resources: finalResources,
44801
+ logger: deps.logger,
44802
+ beforeDelete: async (child, childRecord) => {
44803
+ const childState = childRecord !== void 0 && hasReadableOrphans(childRecord) ? childRecord : void 0;
44804
+ const settled = await settleJournaledOrphansOnSuccess({
44805
+ stateBackend: deps.stateBackend,
44806
+ stackName: child,
44807
+ stackInstanceId: stackInstanceIdOf(childState, displayStackName(child)),
44808
+ region: deps.stackRegion,
44809
+ stateResources: childState?.resources,
44810
+ rollbackOrphans: childState?.orphans,
44811
+ retiredNameGenerations: childState?.retiredNameGenerations,
44812
+ newerOperations: [],
44813
+ ...deployRunId !== void 0 && { deployRunId },
44814
+ foreignHolder: foreignHolderFor({
44815
+ stackName: child,
44816
+ region: deps.stackRegion
44817
+ }),
44818
+ isInterrupted: () => deps.interrupted(),
44819
+ ctx: {
44820
+ ...rollbackExecutorContext(deps, childState ?? previousState, child),
44821
+ producerRegionsIncomplete: true,
44822
+ nestedChildStack: child
44823
+ },
44824
+ logger: deps.logger
44825
+ });
44826
+ nestedLeft += settled.unaddressed;
44827
+ if (settled.stripCleared) stripOnFailure.set(child, settled.stripCleared);
44828
+ return !settled.keepJournal;
44829
+ },
44830
+ onDeleteFailed: async (child) => {
44831
+ await stripOnFailure.get(child)?.();
44832
+ }
44833
+ })]);
44834
+ return ownLeft + nestedLeft;
44835
+ }
44836
+ async function deleteRollbackJournalBestEffort(deps, stackName, supersededLogicalIds = []) {
44837
+ let deleted;
44838
+ try {
44839
+ deleted = await deps.stateBackend.deleteRollbackJournal(stackName, deps.stackRegion);
44840
+ } catch (err) {
44841
+ deps.logger.debug(safeMsg`Failed to delete rollback journal for ${displayStackName(stackName)}: ${describeAwsFailure(err).detail}`);
44842
+ deleted = false;
44843
+ }
44844
+ if (deleted !== false) return true;
44845
+ if (supersededLogicalIds.length === 0) return false;
44846
+ try {
44847
+ await deps.stateBackend.markRollbackJournalSuperseded(stackName, deps.stackRegion, supersededLogicalIds);
44848
+ } catch (markErr) {
44849
+ deps.logger.debug(safeMsg`Failed to record superseded logical ids on the rollback journal for ${displayStackName(stackName)}: ${describeAwsFailure(markErr).detail}`);
44850
+ }
44851
+ return false;
44852
+ }
44853
+ async function settleJournalAfterCleanRollback(deps, stackName, failedOperations, initialDeploy) {
44854
+ if (failedOperations.length === 0) {
44855
+ try {
44856
+ await deps.stateBackend.popRollbackJournalSegment(stackName, deps.stackRegion);
44857
+ } catch (err) {
44858
+ deps.logger.debug(safeMsg`Failed to pop the rollback journal segment after the clean rollback: ${asIsMessage(describeAwsFailure(err).detail)}`);
44859
+ return false;
44860
+ }
44861
+ return true;
44862
+ }
44863
+ try {
44864
+ await deps.stateBackend.popRollbackJournalSegment(stackName, deps.stackRegion);
44865
+ } catch (err) {
44866
+ deps.logger.warn(safeMsg`Failed to settle the rollback journal after the clean rollback: ${describeAwsFailure(err).detail}. ` + `The journal keeps the full segment; a later rollback replay is idempotent.`);
44867
+ return false;
44868
+ }
44869
+ if (!await writeRollbackJournalSegment(deps, stackName, [], failedOperations, "auto-rollback-clean", initialDeploy)) return true;
44870
+ deps.logger.info("The automatic rollback restored the pre-deploy state. The failed resource's pre-failure record was kept — if it was left partially applied, revert it." + safeMsg`\nRevert it with: ${pasteableCommand("cdkd rollback", [{
44871
+ value: stackName,
44872
+ hole: "stack"
44873
+ }, { literal: "--revert-failed" }]).command}`);
44874
+ return true;
44875
+ }
44876
+ async function settleNestedChildrenAfterCleanRollback(deps, stackName, settledNested, settled) {
44877
+ if (!settled) return;
44878
+ await dropSettledNestedJournals({
44879
+ stateBackend: deps.stateBackend,
44880
+ lockManager: deps.lockManager,
44881
+ parentStackName: stackName,
44882
+ region: deps.stackRegion,
44883
+ settled: settledNested,
44884
+ runId: deps.options.eventRecorder?.runId,
44885
+ logger: deps.logger
44886
+ });
44887
+ }
44772
44888
  async function orphanUntakenResumes(deps, stackName, finalResources) {
44773
44889
  if (deps.resumedCreates().size === 0) return;
44774
44890
  const untaken = new Map([...deps.resumedCreates().values()].map((r) => [r.requestToken, r]));
@@ -53884,17 +54000,8 @@ async function compareWithRecord(engine, logicalId, change, stateResources, temp
53884
54000
  };
53885
54001
  }
53886
54002
 
53887
- // src/deployment/deploy-engine/update-replace.ts
53888
- async function updateByReplacement(engine, { change, counts, currentProps, currentResource, dependencies, logicalId, oldResourceType, progress, propertyDrivenReplacement, recreateFlagged, recreateViaCcApi, recreateViaSdkProvider, renderer, resolvedProps, resourceType, stackName, stateResources, template, typeChanged, updateReplacePolicy, updateSecrets, lostWithParent, nameGenerationFields }) {
53889
- const noEchoDeleteValues = await noEchoDeleteValuesFromResolved({
53890
- record: currentResource,
53891
- templateResource: template?.Resources?.[logicalId],
53892
- resolvedProperties: resolvedProps,
53893
- noEchoParameters: noEchoPositionSources(engine.noEchoRun, stateResources, template)?.parameters ?? /* @__PURE__ */ new Set(),
53894
- conditions: engine.noEchoRun.noEchoConditions,
53895
- secrets: updateSecrets,
53896
- inputSources: template && maskedInputSources(engine.resolverContextDeps(), template, stateResources, engine.noEchoRun.noEchoConditions, stackName)
53897
- });
54003
+ // src/deployment/deploy-engine/update-replace/preflight.ts
54004
+ function refuseUnsafeReplacement(engine, { change, currentProps, currentResource, logicalId, oldResourceType, propertyDrivenReplacement, recreateFlagged, recreateViaCcApi, resourceType, typeChanged, updateReplacePolicy }) {
53898
54005
  if (propertyDrivenReplacement && !recreateFlagged && updateReplacePolicy !== "Retain") {
53899
54006
  const statefulReason = isStatefulRecreateTargetForReplace(oldResourceType, currentProps, currentResource.observedProperties);
53900
54007
  if (statefulReason && engine.options.forceStatefulRecreation !== true) {
@@ -53909,6 +54016,194 @@ async function updateByReplacement(engine, { change, counts, currentProps, curre
53909
54016
  const ccBroken = ccBrokenReason(resourceType);
53910
54017
  if (ccBroken !== void 0) throw markNonRetryable(new CdkdError(safeMsg`--recreate-via-cc-api cannot move ${logicalId} (${resourceType}) to Cloud ` + safeMsg`Control: ${ccBroken}, so cdkd keeps it on its SDK provider. Nothing was ` + safeMsg`deleted. Drop ${logicalId} from --recreate-via-cc-api.`, "RECREATE_TARGETS_INVALID"));
53911
54018
  }
54019
+ }
54020
+
54021
+ // src/deployment/deploy-engine/update-replace/recreate.ts
54022
+ async function recreateDestroyThenCreate(engine, { currentResource, equalIdIsSameResource, logicalId, noEchoDeleteValues, oldDeleteProvider, oldDeleteRoute, oldResourceType, replaceDecision, replaceProps, replaceProvider, resolvedProps, resourceType, stackName, updateReplacePolicy, updateSecrets, recreateViaCcApi }) {
54023
+ let createResult;
54024
+ refuseRestoreFromItself(resourceType, replaceProps, currentResource.physicalId, logicalId, {
54025
+ region: engine.stackRegion,
54026
+ account: engine.options.consumerAccount
54027
+ });
54028
+ const recreateFlagName = recreateViaCcApi ? "--recreate-via-cc-api" : "--recreate-via-sdk-provider";
54029
+ if (updateReplacePolicy === "Retain") {
54030
+ engine.replacementRun.retainedOldOnReplacement.add(logicalId);
54031
+ await noteRetainedResource(oldResourceType, logicalId);
54032
+ engine.logger.warn(safeMsg` ⚠ ${logicalId} has UpdateReplacePolicy: Retain — ${recreateFlagName} will ` + safeMsg`leak the old physical resource (${currentResource.physicalId}). The new ` + "resource shares the same name where applicable; if the type has user-supplied names (e.g. functionName, bucketName), the create will deterministically collide with the retained orphan.");
54033
+ } else {
54034
+ engine.logger.info(safeMsg` Destroying old ${logicalId} (${currentResource.physicalId}) before recreate...`);
54035
+ const recreateFinalSnapshotId = await prepareFinalSnapshotForDelete(engine.replacementDeps(), logicalId, oldResourceType, currentResource, updateReplacePolicy, createUnionSecretMasker([updateSecrets, secretNameBagFor(engine.secretsRun, logicalId)]));
54036
+ let recreateDeleteResult;
54037
+ try {
54038
+ recreateDeleteResult = await withPrintingSecrets(updateSecrets, () => oldDeleteProvider.delete(logicalId, currentResource.physicalId, oldResourceType, currentResource.properties, {
54039
+ expectedRegion: engine.stackRegion,
54040
+ forceDataDelete: engine.options.forceStatefulRecreation === true,
54041
+ ...recreateFinalSnapshotId !== void 0 && { finalSnapshotIdentifier: recreateFinalSnapshotId },
54042
+ ...replacementDeleteContext(engine.replacementDeps(), updateReplacePolicy),
54043
+ recordedAttributes: currentResource.attributes,
54044
+ recordedNoEchoLeaves: currentResource.noEchoLeaves,
54045
+ ...noEchoDeleteValues !== void 0 && { noEchoDeleteValues },
54046
+ maskSecrets: createUnionSecretMasker([updateSecrets, secretNameBagFor(engine.secretsRun, logicalId)])
54047
+ }));
54048
+ } catch (deleteError) {
54049
+ const shownSecrets = unionOfSecretBags([updateSecrets, printingSecretsFor(engine.secretsRun, logicalId)]);
54050
+ const deleteFailure = describeAwsFailure(deleteError);
54051
+ const destroyFailureText = (text) => safeMsg`Failed to destroy old resource ${maskSecretsInText(logicalId, shownSecrets)} ` + safeMsg`(${maskSecretsInText(currentResource.physicalId, shownSecrets)}) during ${recreateFlagName}: ` + safeMsg`${asIsMessage(maskSecretsInText(text, shownSecrets))}`;
54052
+ if (deleteFailure.redacted) engine.logger.debug(destroyFailureText(deleteFailure.detail));
54053
+ const destroyFailure = new Error(destroyFailureText(deleteFailure.redacted ? deleteFailure.summary : deleteFailure.detail), { cause: deleteError instanceof Error ? maskSecretsInError(deleteError, updateSecrets) : void 0 });
54054
+ throw deleteFailure.redacted && deleteError instanceof Error ? markRedactedCause(destroyFailure) : destroyFailure;
54055
+ }
54056
+ reportDeleteGuards(recreateDeleteResult, {
54057
+ physicalId: currentResource.physicalId,
54058
+ resourceType: oldResourceType,
54059
+ provisionedBy: oldDeleteRoute.provisionedBy
54060
+ });
54061
+ const recreateSkipReason = deleteSkipReason(recreateDeleteResult);
54062
+ if (recreateSkipReason !== void 0) throw new Error(deleteSkippedMessage(logicalId, currentResource.physicalId, recreateSkipReason, `during ${recreateFlagName}`));
54063
+ engine.logger.info(safeMsg` ${green("✓")} Old resource deleted`);
54064
+ engine.replacementRun.oldDeletedBeforeCreate.add(logicalId);
54065
+ await oldDeleteProvider.waitForNameReleased?.(logicalId, currentResource.physicalId, oldResourceType, {
54066
+ isInterrupted: () => engine.userInterrupted,
54067
+ maskSecrets: createSecretMasker(updateSecrets)
54068
+ });
54069
+ }
54070
+ engine.logger.info(safeMsg` Creating new ${logicalId}...`);
54071
+ createResult = await guardedReplacementCreate(engine, {
54072
+ logicalId,
54073
+ resourceType,
54074
+ stackName,
54075
+ createdVia: replaceDecision.provisionedBy,
54076
+ resolvedProps
54077
+ }, () => withRetry(() => engine.withRetry(() => withCurrentResourceSecrets(updateSecrets, () => replaceProvider.create(logicalId, resourceType, replaceProps, { maskSecrets: createSecretMasker(updateSecrets) })), logicalId, void 0, void 0, replaceProvider, true), logicalId, {
54078
+ maxRetries: 8,
54079
+ initialDelayMs: 2e3,
54080
+ maxDelayMs: 1e4,
54081
+ logger: engine.maskingRetryLoggerFor(updateSecrets),
54082
+ isInterrupted: () => engine.userInterrupted,
54083
+ onInterrupted: () => new InterruptedError("user"),
54084
+ isRetryable: isRecreateRetryableError
54085
+ }));
54086
+ if (equalIdIsSameResource && updateReplacePolicy === "Retain" && createResult.physicalId === currentResource.physicalId) throw new CdkdError(safeMsg`${logicalId} (${resourceType}) recreate returned the existing resource ` + safeMsg`(${currentResource.physicalId}) instead of creating a new one — its Create ` + "API is name-idempotent — and UpdateReplacePolicy: Retain means the old resource was never destroyed, so the new properties were not applied. Rename the resource in your CDK code (or remove the explicit physical name) so the recreate can produce a genuinely new resource.", "NAMED_REPLACEMENT_IDEMPOTENT_CREATE");
54087
+ return createResult;
54088
+ }
54089
+
54090
+ // src/deployment/deploy-engine/update-replace/create-first.ts
54091
+ async function replaceCreateFirst(engine, { currentResource, equalIdIsSameResource, logicalId, noEchoDeleteValues, oldDeleteProvider, oldDeleteRoute, oldResourceType, replaceDecision, replaceProps, replaceProvider, resolvedProps, resourceType, stackName, updateReplacePolicy, updateSecrets, lostWithParent, nameChange }) {
54092
+ let createResult;
54093
+ engine.logger.info(safeMsg` Creating new ${logicalId}...`);
54094
+ let deletedOldFirst = lostWithParent !== void 0;
54095
+ if (lostWithParent !== void 0) {
54096
+ engine.replacementRun.oldDeletedBeforeCreate.add(logicalId);
54097
+ engine.logger.info(safeMsg` ${logicalId} went with ${lostWithParent}, which was destroyed and re-created under the same id: re-creating it`);
54098
+ }
54099
+ try {
54100
+ createResult = await guardedReplacementCreate(engine, {
54101
+ logicalId,
54102
+ resourceType,
54103
+ stackName,
54104
+ createdVia: replaceDecision.provisionedBy,
54105
+ resolvedProps,
54106
+ keepsName: lostWithParent !== void 0
54107
+ }, () => engine.withRetry(() => withCurrentResourceSecrets(updateSecrets, () => replaceProvider.create(logicalId, resourceType, replaceProps, { maskSecrets: createSecretMasker(updateSecrets) })), logicalId, void 0, void 0, replaceProvider, lostWithParent !== void 0));
54108
+ } catch (createError) {
54109
+ const createFailure = describeAwsFailure(createError);
54110
+ const createAwsMsg = displayAwsMessage(maskSecretsInText(createFailure.detail, updateSecrets));
54111
+ const createMsg = createFailure.redacted ? displaySafe(maskSecretsInText(createFailure.summary, updateSecrets)) : createAwsMsg;
54112
+ const createSentence = createMsg.endsWith(".") ? createMsg.slice(0, -1) : createMsg;
54113
+ if (!isNameCollisionErrorFrom(createError, logicalId)) throw createError;
54114
+ if (createFailure.redacted) engine.logger.debug(safeMsg`${maskSecretsInText(logicalId, updateSecrets)}: the create-first attempt collided: ${asIsMessage(createAwsMsg)}`);
54115
+ const nameOrigin = replacementNameOrigin(logicalId, currentResource.physicalId);
54116
+ const nameHeldElsewhere = replacementRequestsDifferentName({
54117
+ oldResourceType,
54118
+ newResourceType: resourceType,
54119
+ desiredProperties: resolvedProps,
54120
+ recorded: currentResource.properties,
54121
+ observed: currentResource.observedProperties,
54122
+ physicalId: currentResource.physicalId
54123
+ });
54124
+ if (nameHeldElsewhere !== void 0) throw markNonRetryable(new CdkdError(safeMsg`${logicalId} (${resourceType}) requires replacement, but the create-first ` + safeMsg`attempt collided: ${createSentence}. ${renderNameHeldElsewhere(nameHeldElsewhere)}` + (engine.options.replace === true ? ` — so --replace was NOT applied and nothing was deleted.` : updateReplacePolicy === "Retain" ? " — so removing UpdateReplacePolicy: Retain and re-running with `cdkd deploy --replace` would delete this resource and still collide." : " — so `cdkd deploy --replace` would delete this resource and still collide.") + " Choose a name no other resource holds, or delete the resource holding it if it is yours.", "NAMED_REPLACEMENT_COLLISION", createError instanceof Error ? createError : void 0));
54125
+ const holder = replacementOldHoldsSentName({
54126
+ createType: resourceType,
54127
+ holderType: oldResourceType,
54128
+ requested: replaceProps,
54129
+ generated: applyDefaultNameForFallback(logicalId, resourceType, resolvedProps, "omit"),
54130
+ recorded: currentResource.properties,
54131
+ observed: currentResource.observedProperties,
54132
+ physicalId: currentResource.physicalId,
54133
+ logicalId,
54134
+ createdVia: replaceDecision.provisionedBy,
54135
+ holderVia: currentResource.provisionedBy,
54136
+ mask: (value) => maskSecretsInText(value, updateSecrets)
54137
+ });
54138
+ if (!holder.holds) {
54139
+ const flagClause = engine.options.replace === true ? ` --replace was NOT applied and nothing was deleted.` : updateReplacePolicy === "Retain" ? " Nothing was deleted. UpdateReplacePolicy: Retain keeps the resource being replaced in place; removing it and re-running with `cdkd deploy --replace` would refuse the same way rather than delete it." : " Nothing was deleted, and `cdkd deploy --replace` would refuse the same way rather than delete it.";
54140
+ throw markNonRetryable(new CdkdError(maskSecretsInText(`${displaySafe(logicalId)} (${displaySafe(resourceType)}) requires replacement, but the create-first attempt collided: ${holder.diagnosis} — ` + (holder.known ? "so another resource holds the colliding name (an orphan of an earlier attempt, or one made outside this stack), and deleting the resource being replaced would destroy it and collide again." + flagClause + " Remove or rename the resource holding that name if it is yours, then re-run the deploy." : "so if another resource holds it (an orphan of an earlier attempt, or one made outside this stack), deleting the resource being replaced would destroy it and collide again." + flagClause + " Remove or rename whatever holds that name if it is yours — if that is the resource being replaced itself, delete it by hand — then re-run the deploy.") + generatedReplacementHolderAdvice({
54141
+ stackName,
54142
+ logicalId,
54143
+ change: nameChange,
54144
+ oldPhysicalId: currentResource.physicalId,
54145
+ mask: (value) => maskSecretsInText(value, unionOfSecretBags([updateSecrets, printingSecretsFor(engine.secretsRun, logicalId)]))
54146
+ }) + ` Underlying collision: ${createMsg}`, updateSecrets), "NAMED_REPLACEMENT_COLLISION", createError instanceof Error ? createError : void 0));
54147
+ }
54148
+ if (updateReplacePolicy === "Retain") throw new CdkdError(safeMsg`${logicalId} (${resourceType}) requires replacement, but its physical name ` + `is still held by the existing resource AND UpdateReplacePolicy: Retain ` + safeMsg`pins that resource in place. ${nameOrigin.descriptor}. ` + safeMsg`${nameOrigin.remedy} — with Retain, the old resource keeps the name, so a ` + `same-name replacement can never proceed.`, "NAMED_REPLACEMENT_COLLISION");
54149
+ if (engine.options.replace !== true) throw new CdkdError(safeMsg`${logicalId} (${resourceType}) requires replacement, but the create-first ` + safeMsg`attempt collided with the existing resource: ${createSentence}. ` + safeMsg`${nameOrigin.descriptor}, so the CloudFormation-style safe replacement ` + "order (create the new resource before deleting the old) cannot reuse the occupied name — CloudFormation refuses this shape with \"cannot update a stack when a custom-named resource requires replacing\". " + safeMsg`${nameOrigin.remedy}, or re-run with \`cdkd deploy --replace\` to delete ` + "the old resource FIRST and recreate it under the same name (the resource is briefly unavailable while it is recreated).", "NAMED_REPLACEMENT_COLLISION");
54150
+ engine.logger.info(` Create-first collided with the existing resource's name and --replace is ` + safeMsg`set — deleting old ${logicalId} (${currentResource.physicalId}) first...`);
54151
+ deletedOldFirst = true;
54152
+ createResult = await replaceDeleteFirstAndRecreate(engine.replacementRun, engine.replacementDeps(), logicalId, resourceType, oldResourceType, currentResource, oldDeleteProvider, replaceProvider, replaceProps, updateSecrets, updateReplacePolicy, oldDeleteRoute.provisionedBy, noEchoDeleteValues);
54153
+ }
54154
+ if (equalIdIsSameResource && !deletedOldFirst && createResult.physicalId === currentResource.physicalId) {
54155
+ const idempotentNameOrigin = replacementNameOrigin(logicalId, currentResource.physicalId);
54156
+ if (updateReplacePolicy === "Retain") throw new CdkdError(safeMsg`${logicalId} (${resourceType}) requires replacement, but its Create API is ` + `name-idempotent: the create-first attempt returned the existing resource ` + safeMsg`(${currentResource.physicalId}) instead of creating a new one, and ` + `UpdateReplacePolicy: Retain pins that resource in place. ` + safeMsg`${idempotentNameOrigin.descriptor}. ${idempotentNameOrigin.remedy} — with ` + "Retain, the old resource keeps the name, so a same-name replacement can never proceed.", "NAMED_REPLACEMENT_IDEMPOTENT_CREATE");
54157
+ if (engine.options.replace !== true) throw new CdkdError(safeMsg`${logicalId} (${resourceType}) requires replacement, but its Create API is ` + `name-idempotent: the create-first attempt returned the EXISTING resource ` + safeMsg`(${currentResource.physicalId}) instead of creating a new one, so deleting ` + `the "old" resource would silently destroy the resource the deploy just ` + safeMsg`reported as created. ${idempotentNameOrigin.descriptor}; ` + safeMsg`${idempotentNameOrigin.remedy}, or re-run with ` + "`cdkd deploy --replace` to delete the old resource FIRST and recreate it under the same name (the resource is briefly unavailable while it is recreated). Note: this branch is also reached when the old resource was deleted out-of-band and the physical id is name-derived — there the create was a genuine fresh create; `--replace` converges that case too.", "NAMED_REPLACEMENT_IDEMPOTENT_CREATE");
54158
+ engine.logger.info(` Create-first returned the existing resource (name-idempotent Create API) ` + safeMsg`and --replace is set — deleting old ${logicalId} ` + safeMsg`(${currentResource.physicalId}) first...`);
54159
+ deletedOldFirst = true;
54160
+ createResult = await replaceDeleteFirstAndRecreate(engine.replacementRun, engine.replacementDeps(), logicalId, resourceType, oldResourceType, currentResource, oldDeleteProvider, replaceProvider, replaceProps, updateSecrets, updateReplacePolicy, oldDeleteRoute.provisionedBy, noEchoDeleteValues);
54161
+ }
54162
+ if (deletedOldFirst) {} else if (updateReplacePolicy === "Retain") {
54163
+ engine.replacementRun.retainedOldOnReplacement.add(logicalId);
54164
+ await noteRetainedResource(oldResourceType, logicalId);
54165
+ engine.logger.info(safeMsg` Retaining old ${logicalId} (${displayPhysicalId(currentResource.resourceType, currentResource.physicalId)}) - UpdateReplacePolicy: Retain`);
54166
+ } else {
54167
+ engine.logger.info(safeMsg` Deleting old ${logicalId} (${displayPhysicalId(currentResource.resourceType, currentResource.physicalId)})...`);
54168
+ let cleanupFinalSnapshotId;
54169
+ let snapshotBlockedDelete = false;
54170
+ try {
54171
+ cleanupFinalSnapshotId = await prepareFinalSnapshotForDelete(engine.replacementDeps(), logicalId, oldResourceType, currentResource, updateReplacePolicy, createUnionSecretMasker([updateSecrets, secretNameBagFor(engine.secretsRun, logicalId)]));
54172
+ } catch (snapshotError) {
54173
+ if (snapshotError instanceof CdkdError && snapshotError.code === "FINAL_SNAPSHOT_UNSUPPORTED") throw snapshotError;
54174
+ snapshotBlockedDelete = true;
54175
+ engine.replacementRun.replacedOldMaySurvive.set(logicalId, "kept");
54176
+ engine.logger.warn(safeMsg` ⚠ Final snapshot for old ${logicalId} (${currentResource.physicalId}) ` + safeMsg`failed: ${asIsMessage(describeAwsFailure(snapshotError).detail)}. ` + "The old resource was NOT deleted (UpdateReplacePolicy: Snapshot) — delete it manually once you have a snapshot; it is no longer tracked in state.");
54177
+ }
54178
+ if (!snapshotBlockedDelete) await deleteReplacedAfterCreate(engine.replacementRun, engine.replacementDeps(), logicalId, oldResourceType, currentResource, oldDeleteProvider, currentResource.properties, cleanupFinalSnapshotId, updateReplacePolicy, updateSecrets, oldDeleteRoute.provisionedBy, noEchoDeleteValues);
54179
+ }
54180
+ return createResult;
54181
+ }
54182
+
54183
+ // src/deployment/deploy-engine/update-replace.ts
54184
+ async function updateByReplacement(engine, { change, counts, currentProps, currentResource, dependencies, logicalId, oldResourceType, progress, propertyDrivenReplacement, recreateFlagged, recreateViaCcApi, recreateViaSdkProvider, renderer, resolvedProps, resourceType, stackName, stateResources, template, typeChanged, updateReplacePolicy, updateSecrets, lostWithParent, nameGenerationFields }) {
54185
+ const noEchoDeleteValues = await noEchoDeleteValuesFromResolved({
54186
+ record: currentResource,
54187
+ templateResource: template?.Resources?.[logicalId],
54188
+ resolvedProperties: resolvedProps,
54189
+ noEchoParameters: noEchoPositionSources(engine.noEchoRun, stateResources, template)?.parameters ?? /* @__PURE__ */ new Set(),
54190
+ conditions: engine.noEchoRun.noEchoConditions,
54191
+ secrets: updateSecrets,
54192
+ inputSources: template && maskedInputSources(engine.resolverContextDeps(), template, stateResources, engine.noEchoRun.noEchoConditions, stackName)
54193
+ });
54194
+ refuseUnsafeReplacement(engine, {
54195
+ change,
54196
+ currentProps,
54197
+ currentResource,
54198
+ logicalId,
54199
+ oldResourceType,
54200
+ propertyDrivenReplacement,
54201
+ recreateFlagged,
54202
+ recreateViaCcApi,
54203
+ resourceType,
54204
+ typeChanged,
54205
+ updateReplacePolicy
54206
+ });
53912
54207
  let replacementReason;
53913
54208
  if (recreateViaCcApi) replacementReason = "--recreate-via-cc-api flag (mid-life SDK→CC migration)";
53914
54209
  else if (recreateViaSdkProvider) replacementReason = "--recreate-via-sdk-provider flag (mid-life CC→SDK migration)";
@@ -53980,159 +54275,43 @@ async function updateByReplacement(engine, { change, counts, currentProps, curre
53980
54275
  trigger: recreateFlagName,
53981
54276
  noEchoDeleteValues
53982
54277
  });
53983
- } else if (recreateFlagged) {
53984
- refuseRestoreFromItself(resourceType, replaceProps, currentResource.physicalId, logicalId, {
53985
- region: engine.stackRegion,
53986
- account: engine.options.consumerAccount
53987
- });
53988
- const recreateFlagName = recreateViaCcApi ? "--recreate-via-cc-api" : "--recreate-via-sdk-provider";
53989
- if (updateReplacePolicy === "Retain") {
53990
- engine.replacementRun.retainedOldOnReplacement.add(logicalId);
53991
- await noteRetainedResource(oldResourceType, logicalId);
53992
- engine.logger.warn(safeMsg` ⚠ ${logicalId} has UpdateReplacePolicy: Retain — ${recreateFlagName} will ` + safeMsg`leak the old physical resource (${currentResource.physicalId}). The new ` + "resource shares the same name where applicable; if the type has user-supplied names (e.g. functionName, bucketName), the create will deterministically collide with the retained orphan.");
53993
- } else {
53994
- engine.logger.info(safeMsg` Destroying old ${logicalId} (${currentResource.physicalId}) before recreate...`);
53995
- const recreateFinalSnapshotId = await prepareFinalSnapshotForDelete(engine.replacementDeps(), logicalId, oldResourceType, currentResource, updateReplacePolicy, createUnionSecretMasker([updateSecrets, secretNameBagFor(engine.secretsRun, logicalId)]));
53996
- let recreateDeleteResult;
53997
- try {
53998
- recreateDeleteResult = await withPrintingSecrets(updateSecrets, () => oldDeleteProvider.delete(logicalId, currentResource.physicalId, oldResourceType, currentResource.properties, {
53999
- expectedRegion: engine.stackRegion,
54000
- forceDataDelete: engine.options.forceStatefulRecreation === true,
54001
- ...recreateFinalSnapshotId !== void 0 && { finalSnapshotIdentifier: recreateFinalSnapshotId },
54002
- ...replacementDeleteContext(engine.replacementDeps(), updateReplacePolicy),
54003
- recordedAttributes: currentResource.attributes,
54004
- recordedNoEchoLeaves: currentResource.noEchoLeaves,
54005
- ...noEchoDeleteValues !== void 0 && { noEchoDeleteValues },
54006
- maskSecrets: createUnionSecretMasker([updateSecrets, secretNameBagFor(engine.secretsRun, logicalId)])
54007
- }));
54008
- } catch (deleteError) {
54009
- const shownSecrets = unionOfSecretBags([updateSecrets, printingSecretsFor(engine.secretsRun, logicalId)]);
54010
- const deleteFailure = describeAwsFailure(deleteError);
54011
- const destroyFailureText = (text) => safeMsg`Failed to destroy old resource ${maskSecretsInText(logicalId, shownSecrets)} ` + safeMsg`(${maskSecretsInText(currentResource.physicalId, shownSecrets)}) during ${recreateFlagName}: ` + safeMsg`${asIsMessage(maskSecretsInText(text, shownSecrets))}`;
54012
- if (deleteFailure.redacted) engine.logger.debug(destroyFailureText(deleteFailure.detail));
54013
- const destroyFailure = new Error(destroyFailureText(deleteFailure.redacted ? deleteFailure.summary : deleteFailure.detail), { cause: deleteError instanceof Error ? maskSecretsInError(deleteError, updateSecrets) : void 0 });
54014
- throw deleteFailure.redacted && deleteError instanceof Error ? markRedactedCause(destroyFailure) : destroyFailure;
54015
- }
54016
- reportDeleteGuards(recreateDeleteResult, {
54017
- physicalId: currentResource.physicalId,
54018
- resourceType: oldResourceType,
54019
- provisionedBy: oldDeleteRoute.provisionedBy
54020
- });
54021
- const recreateSkipReason = deleteSkipReason(recreateDeleteResult);
54022
- if (recreateSkipReason !== void 0) throw new Error(deleteSkippedMessage(logicalId, currentResource.physicalId, recreateSkipReason, `during ${recreateFlagName}`));
54023
- engine.logger.info(safeMsg` ${green("✓")} Old resource deleted`);
54024
- engine.replacementRun.oldDeletedBeforeCreate.add(logicalId);
54025
- await oldDeleteProvider.waitForNameReleased?.(logicalId, currentResource.physicalId, oldResourceType, {
54026
- isInterrupted: () => engine.userInterrupted,
54027
- maskSecrets: createSecretMasker(updateSecrets)
54028
- });
54029
- }
54030
- engine.logger.info(safeMsg` Creating new ${logicalId}...`);
54031
- createResult = await guardedReplacementCreate(engine, {
54032
- logicalId,
54033
- resourceType,
54034
- stackName,
54035
- createdVia: replaceDecision.provisionedBy,
54036
- resolvedProps
54037
- }, () => withRetry(() => engine.withRetry(() => withCurrentResourceSecrets(updateSecrets, () => replaceProvider.create(logicalId, resourceType, replaceProps, { maskSecrets: createSecretMasker(updateSecrets) })), logicalId, void 0, void 0, replaceProvider, true), logicalId, {
54038
- maxRetries: 8,
54039
- initialDelayMs: 2e3,
54040
- maxDelayMs: 1e4,
54041
- logger: engine.maskingRetryLoggerFor(updateSecrets),
54042
- isInterrupted: () => engine.userInterrupted,
54043
- onInterrupted: () => new InterruptedError("user"),
54044
- isRetryable: isRecreateRetryableError
54045
- }));
54046
- if (equalIdIsSameResource && updateReplacePolicy === "Retain" && createResult.physicalId === currentResource.physicalId) throw new CdkdError(safeMsg`${logicalId} (${resourceType}) recreate returned the existing resource ` + safeMsg`(${currentResource.physicalId}) instead of creating a new one — its Create ` + "API is name-idempotent — and UpdateReplacePolicy: Retain means the old resource was never destroyed, so the new properties were not applied. Rename the resource in your CDK code (or remove the explicit physical name) so the recreate can produce a genuinely new resource.", "NAMED_REPLACEMENT_IDEMPOTENT_CREATE");
54047
- } else {
54048
- engine.logger.info(safeMsg` Creating new ${logicalId}...`);
54049
- let deletedOldFirst = lostWithParent !== void 0;
54050
- if (lostWithParent !== void 0) {
54051
- engine.replacementRun.oldDeletedBeforeCreate.add(logicalId);
54052
- engine.logger.info(safeMsg` ${logicalId} went with ${lostWithParent}, which was destroyed and re-created under the same id: re-creating it`);
54053
- }
54054
- try {
54055
- createResult = await guardedReplacementCreate(engine, {
54056
- logicalId,
54057
- resourceType,
54058
- stackName,
54059
- createdVia: replaceDecision.provisionedBy,
54060
- resolvedProps,
54061
- keepsName: lostWithParent !== void 0
54062
- }, () => engine.withRetry(() => withCurrentResourceSecrets(updateSecrets, () => replaceProvider.create(logicalId, resourceType, replaceProps, { maskSecrets: createSecretMasker(updateSecrets) })), logicalId, void 0, void 0, replaceProvider, lostWithParent !== void 0));
54063
- } catch (createError) {
54064
- const createFailure = describeAwsFailure(createError);
54065
- const createAwsMsg = displayAwsMessage(maskSecretsInText(createFailure.detail, updateSecrets));
54066
- const createMsg = createFailure.redacted ? displaySafe(maskSecretsInText(createFailure.summary, updateSecrets)) : createAwsMsg;
54067
- const createSentence = createMsg.endsWith(".") ? createMsg.slice(0, -1) : createMsg;
54068
- if (!isNameCollisionErrorFrom(createError, logicalId)) throw createError;
54069
- if (createFailure.redacted) engine.logger.debug(safeMsg`${maskSecretsInText(logicalId, updateSecrets)}: the create-first attempt collided: ${asIsMessage(createAwsMsg)}`);
54070
- const nameOrigin = replacementNameOrigin(logicalId, currentResource.physicalId);
54071
- const nameHeldElsewhere = replacementRequestsDifferentName({
54072
- oldResourceType,
54073
- newResourceType: resourceType,
54074
- desiredProperties: resolvedProps,
54075
- recorded: currentResource.properties,
54076
- observed: currentResource.observedProperties,
54077
- physicalId: currentResource.physicalId
54078
- });
54079
- if (nameHeldElsewhere !== void 0) throw markNonRetryable(new CdkdError(safeMsg`${logicalId} (${resourceType}) requires replacement, but the create-first ` + safeMsg`attempt collided: ${createSentence}. ${renderNameHeldElsewhere(nameHeldElsewhere)}` + (engine.options.replace === true ? ` — so --replace was NOT applied and nothing was deleted.` : updateReplacePolicy === "Retain" ? " — so removing UpdateReplacePolicy: Retain and re-running with `cdkd deploy --replace` would delete this resource and still collide." : " — so `cdkd deploy --replace` would delete this resource and still collide.") + " Choose a name no other resource holds, or delete the resource holding it if it is yours.", "NAMED_REPLACEMENT_COLLISION", createError instanceof Error ? createError : void 0));
54080
- const holder = replacementOldHoldsSentName({
54081
- createType: resourceType,
54082
- holderType: oldResourceType,
54083
- requested: replaceProps,
54084
- generated: applyDefaultNameForFallback(logicalId, resourceType, resolvedProps, "omit"),
54085
- recorded: currentResource.properties,
54086
- observed: currentResource.observedProperties,
54087
- physicalId: currentResource.physicalId,
54088
- logicalId,
54089
- createdVia: replaceDecision.provisionedBy,
54090
- holderVia: currentResource.provisionedBy,
54091
- mask: (value) => maskSecretsInText(value, updateSecrets)
54092
- });
54093
- if (!holder.holds) {
54094
- const flagClause = engine.options.replace === true ? ` --replace was NOT applied and nothing was deleted.` : updateReplacePolicy === "Retain" ? " Nothing was deleted. UpdateReplacePolicy: Retain keeps the resource being replaced in place; removing it and re-running with `cdkd deploy --replace` would refuse the same way rather than delete it." : " Nothing was deleted, and `cdkd deploy --replace` would refuse the same way rather than delete it.";
54095
- throw markNonRetryable(new CdkdError(maskSecretsInText(`${displaySafe(logicalId)} (${displaySafe(resourceType)}) requires replacement, but the create-first attempt collided: ${holder.diagnosis} — ` + (holder.known ? "so another resource holds the colliding name (an orphan of an earlier attempt, or one made outside this stack), and deleting the resource being replaced would destroy it and collide again." + flagClause + " Remove or rename the resource holding that name if it is yours, then re-run the deploy." : "so if another resource holds it (an orphan of an earlier attempt, or one made outside this stack), deleting the resource being replaced would destroy it and collide again." + flagClause + " Remove or rename whatever holds that name if it is yours — if that is the resource being replaced itself, delete it by hand — then re-run the deploy.") + generatedReplacementHolderAdvice({
54096
- stackName,
54097
- logicalId,
54098
- change: nameChange,
54099
- oldPhysicalId: currentResource.physicalId,
54100
- mask: (value) => maskSecretsInText(value, unionOfSecretBags([updateSecrets, printingSecretsFor(engine.secretsRun, logicalId)]))
54101
- }) + ` Underlying collision: ${createMsg}`, updateSecrets), "NAMED_REPLACEMENT_COLLISION", createError instanceof Error ? createError : void 0));
54102
- }
54103
- if (updateReplacePolicy === "Retain") throw new CdkdError(safeMsg`${logicalId} (${resourceType}) requires replacement, but its physical name ` + `is still held by the existing resource AND UpdateReplacePolicy: Retain ` + safeMsg`pins that resource in place. ${nameOrigin.descriptor}. ` + safeMsg`${nameOrigin.remedy} — with Retain, the old resource keeps the name, so a ` + `same-name replacement can never proceed.`, "NAMED_REPLACEMENT_COLLISION");
54104
- if (engine.options.replace !== true) throw new CdkdError(safeMsg`${logicalId} (${resourceType}) requires replacement, but the create-first ` + safeMsg`attempt collided with the existing resource: ${createSentence}. ` + safeMsg`${nameOrigin.descriptor}, so the CloudFormation-style safe replacement ` + "order (create the new resource before deleting the old) cannot reuse the occupied name — CloudFormation refuses this shape with \"cannot update a stack when a custom-named resource requires replacing\". " + safeMsg`${nameOrigin.remedy}, or re-run with \`cdkd deploy --replace\` to delete ` + "the old resource FIRST and recreate it under the same name (the resource is briefly unavailable while it is recreated).", "NAMED_REPLACEMENT_COLLISION");
54105
- engine.logger.info(` Create-first collided with the existing resource's name and --replace is ` + safeMsg`set — deleting old ${logicalId} (${currentResource.physicalId}) first...`);
54106
- deletedOldFirst = true;
54107
- createResult = await replaceDeleteFirstAndRecreate(engine.replacementRun, engine.replacementDeps(), logicalId, resourceType, oldResourceType, currentResource, oldDeleteProvider, replaceProvider, replaceProps, updateSecrets, updateReplacePolicy, oldDeleteRoute.provisionedBy, noEchoDeleteValues);
54108
- }
54109
- if (equalIdIsSameResource && !deletedOldFirst && createResult.physicalId === currentResource.physicalId) {
54110
- const idempotentNameOrigin = replacementNameOrigin(logicalId, currentResource.physicalId);
54111
- if (updateReplacePolicy === "Retain") throw new CdkdError(safeMsg`${logicalId} (${resourceType}) requires replacement, but its Create API is ` + `name-idempotent: the create-first attempt returned the existing resource ` + safeMsg`(${currentResource.physicalId}) instead of creating a new one, and ` + `UpdateReplacePolicy: Retain pins that resource in place. ` + safeMsg`${idempotentNameOrigin.descriptor}. ${idempotentNameOrigin.remedy} — with ` + "Retain, the old resource keeps the name, so a same-name replacement can never proceed.", "NAMED_REPLACEMENT_IDEMPOTENT_CREATE");
54112
- if (engine.options.replace !== true) throw new CdkdError(safeMsg`${logicalId} (${resourceType}) requires replacement, but its Create API is ` + `name-idempotent: the create-first attempt returned the EXISTING resource ` + safeMsg`(${currentResource.physicalId}) instead of creating a new one, so deleting ` + `the "old" resource would silently destroy the resource the deploy just ` + safeMsg`reported as created. ${idempotentNameOrigin.descriptor}; ` + safeMsg`${idempotentNameOrigin.remedy}, or re-run with ` + "`cdkd deploy --replace` to delete the old resource FIRST and recreate it under the same name (the resource is briefly unavailable while it is recreated). Note: this branch is also reached when the old resource was deleted out-of-band and the physical id is name-derived — there the create was a genuine fresh create; `--replace` converges that case too.", "NAMED_REPLACEMENT_IDEMPOTENT_CREATE");
54113
- engine.logger.info(` Create-first returned the existing resource (name-idempotent Create API) ` + safeMsg`and --replace is set — deleting old ${logicalId} ` + safeMsg`(${currentResource.physicalId}) first...`);
54114
- deletedOldFirst = true;
54115
- createResult = await replaceDeleteFirstAndRecreate(engine.replacementRun, engine.replacementDeps(), logicalId, resourceType, oldResourceType, currentResource, oldDeleteProvider, replaceProvider, replaceProps, updateSecrets, updateReplacePolicy, oldDeleteRoute.provisionedBy, noEchoDeleteValues);
54116
- }
54117
- if (deletedOldFirst) {} else if (updateReplacePolicy === "Retain") {
54118
- engine.replacementRun.retainedOldOnReplacement.add(logicalId);
54119
- await noteRetainedResource(oldResourceType, logicalId);
54120
- engine.logger.info(safeMsg` Retaining old ${logicalId} (${displayPhysicalId(currentResource.resourceType, currentResource.physicalId)}) - UpdateReplacePolicy: Retain`);
54121
- } else {
54122
- engine.logger.info(safeMsg` Deleting old ${logicalId} (${displayPhysicalId(currentResource.resourceType, currentResource.physicalId)})...`);
54123
- let cleanupFinalSnapshotId;
54124
- let snapshotBlockedDelete = false;
54125
- try {
54126
- cleanupFinalSnapshotId = await prepareFinalSnapshotForDelete(engine.replacementDeps(), logicalId, oldResourceType, currentResource, updateReplacePolicy, createUnionSecretMasker([updateSecrets, secretNameBagFor(engine.secretsRun, logicalId)]));
54127
- } catch (snapshotError) {
54128
- if (snapshotError instanceof CdkdError && snapshotError.code === "FINAL_SNAPSHOT_UNSUPPORTED") throw snapshotError;
54129
- snapshotBlockedDelete = true;
54130
- engine.replacementRun.replacedOldMaySurvive.set(logicalId, "kept");
54131
- engine.logger.warn(safeMsg` ⚠ Final snapshot for old ${logicalId} (${currentResource.physicalId}) ` + safeMsg`failed: ${asIsMessage(describeAwsFailure(snapshotError).detail)}. ` + "The old resource was NOT deleted (UpdateReplacePolicy: Snapshot) — delete it manually once you have a snapshot; it is no longer tracked in state.");
54132
- }
54133
- if (!snapshotBlockedDelete) await deleteReplacedAfterCreate(engine.replacementRun, engine.replacementDeps(), logicalId, oldResourceType, currentResource, oldDeleteProvider, currentResource.properties, cleanupFinalSnapshotId, updateReplacePolicy, updateSecrets, oldDeleteRoute.provisionedBy, noEchoDeleteValues);
54134
- }
54135
- }
54278
+ } else if (recreateFlagged) createResult = await recreateDestroyThenCreate(engine, {
54279
+ currentResource,
54280
+ equalIdIsSameResource,
54281
+ logicalId,
54282
+ noEchoDeleteValues,
54283
+ oldDeleteProvider,
54284
+ oldDeleteRoute,
54285
+ oldResourceType,
54286
+ replaceDecision,
54287
+ replaceProps,
54288
+ replaceProvider,
54289
+ resolvedProps,
54290
+ resourceType,
54291
+ stackName,
54292
+ updateReplacePolicy,
54293
+ updateSecrets,
54294
+ recreateViaCcApi
54295
+ });
54296
+ else createResult = await replaceCreateFirst(engine, {
54297
+ currentResource,
54298
+ equalIdIsSameResource,
54299
+ logicalId,
54300
+ noEchoDeleteValues,
54301
+ oldDeleteProvider,
54302
+ oldDeleteRoute,
54303
+ oldResourceType,
54304
+ replaceDecision,
54305
+ replaceProps,
54306
+ replaceProvider,
54307
+ resolvedProps,
54308
+ resourceType,
54309
+ stackName,
54310
+ updateReplacePolicy,
54311
+ updateSecrets,
54312
+ lostWithParent,
54313
+ nameChange
54314
+ });
54136
54315
  registerNoEchoAttributes(engine.secretsRun, engine.maskingDeps(), logicalId, createResult, updateSecrets, resolvedProps);
54137
54316
  if (equalIdIsSameResource && createResult.physicalId === currentResource.physicalId) engine.replacementRun.recreatedUnderSameId.add(logicalId);
54138
54317
  const recordedReplacementProperties = propertiesToRecord(resolvedProps, createResult, resourceType, replaceDecision.provisionedBy);
@@ -58212,5 +58391,5 @@ var DeployEngine = class {
58212
58391
  }
58213
58392
  };
58214
58393
 
58215
- export { planVectorIndexUpdates as $, classifyRecordedSecretRegion as $a, markSameGenerationBag as $c, isRefusedByName as $i, importableOutputKeys as $l, demoteSupersededOrphans as $n, requireConfigArray as $o, gray as $r, malformedOutputsWarning as $s, deleteJournaledOrphans as $t, runDockerForeground as $u, recordedProtectionEvidence as A, reDisableInstanceApiTermination as Aa, dbInstanceEngineChangeIsInPlace as Ac, AssemblyReader as Ad, extractDeploymentEventError as Ai, recordPhysicalNameCopy as Al, isPairableType as An, unsettledItemsField as Ao, secretBearing as Ar, refuseMalformedResourceEntriesForImport as As, hasCdkAutoDeleteTag as At, isCrossRegionRedirect as Au, declaredStreamTagsMember as B, resolveDynamicReferences as Ba, maskAtCoordinates as Bc, ownValue as Bd, APPSYNC_APIKEY_ARN_RESOURCE_PATH as Bi, wholeStringLeavesOf as Bl, calculateResourceDrift as Bn, renderStatefulReason as Bo, isExportAliasCollision as Br, refuseMalformedResourcePropertiesForOrphan as Bs, readRefactorMarkerOnce as Bt, describeDockerExecFailure as Bu, pendingMovesOutOf as C, deleteLeftInPlace as Ca, findHandledUnwrittenCreateOnly as Cc, CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION as Cd, orphanRecordsPrintingBag as Ci, spelledKeysOf as Cl, findDestructiveChanges as Cn, carriesFetchableDynamicReference as Co, computeParameterTaint as Cr, malformedLocalResourcesWarning as Cs, TABLE_INDEX_NOUN as Ct, createAssetRedirectResolver as Cu, findServiceTokenRefusals as D, ec2InstanceProtectionSite as Da, NO_CC_HANDLERS_REASON as Dc, canonicalizeRegion as Dd, secretNamedRecordNeedles as Di, recoverMaskedOutput as Dl, movedToHint as Dn, withSharedDrainBudget as Do, WITHHELD_NAME_DISPLAY as Dr, refuseMalformedResourceEntries as Ds, waitForIndexesSettled as Dt, ensureAssetStorage as Du, deferredServiceTokenWarning as E, disableInstanceApiTermination as Ea, withoutSdkUnwiredProperties as Ec, PARTITION_TABLE as Ed, secretNamedAttributeNamesOf as Ei, inheritNestedStackParameterAssociations as El, hintSidesOf as En, keepsSecretReferenceToken as Eo, resourcesNamingDeclaredParameter as Er, refuseMalformedResourceAttributesForOrphan as Es, relayedIndexBusyDelete as Et, AssetModeResolver as Eu, readProtection as F, DiffCalculator as Fa, sameLambdaFunctionAddress as Fc, utf8ByteLength as Fd, isFinalSnapshotError as Fi, recordMaskOnlyValue as Fl, replayFailedOperations as Fn, findReplacedReadersOfRecreateTargets as Fo, exportNameSecretExposure as Fr, malformedDriftResourcePropertiesWarning as Fs, IMPLICIT_DELETE_DEPENDENCIES as Ft, validateContainerRepoName as Fu, streamMemberRefusals as G, assertSendableRoleArn as Ga, noEchoLeavesOf as Gc, resolveAssemblyPath as Gd, stringifyIfAssigned as Gi, S3StateBackend as Gl, updatePartialReason as Gn, toFiniteNumber as Go, refuseRestoreFromItself as Gr, malformedOrphansWarning as Gs, updateRefactorMarker as Gt, dockerSpawnEnvWithSensitive as Gu, reverseMapStreamPolicy as H, refuseUnreadableCdkCrossAccountRefs as Ha, maskWholeValue as Hc, describeFileReadFailure as Hd, secretSegmentsOfState as Hi, isSingleDynamicReferenceToken as Hl, equalModuloMask as Hn, coerceWarmThroughput as Ho, DEFAULT_RESOURCE_TIMEOUT_MS as Hr, UNREADABLE_ORPHANS_CONTAINER_ROW as Hs, refactorMarkerRefusalMessage as Ht, redactedCause as Hu, DynamoDBGlobalTableProvider as I, IntrinsicFunctionResolver as Ia, DagBuilder as Ic, defineOwnKey as Id, refusesFinalSnapshot as Ii, recordMaskOnlyValuesIn as Il, replayRollback as In, shownType as Io, isWholeDynamicReferenceValue as Ir, malformedResourcePropertiesWarning as Is, computeImplicitDeleteEdges as It, BOOTSTRAP_MARKER_PREFIX as Iu, isTtlAlreadyDisabled as J, sendableAssumeRoleCommand as Ja, readbackPathFor as Jc, clearBucketRegionCache as Jd, planTagDiff as Ji, describeRegionValueKind as Jl, reserveStackCreateToken as Jn, configBooleanRefusal as Jo, getStackRecords as Jr, repairMalformedOrphansForReadOnly as Js, formatResourceLine as Jt, warnFinchArgvExposure as Ju, streamPolicyMatchesDeclared as K, explicitRoleArnOrThrow as Ka, noEchoOutputsComparison as Kc, injectAwsRegion as Kd, DBPROXY_TAGS_WHAT as Ki, splitImportedOps as Kl, earliestDefined as Kn, coerceCfnBoolean as Ko, awaitInFlightSibling as Kr, refuseMalformedOrphans as Ks, getPriorAttempts as Kt, finchSecretArgvRefusal as Ku, STREAM_POLICY_KEY as L, isAlwaysLiveAttribute as La, TemplateParser as Lc, hasOwnKey as Ld, unsupportedFinalSnapshotError as Li, recordNoEchoAttributeValues as Ll, recordAfterRollbackUpdate as Ln, MULTI_REGION_RECREATE_BLOCKED_TYPES as Lo, noEchoParameterValueSeed as Lr, refuseMalformedResourcePropertiesForDestroy as Ls, keptForRetainedRecord as Lt, buildDockerImage as Lu, PROTECTION_PROPERTY_BY_TYPE as M, onlySecretReferencesDiffer as Ma, emrClusterInstancesReplaced as Mc, processStackMessages as Md, PRE_DELETE_SNAPSHOT_TYPES as Mi, splitGetAttStringForm as Ml, mappingPairs as Mn, unsettledPropertiesOf as Mo, secretSafeKeyDisplay as Mr, refuseMalformedResourceEntriesForOrphan as Ms, enclosingDeadlineExpired as Mt, parseBootstrapMarker as Mu, isProtectionValueActive as N, unchangedBehindSecretReference as Na, canonicalLambdaFunctionName as Nc, describeJsonParseFailure as Nd, ccRoutedFinalSnapshotError as Ni, carriesSecretMask as Nl, parseMappingFile as Nn, withUnsettledProperties as No, carriedExportAliasExposure as Nr, repairMalformedResourceEntriesForReadOnly as Ns, enclosingDeadlineRemainingMs as Nt, readBootstrapMarkerBody as Nu, serviceTokenBlockingReason as O, isTerminationProtectionPropagationError as Oa, hasNoCloudControlHandlers as Oc, derivePartitionAndUrlSuffix as Od, stateSecretNameNeedles as Oi, physicalNameCopiesOf as Ol, rollbackOrphanIds as On, INTRINSIC_KEYS as Oo, displayTextOrWithheld as Or, refuseMalformedResourceEntriesForDeploy as Os, ECR_AUTO_DELETE_IMAGES_TAG as Ot, buildDenyExternalAccessPolicy as Ou, perType as P, isWaitAbandonedError as Pa, lambdaFunctionNameForMask as Pc, parseFailureDebugDetail as Pd, effectiveDeletionPolicy as Pi, provenPublicValue as Pl, proposeRenames as Pn, withoutUnsettledProperties as Po, exportNameNoEchoParameters as Pr, unreadableResourceEntries as Ps, withResourceDeadline as Pt, validateAssetBucketName as Pu, sendTtlWaitingOutRateLimit as Q, envCredentialsAreAssumedRole as Qa, liveMatchesUnresolvedTokenFrame as Qc, tagPlanWarning as Qi, hasUnverifiableParameterRefusal as Ql, seedsDeleteFirstGuard as Qn, replayWarn as Qo, cyan as Qr, malformedOutputsRefusalMessage as Qs, resolvePendingCloudControlRequests as Qt, getDockerCmd as Qu, STREAM_TAGS_KEY as R, poisonRenderedSpellingsCollidingIn as Ra, canonicalCoordinates as Rc, hasPlainPrototype$1 as Rd, createPreDeleteFinalSnapshot as Ri, recordNoEchoParameterFreshValue as Rl, settleUnsettledPrevious as Rn, isStatefulRecreateTargetForReplace as Ro, collectDeclaredOutputNames as Rr, refuseMalformedResourcePropertiesForDrift as Rs, recordRetainedForReadoption as Rt, resolveDockerContextDirectory as Ru, hasPendingMovesOut as S, deleteIndeterminateGuards as Sa, findActionableSdkUnwired as Sc, uploadCfnTemplate as Sd, namingSecretsWithRecordedNoEcho as Si, isUncertifiedBaselineMaskPosition as Sl, constructPathOf as Sn, isImpossibleEmptyStoredAttribute as So, inheritProducerRegions as Sr, malformedLocalResourceEntriesWarning as Ss, INDEX_SETTLE_POLL_INTERVAL_MS as St, buildAssetRedirectMap as Su, refusePendingMovesOut as T, withIndeterminateGuard as Ta, unwrittenCreateOnlyReplacement as Tc, expectedOwnerParam as Td, secretNamePrintingBags as Ti, identityKeyFor as Tl, findRefactorHints as Tn, carriesDynamicReference as To, reachableDivergentParameters as Tr, malformedScrubResourceEntriesRefusalMessage as Ts, maskedLogger as Tt, rewriteTemplateAssetReferences as Tu, streamDeclaresPolicy as U, applyRoleArnIfSet as Ua, maskedLeafCoordinatesOf as Uc, displayAssemblyPath as Ud, withSecretPhysicalIdsMaskedInState as Ui, LockManager as Ul, undeclaredEmptyObservedKeys as Un, isWarmThroughputDecrease as Uo, DEFAULT_RESOURCE_WARN_AFTER_MS as Ur, hasReadableOrphans as Us, refuseRefactorMarker as Ut, redactedDockerCause as Uu, planStreamMemberOps as V, producerLookupOver as Va, maskReadbackAtCoordinates as Vc, absoluteAssemblyPathEscape as Vd, maskedSecretSegment as Vi, WHOLE_DYNAMIC_REFERENCE_PATTERN as Vl, equalModuloMarkedMask as Vn, WARM_THROUGHPUT_MEMBERS as Vo, bindingSkippedOutputs as Vr, repairMalformedResourcePropertiesForReadOnly as Vs, refactorMarkerMovesOf as Vt, describeDockerFailure as Vu, streamDeclaresTags as W, assertFlagRoleArn as Wa, noEchoCoordinatesOf as Wc, renderAssemblyPathEscape as Wd, definedAttributes as Wi, isLockInfoExpired as Wl, updatePartialMessage as Wn, toCfnInteger as Wo, maskingRetryLogger as Wr, malformedOrphansRefusalMessage as Ws, sameMove as Wt, redactDockerArgvValues as Wu, planTimeToLive as X, applyCallerIdentityCredentials as Xa, recordedNoEchoValuesOf as Xc, refuseMalformedDesiredTags as Xi, hasReadableExportSet as Xl, acquireIdempotencyToken as Xn, configStringRefusal as Xo, replacedDeleteFailureVerdict as Xr, malformedExportSourceWarning as Xs, planOrphanAdoption as Xt, isMalformedEnvKey as Xu, isTtlRateLimited as Y, AWS_CREDENTIAL_ENV_KEYS as Ya, readsNoEchoSource as Yc, resolveBucketRegion as Yd, readTagList as Yi, exportNamesCarriedFrom as Yl, withCreateTokenLedger as Yn, configIntegerRefusal as Yo, withStackRecords as Yr, malformedExportNamesWarning as Ys, makeSiblingClaimReader as Yt, isDockerClientEnvKey as Yu, readTtlSpec as Z, callerEnvCredentials as Za, valueAtCoordinate as Zc, tagMapAsList as Zi, hasReasonlessBaselineRefusal as Zl, planRollback as Zn, readConfigString as Zo, bold as Zr, malformedLocalOutputsWarning as Zs, pendingRequestCount as Zt, formatDockerLoginError as Zu, findNestedTemplateTreeDefect as _, resolvedResourceTimeoutMs as _a, STATE_RESOURCES_MALFORMED as _c, ssmResolvedValueType as _d, withAttemptedItemsMasked as _i, scrubResourceRecord as _l, collectNestedChildUnaddressed as _n, keepHeldTokenProvenance as _o, retiredAfterRollback as _r, refuseMalformedOrphansForOrphan as _s, compensateRemovedDeletionProtection as _t, withStackInstanceIdWithheld as _u, withApiLimit as a, wouldReturnToSdkProvider as aa, refuseDivergentRecordRegionForDestroy as ac, getDefaultStateBucketName as ad, holdsSupersededResources as ai, hasMaskableValues as al, sameJournaledOrphans as an, s3BucketDualStackDomainName as ao, replacementNeverSwapped as ar, withRetry as as, contributorInsightsRefusals as at, stackInstanceIdCarriedFrom as au, renderNestedTemplateTreeDefect as b, RollbackInlinePolicyWriters as ba, hasReadableOutputs as bc, MIGRATE_TMP_PREFIX as bd, journaledOrphanPrintingBag as bi, DYNAMIC_REFERENCE_TOKEN_SCAN as bl, DeploymentEventsReader as bn, recordedReferenceRegions as bo, withNameGenerationReached as br, unreadableOrphanRecords as bs, resolveDynamoDbDeleteBudgetMs as bt, stringifyValue as bu, mergeNoChangeOutputs as c, customResourceResponseExpirationWarning as ca, malformedStateRefusalMessage as cc, resolveApp as cd, supersededAfterRollback as ci, printingCorpusOf as cl, displacedOpClause as cn, coerceParameterTypedValue as co, REDACTED_DELETE_ADDRESS_SKIP_REASON as cr, declaresNoEcho as cs, planIndexContributorInsightsOps as ct, timePhase as cu, makeCanonicalizePropertiesFn as d, isCustomResourceType as da, refuseMalformedResourcesForExport as dc, resolveSkipPrefix as dd, supersededResourcesOf as di, shareLogOnlyValues as dl, getNestedRevertRun as dn, AWS_NO_VALUE as do, redactedDeleteAddressSkip as dr, malformedOrphanRecordsRefusalMessage as ds, reverseMapTableContributorInsights as dt, CrossPrefixScanCache as du, markDeleteStarted as ea, refuseMalformedNestedChildOutputs as ec, runDockerStreaming as ed, green as ei, redactForState as el, dropFailedCommands as en, classifyReplaySecretRegion as eo, isJournaledOrphan as er, requireConfigObject as es, readbackVectorIndexes as et, importableOutputs as eu, conditionFingerprint as f, getCurrentResourceSecrets as fa, refuseMalformedState as fc, resolveStateBucketWithDefault as fd, withoutSuperseded as fi, unionOfSecretBags as fl, nestedChildStackName as fn, cfnRefValueFromPhysicalId as fo, removeProtectionTypeList as fr, malformedOrphanRecordsWarning as fs, stripIndexContributorInsights as ft, applyCrossPrefixScan as fu, childTemplateLoader as g, waitForGoneAfterDelete as ga, withheldAccountClause as gc, warnDeprecatedNoPrefixCliFlag as gd, noEchoParameterNamesOf as gi, maskSecretsInText as gl, withNestedRevertRun as gn, parseWebACLArn as go, nameScopeOf as gr, refuseMalformedOrphanRecordsForDestroy as gs, beginDeleteWait as gt, stackInstanceIdOf as gu, readRecordedConditionVerdicts as h, CloudControlProvider as ha, accountArgs as hc, stateBucketExistenceConfirmed as hd, noEchoExactEchoLeavesOf as hi, maskSecretsInError as hl, revertedNestedRowIds as hn, refStateLookupFromResource as ho, nameGenerationHighWaterOf as hr, refuseMalformedOrphanRecords as hs, DYNAMODB_DELETE_POLL_COST_MS as ht, isNotImplemented as hu, lookupEachName as i, isCustomResource as ia, STATE_REGION_DIVERGED as ic, synthesisStatusMessage as id, deleteSupersededEntry as ii, createUnionSecretMasker as il, loadJournaledOrphans as in, s3BucketDomainName as io, recordUnderIdIsNotOwn as ir, describeTypeWithThrottleRetry as is, CONTRIBUTOR_INSIGHTS_KEY as it, shouldRetainResource as iu, recordedProtectionNote as j, reEnableInstanceApiTermination as ja, ecsServiceLaunchTypeSetOrChanged as jc, StageLoadError as jd, ATOMIC_FINAL_SNAPSHOT_TYPES as ji, recordNestedStackParameterExpressions as jl, looselyEqual as jn, unsettledItemsOf as jo, secretBearingStateKeyWarning as jr, refuseMalformedResourceEntriesForImportSave as js, isTruthyCfnBoolean as jt, getBootstrapMarkerKey as ju, diffSecurity as k, observeThenDisableInstanceApiTermination as ka, blockDeviceMappingsDifferOnlyInDeleteOnTermination as kc, refuseFailedLookups as kd, storedSecretNameNeedles as ki, recordAttributeIdCopy as kl, withMovedTo as kn, isUsableAttemptedName as ko, exportAliasCollisionScrubWarning as kr, refuseMalformedResourceEntriesForDestroy as ks, S3_AUTO_DELETE_OBJECTS_TAG as kt, assertAssetBucketRegion as ku, crossStackOutputProvenanceSource as l, TemplateNoEchoReresolver as la, refuseMalformedResourcesForDeploy as lc, resolveAutoAssetStorage as ld, supersededHeldByOtherTypeWarning as li, recordLogOnlyParameterValue as ll, displacedPhysicalIdShown as ln, isUnboundTemplateParameter as lo, isRedactedRecordedValue as lr, deployRefusesOrphanRowsReason as ls, readContributorInsightsSpec as lt, rebuildClientForBucketRegion as lu, parentSuppliedValues as m, waitForLambdaFunctionActive as ma, JSON_LISTING_HOLE_VALUE as mc, resolveUseCdkBootstrapAssets as md, noEchoComparisonForTemplate as mi, errorCauseChain as ml, revertNestedChildFromJournal as mn, lacksRecordedTableArn as mo, nameGenerationCarriedFrom as mr, previewableOrphanRecords as ms, DYNAMODB_DELETE_MIN_RESOURCE_TIMEOUT_MS as mt, isAccessDenied$1 as mu, chunks as n, ProviderRegistry as na, refuseMalformedOutputsForDestroy as nc, getDockerImageBySourceHash as nd, yellow as ni, snapshotPassProvenance as nl, isHandledOrphan as nn, regionLessSecretName as no, planFailedOps as nr, prefetchCreateOnlyPropertyPaths as ns, vectorIndexesSettled as nt, orphansAfterRollback as nu, isSecretBearingReferenceString as o, CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID as oa, malformedRenderedContainersWarning as oc, getLegacyStateBucketName as od, isSupersededResourceRecord as oi, literalSplitDelimitersOf as ol, makeForeignHolderScan as on, s3BucketRegionalDomainName as oo, resolveReplacementOldType as or, parameterInputsFor as os, indexDeclaresContributorInsights as ot, PhaseClock as ou, conditionInputsFrom as p, withPrintingSecrets as pa, repairMalformedResourcesForReadOnly as pc, resolveStateBucketWithDefaultAndSource as pd, noEchoAttributeNamesOf as pi, createSecretMasker as pl, recordDisplacedSkips as pn, isStalePlaceholderArnAttribute as po, orphanNeedsIdentity as pr, malformedOrphanRowsKeptWarning as ps, DYNAMODB_DELETE_DEADLINE_MARGIN_MS as pt, crossPrefixDeniedWarning as pu, streamTagsMatchDeclared as q, isIamRoleArn as qa, passedNoEchoParametersOf as qc, injectedAwsRegionValue as qd, DBPROXY_TAG_OPTIONS as qi, acceptedCreateOnlyDropsOf as ql, ledgerForStack as qn, coerceCfnInteger as qo, destroyStackRecordsView as qr, refuseMalformedOrphansForDestroy as qs, markRefusedBeforeApplying as qt, partitionSensitiveEnv as qu, isAccessDeniedError as r, ccBrokenReason as ra, repairMalformedOutputsForReadOnly as rc, Synthesizer as rd, addSuperseded as ri, carryLogOnlyValues as rl, journaledOrphanLines as rn, s3BucketArn as ro, recheckFailedPlan as rr, templateResourceTypes as rs, vectorIndexesShapeDetail as rt, orphansCarriedFrom as ru, keptWholeReasonText as s, applyCustomResourceResponseExpiration as sa, malformedResourcesWarning as sc, loadCdkJson as sd, removeSuperseded as si, logOnlyValueCount as sl, NESTED_PENDING_PARENT_REASON as sn, s3BucketWebsiteUrl as so, findNestedStackTypeChanges as sr, passedParameterClassesOf as ss, planContributorInsightsOp as st, renderPhaseTimings as su, DeployEngine as t, CC_BROKEN_REASON as ta, refuseMalformedOutputs as tc, AssetManifestLoader as td, red as ti, recordReferenceProvenanceEntry as tl, dropFailedHint as tn, producerRegionsFromState as to, isReplacementOrphan as tr, requireConfigString as ts, vectorIndexesForCreate as tt, isReadableBag as tu, inheritedProvenanceForChildDiff as u, readsNoEchoDeleteValues as ua, refuseMalformedResourcesForDestroy as uc, resolveCaptureObservedState as ud, supersededHolderOf as ui, recordLogOnlyValue as ul, dropSettledNestedJournals as un, parameterTypeMayLoseSecretIdentity as uo, redactedDeleteAddressFields as ur, isReadableOrphanRecord as us, reverseMapIndexContributorInsights as ut, CrossPrefixReadError as uu, isAbsoluteAssetPath as v, setResolvedResourceTimeouts as va, UNREADABLE_RESOURCES_MAP_ROW as vc, CFN_TEMPLATE_BODY_LIMIT as vd, createReadOnlyAttributeHealerFactory as vi, withPhysicalNameCopies as vl, getCurrentNestedStackContext as vn, outputReferenceProvenanceOf as vo, retiredNameGenerationsAfter as vr, repairMalformedOrphanRecordsForReadOnly as vs, deleteBudgetKey as vt, AssetPublisher as vu, pendingMovesRefusalMessage as w, deleteSkipReason as wa, findSdkUnwiredProperties as wc, decodeListingKey as wd, secretNamePrintingBag as wi, pathCrossesDottedKey as wl, formatDestructiveChange as wn, isNamelessDynamicReferenceError as wo, namesAnyDeclaredParameter as wr, malformedResourceEntriesWarning as ws, deleteTableWithIndexBusyRetry as wt, loadPublishableAssetManifest as wu, templateIdentity as x, UNSPECIFIED_SKIP_REASON as xa, hasReadableResources as xc, findLargeInlineResources as xd, maskEventTextWithBoundBags as xi, dynamicReferenceTokens as xl, DeploymentEventsStore as xn, getAccountInfo as xo, getCurrentProducerRegions as xr, isReadableResourceEntry as xs, DELETE_INDEX_WAIT_PROCEED_NOTE as xt, WorkGraph as xu, listNestedTemplateRows as y, slowCcOperationTimeoutMs as ya, displayLogicalId as yc, CFN_TEMPLATE_URL_LIMIT as yd, completedReplayEntries as yi, withoutPhysicalNameCopies as yl, withNestedStackContext as yn, recordedOutputReferenceRegions as yo, retiredNameGenerationsLeaving as yr, unpreviewableOrphanRecords as ys, resolveDynamoDbDeleteBudgetClock as yt, isSensitiveAttributeName as yu, declaredStreamPolicyMember as z, isSettledInstanceState as za, isMarkedCoordinate as zc, nullPrototypeRecord as zd, buildFinalSnapshotIdentifier as zi, recordProvenPublicExpression as zl, withUnprovenUnsettled as zn, isStatefulRecreateTargetSync as zo, collectPublishedOutputNames as zr, refuseMalformedResourcePropertiesForExport as zs, readRefactorMarker as zt, describeDockerCapturedOutput as zu };
58216
- //# sourceMappingURL=deploy-engine-BktCSZdi.js.map
58394
+ export { planVectorIndexUpdates as $, envCredentialsAreAssumedRole as $a, liveMatchesUnresolvedTokenFrame as $c, tagPlanWarning as $i, importableOutputs as $l, demoteSupersededOrphans as $n, replayWarn as $o, isSupersededResourceRecord as $r, malformedOutputsRefusalMessage as $s, displacedPhysicalIdShown as $t, getDockerCmd as $u, recordedProtectionEvidence as A, observeThenDisableInstanceApiTermination as Aa, blockDeviceMappingsDifferOnlyInDeleteOnTermination as Ac, refuseFailedLookups as Ad, extractDeploymentEventError as Ai, recordAttributeIdCopy as Al, isPairableType as An, isUsableAttemptedName as Ao, secretBearing as Ar, refuseMalformedResourceEntriesForDestroy as As, hasCdkAutoDeleteTag as At, assertAssetBucketRegion as Au, declaredStreamTagsMember as B, isSettledInstanceState as Ba, isMarkedCoordinate as Bc, nullPrototypeRecord as Bd, isFinalSnapshotError as Bi, recordProvenPublicExpression as Bl, calculateResourceDrift as Bn, isStatefulRecreateTargetSync as Bo, isExportAliasCollision as Br, refuseMalformedResourcePropertiesForExport as Bs, readRefactorMarkerOnce as Bt, describeDockerCapturedOutput as Bu, pendingMovesOutOf as C, deleteIndeterminateGuards as Ca, findActionableSdkUnwired as Cc, uploadCfnTemplate as Cd, orphanRecordsPrintingBag as Ci, isUncertifiedBaselineMaskPosition as Cl, findDestructiveChanges as Cn, isImpossibleEmptyStoredAttribute as Co, computeParameterTaint as Cr, malformedLocalResourceEntriesWarning as Cs, TABLE_INDEX_NOUN as Ct, buildAssetRedirectMap as Cu, findServiceTokenRefusals as D, disableInstanceApiTermination as Da, withoutSdkUnwiredProperties as Dc, PARTITION_TABLE as Dd, secretNamedRecordNeedles as Di, inheritNestedStackParameterAssociations as Dl, movedToHint as Dn, keepsSecretReferenceToken as Do, WITHHELD_NAME_DISPLAY as Dr, refuseMalformedResourceAttributesForOrphan as Ds, waitForIndexesSettled as Dt, AssetModeResolver as Du, deferredServiceTokenWarning as E, withIndeterminateGuard as Ea, unwrittenCreateOnlyReplacement as Ec, expectedOwnerParam as Ed, secretNamedAttributeNamesOf as Ei, identityKeyFor as El, hintSidesOf as En, carriesDynamicReference as Eo, resourcesNamingDeclaredParameter as Er, malformedScrubResourceEntriesRefusalMessage as Es, relayedIndexBusyDelete as Et, rewriteTemplateAssetReferences as Eu, readProtection as F, isWaitAbandonedError as Fa, lambdaFunctionNameForMask as Fc, parseFailureDebugDetail as Fd, ATOMIC_FINAL_SNAPSHOT_TYPES as Fi, provenPublicValue as Fl, replayFailedOperations as Fn, withoutUnsettledProperties as Fo, exportNameSecretExposure as Fr, unreadableResourceEntries as Fs, IMPLICIT_DELETE_DEPENDENCIES as Ft, validateAssetBucketName as Fu, streamMemberRefusals as G, assertFlagRoleArn as Ga, noEchoCoordinatesOf as Gc, renderAssemblyPathEscape as Gd, definedAttributes as Gi, isLockInfoExpired as Gl, updatePartialReason as Gn, toCfnInteger as Go, awaitInFlightSibling as Gr, malformedOrphansRefusalMessage as Gs, updateRefactorMarker as Gt, redactDockerArgvValues as Gu, reverseMapStreamPolicy as H, producerLookupOver as Ha, maskReadbackAtCoordinates as Hc, absoluteAssemblyPathEscape as Hd, unsupportedFinalSnapshotError as Hi, WHOLE_DYNAMIC_REFERENCE_PATTERN as Hl, equalModuloMask as Hn, WARM_THROUGHPUT_MEMBERS as Ho, DEFAULT_RESOURCE_TIMEOUT_MS as Hr, repairMalformedResourcePropertiesForReadOnly as Hs, refactorMarkerRefusalMessage as Ht, describeDockerFailure as Hu, DynamoDBGlobalTableProvider as I, DiffCalculator as Ia, sameLambdaFunctionAddress as Ic, utf8ByteLength as Id, PRE_DELETE_SNAPSHOT_TYPES as Ii, recordMaskOnlyValue as Il, replayRollback as In, findReplacedReadersOfRecreateTargets as Io, isWholeDynamicReferenceValue as Ir, malformedDriftResourcePropertiesWarning as Is, computeImplicitDeleteEdges as It, validateContainerRepoName as Iu, isTtlAlreadyDisabled as J, isIamRoleArn as Ja, passedNoEchoParametersOf as Jc, injectedAwsRegionValue as Jd, DBPROXY_TAG_OPTIONS as Ji, acceptedCreateOnlyDropsOf as Jl, reserveStackCreateToken as Jn, coerceCfnInteger as Jo, withStackRecords as Jr, refuseMalformedOrphansForDestroy as Js, formatResourceLine as Jt, partitionSensitiveEnv as Ju, streamPolicyMatchesDeclared as K, assertSendableRoleArn as Ka, noEchoLeavesOf as Kc, resolveAssemblyPath as Kd, stringifyIfAssigned as Ki, S3StateBackend as Kl, earliestDefined as Kn, toFiniteNumber as Ko, destroyStackRecordsView as Kr, malformedOrphansWarning as Ks, getPriorAttempts as Kt, dockerSpawnEnvWithSensitive as Ku, STREAM_POLICY_KEY as L, IntrinsicFunctionResolver as La, DagBuilder as Lc, defineOwnKey as Ld, ccRoutedFinalSnapshotError as Li, recordMaskOnlyValuesIn as Ll, recordAfterRollbackUpdate as Ln, shownType as Lo, noEchoParameterValueSeed as Lr, malformedResourcePropertiesWarning as Ls, keptForRetainedRecord as Lt, BOOTSTRAP_MARKER_PREFIX as Lu, PROTECTION_PROPERTY_BY_TYPE as M, reEnableInstanceApiTermination as Ma, ecsServiceLaunchTypeSetOrChanged as Mc, StageLoadError as Md, maskedSecretSegment as Mi, recordNestedStackParameterExpressions as Ml, mappingPairs as Mn, unsettledItemsOf as Mo, secretSafeKeyDisplay as Mr, refuseMalformedResourceEntriesForImportSave as Ms, enclosingDeadlineExpired as Mt, getBootstrapMarkerKey as Mu, isProtectionValueActive as N, onlySecretReferencesDiffer as Na, emrClusterInstancesReplaced as Nc, processStackMessages as Nd, secretSegmentsOfState as Ni, splitGetAttStringForm as Nl, parseMappingFile as Nn, unsettledPropertiesOf as No, carriedExportAliasExposure as Nr, refuseMalformedResourceEntriesForOrphan as Ns, enclosingDeadlineRemainingMs as Nt, parseBootstrapMarker as Nu, serviceTokenBlockingReason as O, ec2InstanceProtectionSite as Oa, NO_CC_HANDLERS_REASON as Oc, canonicalizeRegion as Od, stateSecretNameNeedles as Oi, recoverMaskedOutput as Ol, rollbackOrphanIds as On, withSharedDrainBudget as Oo, displayTextOrWithheld as Or, refuseMalformedResourceEntries as Os, ECR_AUTO_DELETE_IMAGES_TAG as Ot, ensureAssetStorage as Ou, perType as P, unchangedBehindSecretReference as Pa, canonicalLambdaFunctionName as Pc, describeJsonParseFailure as Pd, withSecretPhysicalIdsMaskedInState as Pi, carriesSecretMask as Pl, proposeRenames as Pn, withUnsettledProperties as Po, exportNameNoEchoParameters as Pr, repairMalformedResourceEntriesForReadOnly as Ps, withResourceDeadline as Pt, readBootstrapMarkerBody as Pu, sendTtlWaitingOutRateLimit as Q, callerEnvCredentials as Qa, valueAtCoordinate as Qc, tagMapAsList as Qi, importableOutputKeys as Ql, seedsDeleteFirstGuard as Qn, readConfigString as Qo, holdsSupersededResources as Qr, malformedLocalOutputsWarning as Qs, displacedOpClause as Qt, formatDockerLoginError as Qu, STREAM_TAGS_KEY as R, isAlwaysLiveAttribute as Ra, TemplateParser as Rc, hasOwnKey as Rd, ccRoutedInstanceTakesNoSnapshot as Ri, recordNoEchoAttributeValues as Rl, settleUnsettledPrevious as Rn, MULTI_REGION_RECREATE_BLOCKED_TYPES as Ro, collectDeclaredOutputNames as Rr, refuseMalformedResourcePropertiesForDestroy as Rs, recordRetainedForReadoption as Rt, buildDockerImage as Ru, hasPendingMovesOut as S, UNSPECIFIED_SKIP_REASON as Sa, hasReadableResources as Sc, findLargeInlineResources as Sd, namingSecretsWithRecordedNoEcho as Si, dynamicReferenceTokens as Sl, constructPathOf as Sn, getAccountInfo as So, inheritProducerRegions as Sr, isReadableResourceEntry as Ss, INDEX_SETTLE_POLL_INTERVAL_MS as St, WorkGraph as Su, refusePendingMovesOut as T, deleteSkipReason as Ta, findSdkUnwiredProperties as Tc, decodeListingKey as Td, secretNamePrintingBags as Ti, pathCrossesDottedKey as Tl, findRefactorHints as Tn, isNamelessDynamicReferenceError as To, reachableDivergentParameters as Tr, malformedResourceEntriesWarning as Ts, maskedLogger as Tt, loadPublishableAssetManifest as Tu, streamDeclaresPolicy as U, refuseUnreadableCdkCrossAccountRefs as Ua, maskWholeValue as Uc, describeFileReadFailure as Ud, createPreDeleteFinalSnapshot as Ui, isSingleDynamicReferenceToken as Ul, undeclaredEmptyObservedKeys as Un, coerceWarmThroughput as Uo, DEFAULT_RESOURCE_WARN_AFTER_MS as Ur, UNREADABLE_ORPHANS_CONTAINER_ROW as Us, refuseRefactorMarker as Ut, redactedCause as Uu, planStreamMemberOps as V, resolveDynamicReferences as Va, maskAtCoordinates as Vc, ownValue as Vd, refusesFinalSnapshot as Vi, wholeStringLeavesOf as Vl, equalModuloMarkedMask as Vn, renderStatefulReason as Vo, bindingSkippedOutputs as Vr, refuseMalformedResourcePropertiesForOrphan as Vs, refactorMarkerMovesOf as Vt, describeDockerExecFailure as Vu, streamDeclaresTags as W, applyRoleArnIfSet as Wa, maskedLeafCoordinatesOf as Wc, displayAssemblyPath as Wd, buildFinalSnapshotIdentifier as Wi, LockManager as Wl, updatePartialMessage as Wn, isWarmThroughputDecrease as Wo, maskingRetryLogger as Wr, hasReadableOrphans as Ws, sameMove as Wt, redactedDockerCause as Wu, planTimeToLive as X, AWS_CREDENTIAL_ENV_KEYS as Xa, readsNoEchoSource as Xc, resolveBucketRegion as Xd, readTagList as Xi, exportNamesCarriedFrom as Xl, acquireIdempotencyToken as Xn, configIntegerRefusal as Xo, addSuperseded as Xr, malformedExportNamesWarning as Xs, resolvePendingCloudControlRequests as Xt, isDockerClientEnvKey as Xu, isTtlRateLimited as Y, sendableAssumeRoleCommand as Ya, readbackPathFor as Yc, clearBucketRegionCache as Yd, planTagDiff as Yi, describeRegionValueKind as Yl, withCreateTokenLedger as Yn, configBooleanRefusal as Yo, replacedDeleteFailureVerdict as Yr, repairMalformedOrphansForReadOnly as Ys, pendingRequestCount as Yt, warnFinchArgvExposure as Yu, readTtlSpec as Z, applyCallerIdentityCredentials as Za, recordedNoEchoValuesOf as Zc, refuseMalformedDesiredTags as Zi, hasReadableExportSet as Zl, planRollback as Zn, configStringRefusal as Zo, deleteSupersededEntry as Zr, malformedExportSourceWarning as Zs, NESTED_PENDING_PARENT_REASON as Zt, isMalformedEnvKey as Zu, findNestedTemplateTreeDefect as _, waitForGoneAfterDelete as _a, withheldAccountClause as _c, warnDeprecatedNoPrefixCliFlag as _d, withAttemptedItemsMasked as _i, maskSecretsInText as _l, makeForeignHolderScan as _n, parseWebACLArn as _o, retiredAfterRollback as _r, refuseMalformedOrphanRecordsForDestroy as _s, compensateRemovedDeletionProtection as _t, stackInstanceIdOf as _u, withApiLimit as a, isCustomResource as aa, STATE_REGION_DIVERGED as ac, synthesisStatusMessage as ad, withoutSuperseded as ai, createUnionSecretMasker as al, revertedNestedRowIds as an, s3BucketDomainName as ao, replacementNeverSwapped as ar, describeTypeWithThrottleRetry as as, contributorInsightsRefusals as at, hasReasonlessBaselineRefusal as au, renderNestedTemplateTreeDefect as b, slowCcOperationTimeoutMs as ba, displayLogicalId as bc, CFN_TEMPLATE_URL_LIMIT as bd, journaledOrphanPrintingBag as bi, withoutPhysicalNameCopies as bl, DeploymentEventsReader as bn, recordedOutputReferenceRegions as bo, withNameGenerationReached as br, unpreviewableOrphanRecords as bs, resolveDynamoDbDeleteBudgetMs as bt, isSensitiveAttributeName as bu, mergeNoChangeOutputs as c, applyCustomResourceResponseExpiration as ca, malformedResourcesWarning as cc, loadCdkJson as cd, cyan as ci, logOnlyValueCount as cl, getCurrentNestedStackContext as cn, s3BucketWebsiteUrl as co, REDACTED_DELETE_ADDRESS_SKIP_REASON as cr, passedParameterClassesOf as cs, planIndexContributorInsightsOps as ct, renderPhaseTimings as cu, makeCanonicalizePropertiesFn as d, readsNoEchoDeleteValues as da, refuseMalformedResourcesForDestroy as dc, resolveCaptureObservedState as dd, red as di, recordLogOnlyValue as dl, dropFailedCommands as dn, parameterTypeMayLoseSecretIdentity as do, redactedDeleteAddressSkip as dr, isReadableOrphanRecord as ds, reverseMapTableContributorInsights as dt, CrossPrefixReadError as du, isRefusedByName as ea, malformedOutputsWarning as ec, runDockerForeground as ed, removeSuperseded as ei, markSameGenerationBag as el, dropSettledNestedJournals as en, classifyRecordedSecretRegion as eo, isJournaledOrphan as er, requireConfigArray as es, readbackVectorIndexes as et, isReadableBag as eu, conditionFingerprint as f, isCustomResourceType as fa, refuseMalformedResourcesForExport as fc, resolveSkipPrefix as fd, yellow as fi, shareLogOnlyValues as fl, dropFailedHint as fn, AWS_NO_VALUE as fo, removeProtectionTypeList as fr, malformedOrphanRecordsRefusalMessage as fs, stripIndexContributorInsights as ft, CrossPrefixScanCache as fu, childTemplateLoader as g, CloudControlProvider as ga, accountArgs as gc, stateBucketExistenceConfirmed as gd, noEchoParameterNamesOf as gi, maskSecretsInError as gl, sameJournaledOrphans as gn, refStateLookupFromResource as go, nameScopeOf as gr, refuseMalformedOrphanRecords as gs, beginDeleteWait as gt, isNotImplemented as gu, readRecordedConditionVerdicts as h, waitForLambdaFunctionActive as ha, JSON_LISTING_HOLE_VALUE as hc, resolveUseCdkBootstrapAssets as hd, noEchoExactEchoLeavesOf as hi, errorCauseChain as hl, loadJournaledOrphans as hn, lacksRecordedTableArn as ho, nameGenerationHighWaterOf as hr, previewableOrphanRecords as hs, DYNAMODB_DELETE_POLL_COST_MS as ht, isAccessDenied$1 as hu, lookupEachName as i, ccBrokenReason as ia, repairMalformedOutputsForReadOnly as ic, Synthesizer as id, supersededResourcesOf as ii, carryLogOnlyValues as il, revertNestedChildFromJournal as in, s3BucketArn as io, recordUnderIdIsNotOwn as ir, templateResourceTypes as is, CONTRIBUTOR_INSIGHTS_KEY as it, stackInstanceIdCarriedFrom as iu, recordedProtectionNote as j, reDisableInstanceApiTermination as ja, dbInstanceEngineChangeIsInPlace as jc, AssemblyReader as jd, APPSYNC_APIKEY_ARN_RESOURCE_PATH as ji, recordPhysicalNameCopy as jl, looselyEqual as jn, unsettledItemsField as jo, secretBearingStateKeyWarning as jr, refuseMalformedResourceEntriesForImport as js, isTruthyCfnBoolean as jt, isCrossRegionRedirect as ju, diffSecurity as k, isTerminationProtectionPropagationError as ka, hasNoCloudControlHandlers as kc, derivePartitionAndUrlSuffix as kd, storedSecretNameNeedles as ki, physicalNameCopiesOf as kl, withMovedTo as kn, INTRINSIC_KEYS as ko, exportAliasCollisionScrubWarning as kr, refuseMalformedResourceEntriesForDeploy as ks, S3_AUTO_DELETE_OBJECTS_TAG as kt, buildDenyExternalAccessPolicy as ku, crossStackOutputProvenanceSource as l, customResourceResponseExpirationWarning as la, malformedStateRefusalMessage as lc, resolveApp as ld, gray as li, printingCorpusOf as ll, withNestedStackContext as ln, coerceParameterTypedValue as lo, isRedactedRecordedValue as lr, declaresNoEcho as ls, readContributorInsightsSpec as lt, timePhase as lu, parentSuppliedValues as m, withPrintingSecrets as ma, repairMalformedResourcesForReadOnly as mc, resolveStateBucketWithDefaultAndSource as md, noEchoComparisonForTemplate as mi, createSecretMasker as ml, journaledOrphanLines as mn, isStalePlaceholderArnAttribute as mo, nameGenerationCarriedFrom as mr, malformedOrphanRowsKeptWarning as ms, DYNAMODB_DELETE_MIN_RESOURCE_TIMEOUT_MS as mt, crossPrefixDeniedWarning as mu, chunks as n, CC_BROKEN_REASON as na, refuseMalformedOutputs as nc, AssetManifestLoader as nd, supersededHeldByOtherTypeWarning as ni, recordReferenceProvenanceEntry as nl, nestedChildStackName as nn, producerRegionsFromState as no, planFailedOps as nr, requireConfigString as ns, vectorIndexesSettled as nt, orphansCarriedFrom as nu, isSecretBearingReferenceString as o, wouldReturnToSdkProvider as oa, refuseDivergentRecordRegionForDestroy as oc, getDefaultStateBucketName as od, refuseRestoreFromItself as oi, hasMaskableValues as ol, withNestedRevertRun as on, s3BucketDualStackDomainName as oo, resolveReplacementOldType as or, withRetry as os, indexDeclaresContributorInsights as ot, hasUnverifiableParameterRefusal as ou, conditionInputsFrom as p, getCurrentResourceSecrets as pa, refuseMalformedState as pc, resolveStateBucketWithDefault as pd, noEchoAttributeNamesOf as pi, unionOfSecretBags as pl, isHandledOrphan as pn, cfnRefValueFromPhysicalId as po, orphanNeedsIdentity as pr, malformedOrphanRecordsWarning as ps, DYNAMODB_DELETE_DEADLINE_MARGIN_MS as pt, applyCrossPrefixScan as pu, streamTagsMatchDeclared as q, explicitRoleArnOrThrow as qa, noEchoOutputsComparison as qc, injectAwsRegion as qd, DBPROXY_TAGS_WHAT as qi, splitImportedOps as ql, ledgerForStack as qn, coerceCfnBoolean as qo, getStackRecords as qr, refuseMalformedOrphans as qs, markRefusedBeforeApplying as qt, finchSecretArgvRefusal as qu, isAccessDeniedError as r, ProviderRegistry as ra, refuseMalformedOutputsForDestroy as rc, getDockerImageBySourceHash as rd, supersededHolderOf as ri, snapshotPassProvenance as rl, recordDisplacedSkips as rn, regionLessSecretName as ro, recheckFailedPlan as rr, prefetchCreateOnlyPropertyPaths as rs, vectorIndexesShapeDetail as rt, shouldRetainResource as ru, keptWholeReasonText as s, CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID as sa, malformedRenderedContainersWarning as sc, getLegacyStateBucketName as sd, bold as si, literalSplitDelimitersOf as sl, collectNestedChildUnaddressed as sn, s3BucketRegionalDomainName as so, findNestedStackTypeChanges as sr, parameterInputsFor as ss, planContributorInsightsOp as st, PhaseClock as su, DeployEngine as t, markDeleteStarted as ta, refuseMalformedNestedChildOutputs as tc, runDockerStreaming as td, supersededAfterRollback as ti, redactForState as tl, getNestedRevertRun as tn, classifyReplaySecretRegion as to, isReplacementOrphan as tr, requireConfigObject as ts, vectorIndexesForCreate as tt, orphansAfterRollback as tu, inheritedProvenanceForChildDiff as u, TemplateNoEchoReresolver as ua, refuseMalformedResourcesForDeploy as uc, resolveAutoAssetStorage as ud, green as ui, recordLogOnlyParameterValue as ul, deleteJournaledOrphans as un, isUnboundTemplateParameter as uo, redactedDeleteAddressFields as ur, deployRefusesOrphanRowsReason as us, reverseMapIndexContributorInsights as ut, rebuildClientForBucketRegion as uu, isAbsoluteAssetPath as v, resolvedResourceTimeoutMs as va, STATE_RESOURCES_MALFORMED as vc, ssmResolvedValueType as vd, createReadOnlyAttributeHealerFactory as vi, scrubResourceRecord as vl, makeSiblingClaimReader as vn, keepHeldTokenProvenance as vo, retiredNameGenerationsAfter as vr, refuseMalformedOrphansForOrphan as vs, deleteBudgetKey as vt, withStackInstanceIdWithheld as vu, pendingMovesRefusalMessage as w, deleteLeftInPlace as wa, findHandledUnwrittenCreateOnly as wc, CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION as wd, secretNamePrintingBag as wi, spelledKeysOf as wl, formatDestructiveChange as wn, carriesFetchableDynamicReference as wo, namesAnyDeclaredParameter as wr, malformedLocalResourcesWarning as ws, deleteTableWithIndexBusyRetry as wt, createAssetRedirectResolver as wu, templateIdentity as x, RollbackInlinePolicyWriters as xa, hasReadableOutputs as xc, MIGRATE_TMP_PREFIX as xd, maskEventTextWithBoundBags as xi, DYNAMIC_REFERENCE_TOKEN_SCAN as xl, DeploymentEventsStore as xn, recordedReferenceRegions as xo, getCurrentProducerRegions as xr, unreadableOrphanRecords as xs, DELETE_INDEX_WAIT_PROCEED_NOTE as xt, stringifyValue as xu, listNestedTemplateRows as y, setResolvedResourceTimeouts as ya, UNREADABLE_RESOURCES_MAP_ROW as yc, CFN_TEMPLATE_BODY_LIMIT as yd, completedReplayEntries as yi, withPhysicalNameCopies as yl, planOrphanAdoption as yn, outputReferenceProvenanceOf as yo, retiredNameGenerationsLeaving as yr, repairMalformedOrphanRecordsForReadOnly as ys, resolveDynamoDbDeleteBudgetClock as yt, AssetPublisher as yu, declaredStreamPolicyMember as z, poisonRenderedSpellingsCollidingIn as za, canonicalCoordinates as zc, hasPlainPrototype$1 as zd, effectiveDeletionPolicy as zi, recordNoEchoParameterFreshValue as zl, withUnprovenUnsettled as zn, isStatefulRecreateTargetForReplace as zo, collectPublishedOutputNames as zr, refuseMalformedResourcePropertiesForDrift as zs, readRefactorMarker as zt, resolveDockerContextDirectory as zu };
58395
+ //# sourceMappingURL=deploy-engine-iQpILlcZ.js.map