@go-to-k/cdkd 0.296.20 → 0.296.22

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.
@@ -2,12 +2,12 @@ import { r as getAwsClients } from "./aws-clients-CnmtbrxD.js";
2
2
  import { F as displayStackName, I as isPasteableIdent, N as displayIdent, O as SECRET_REF_MAX_CODE_POINTS, P as displaySafe, R as plainIdentOr, a as getLogger, b as generateResourceNameWithFallback, n as isAwsAuthoredFailure, r as safeStringify, t as describeAwsFailure, y as generateResourceName, z as safeMsg } from "./aws-failure-text-BaWeCWRz.js";
3
3
  import { $ as protectedReplacementAdvice, $t as AccountIdUnavailableError, A as isQuotableImportValue, An as commandHole, B as isTerminalDeleteFailure, C as setBounded, D as VALUE_NOT_SHOWN, E as assertRegionMatch, F as resolveExplicitPhysicalId, Fn as plainOrDescribed, H as observeThenDisableProtection, Jn as markNameCollision, Jt as withPasteableAwsProfile, L as ProtectionFlipRegistry, M as quotedRemedyLogicalId, Mn as isInertUnquoted, Mt as markCreatedBeforeFailure, N as refusalTypeShown, Nn as pasteableCommand, O as isPlainImportJson, P as remedyLogicalId, Q as pasteableAwsCommand, Qn as isAmbiguousOutcomeError, Qt as credentialFingerprint, Rn as shellQuote, S as replayedSendWindow, St as withDerivedNameMasks, T as RESOURCE_NOT_FOUND, Tt as clearCreatedBeforeFailure, U as protectionFlipKey, Ut as injectiveKey, V as logGroupProtectionSite, W as rdsFamilyProtectionSite, Wt as injectiveKeyPrefix, X as WITHHELD_AWS_COMMAND, Xt as ambientCredentialConfig, Y as UNNAMEABLE_ID_CLAUSE, Yn as markReplayMayCollide, Yt as ambientClientDefaults, Z as isAwsCliLiteral, Zt as clientDefaultsFor, _ as RecentIdSet, _n as ResourceUpdateNotSupportedError, _t as createMaskedLogSinks, a as onlySecretDerived, ar as isThrottlingError, at as startInterruptWatch, b as isInsideWindow, bt as maskDeep, c as recordedPrincipalsRepair, cr as wrapMaskedAwsError, ct as canonicalizeRoute53QueryName, dt as compositeIdSkipResult, er as isRetryableTransientError, et as renderDisableCommand, ft as logicalIdShown, g as AmbiguousCreateLatch, gt as stateOrphanRecordRemedy, h as AMBIGUOUS_LATCH_TTL_MS, hn as ProvisioningError, ht as segmentAfterAnchor, i as holdsSecretDerivedEntry, ir as isMarkedNonRetryable, it as isInterruptedWaitError, j as normalizeAwsTagsToCfn, jn as hasClauseBreak, jt as markAuxiliaryFailure, k as isPlainImportValue, lt as compositeIdFormatMessage, o as readPrincipalLists, or as markNonRetryable, ot as ElapsedBudgetRegistry, p as withRemovalDefaults, pt as packCompositeId, q as userPoolProtectionSite, r as SECRET_DERIVED_READ_LIVE, rr as THROTTLING_ERROR_NAMES, sr as markRedactedCause, tn as CdkdError, tr as isTransientServerError, u as clearOnUpdateRemoval, ut as compositeIdSeparatorRefusal, v as ambiguousAttemptLead, vt as createMaskedRetryLogger, w as withoutServerErrorRetries, x as replayFollowedAmbiguousAttempt, xt as maskerOrIdentity, y as createAttemptKey, yt as isSecretDerivedValue, z as deleteWithProtectionCompensation, zn as withheldTargetClause } from "./iam-policy-targets-BoZuWtxK.js";
4
4
  import { s as ambientRegion } from "./aws-client-defaults-D0q0z4dG.js";
5
- import { A as beginDeleteWait, B as S3_AUTO_DELETE_OBJECTS_TAG, Ba as configStringRefusal, Bi as refuseMalformedNestedChildOutputs, Bn as DBPROXY_TAGS_WHAT, Br as s3BucketDualStackDomainName, Co as markSameGenerationBag, Do as dynamicReferenceTokens, Et as awaitInFlightSibling, F as DELETE_INDEX_WAIT_PROCEED_NOTE, Fa as toFiniteNumber, Fn as earliestDefined, Ga as requireConfigString, Gn as tagMapAsList, Gt as redactedDeleteAddressFields, H as isTruthyCfnBoolean, Ha as replayWarn, Hn as planTagDiff, Hr as s3BucketWebsiteUrl, I as INDEX_SETTLE_POLL_INTERVAL_MS, Ia as coerceCfnBoolean, Jn as stringifyIfAssigned, Kn as tagPlanWarning, Kr as getAccountInfo, Kt as redactedDeleteAddressSkip, L as deleteTableWithIndexBusyRetry, La as coerceCfnInteger, Ln as reserveStackCreateToken, Lr as isSettledInstanceState, M as deleteBudgetKey, Ma as coerceWarmThroughput$1, Mc as displayAssemblyPath, N as resolveDynamoDbDeleteBudgetClock, Na as isWarmThroughputDecrease, Nc as renderAssemblyPathEscape, No as recoverMaskedOutput, O as DynamoDBGlobalTableProvider, Ot as getStackRecords, P as resolveDynamoDbDeleteBudgetMs, Pa as toCfnInteger, Pc as resolveAssemblyPath, Po as carriesSecretMask, Qa as sameLambdaFunctionAddress, R as waitForIndexesSettled, Ra as configBooleanRefusal, Rr as s3BucketArn, Sa as withoutSilentDropProperties, U as getPriorAttempts, Ua as requireConfigArray, Un as readTagList, Ut as REDACTED_DELETE_ADDRESS_SKIP_REASON, V as hasCdkAutoDeleteTag, Va as readConfigString, Vn as DBPROXY_TAG_OPTIONS, Vr as s3BucketRegionalDomainName, Vt as getCurrentProducerRegions, W as markRefusedBeforeApplying, Wa as requireConfigObject, Wn as refuseMalformedDesiredTags, Wt as isRedactedRecordedValue, Xa as canonicalLambdaFunctionName, Ya as withRetry, Za as lambdaFunctionNameForMask, _c as decodeListingKey, _r as observeThenDisableInstanceApiTermination, _s as rewriteTemplateAssetReferences, a as findNestedTemplateTreeDefect, ai as passedParameterClassesOf, ba as findSilentDropProperties, bc as canonicalizeRegion, c as renderNestedTemplateTreeDefect, di as accountArgs, dr as withIndeterminateGuard, fo as hasMaskableValues, fr as isWaitAbandonedError, fs as stringifyValue, ft as revertNestedChildFromJournal, gr as isTerminationProtectionPropagationError, gt as withNestedStackContext, hr as ec2InstanceProtectionSite, ht as getCurrentNestedStackContext, j as compensateRemovedDeletionProtection, ja as WARM_THROUGHPUT_MEMBERS, jc as describeFileReadFailure, k as DYNAMODB_DELETE_MIN_RESOURCE_TIMEOUT_MS, lt as getNestedRevertRun, ni as parseWebACLArn, o as isAbsoluteAssetPath, oa as refuseMalformedResourcesForDestroy, or as slowCcOperationTimeoutMs, pr as markWaitAbandoned, qn as definedAttributes, rr as getCurrentResourceSecrets, s as listNestedTemplateRows, so as passedNoEchoParametersOf, sr as unchangedBehindSecretReference, t as DeployEngine, ur as deleteSkipReason, va as withheldAccountClause, vr as reDisableInstanceApiTermination, wo as redactSecretsForState, xc as derivePartitionAndUrlSuffix, yr as reEnableInstanceApiTermination, z as ECR_AUTO_DELETE_IMAGES_TAG, za as configIntegerRefusal, zn as acquireIdempotencyToken, zr as s3BucketDomainName } from "./deploy-engine-Bf4lSjKH.js";
6
- import { n as collectInlinePolicyNamesManagedBySiblings, r as IamCreateClientCache, t as IAMRoleProvider } from "./iam-role-provider-9GziixCH.js";
7
- import { a as canonicalizeIpProtocolValue, i as resolveSecretDerivedPrincipals, n as runDestroyForStack, o as resolvedResourceTimeoutMs, r as isResolvableSecretPrincipalList, t as canonicalizeIpv4Cidr } from "./program-DmQ1kq4a.js";
8
- import { RDSProvider } from "./rds-provider-CE-DoYJ6.js";
9
- import { NeptuneProvider } from "./neptune-provider-Hl0cy_mD.js";
10
- import { ASGProvider } from "./asg-provider-D3XKsjzK.js";
5
+ import { $a as lambdaFunctionNameForMask, A as beginDeleteWait, B as S3_AUTO_DELETE_OBJECTS_TAG, Ba as configBooleanRefusal, Br as s3BucketArn, Cc as derivePartitionAndUrlSuffix, Eo as redactSecretsForState, Et as awaitInFlightSibling, F as DELETE_INDEX_WAIT_PROCEED_NOTE, Fa as isWarmThroughputDecrease, Fc as renderAssemblyPathEscape, Fo as recoverMaskedOutput, Ga as requireConfigArray, Gn as readTagList, Gt as REDACTED_DELETE_ADDRESS_SKIP_REASON, H as isTruthyCfnBoolean, Ha as configStringRefusal, Hi as refuseMalformedNestedChildOutputs, Hn as DBPROXY_TAGS_WHAT, Hr as s3BucketDualStackDomainName, I as INDEX_SETTLE_POLL_INTERVAL_MS, Ia as toCfnInteger, Ic as resolveAssemblyPath, Io as carriesSecretMask, Jn as tagPlanWarning, Jr as getAccountInfo, Jt as redactedDeleteAddressSkip, Ka as requireConfigObject, Kn as refuseMalformedDesiredTags, Kt as isRedactedRecordedValue, L as deleteTableWithIndexBusyRetry, La as toFiniteNumber, Ln as earliestDefined, M as deleteBudgetKey, N as resolveDynamoDbDeleteBudgetClock, Na as WARM_THROUGHPUT_MEMBERS, Nc as describeFileReadFailure, O as DynamoDBGlobalTableProvider, Ot as getStackRecords, P as resolveDynamoDbDeleteBudgetMs, Pa as coerceWarmThroughput$1, Pc as displayAssemblyPath, Qa as canonicalLambdaFunctionName, R as waitForIndexesSettled, Ra as coerceCfnBoolean, Sa as findSilentDropProperties, Sc as canonicalizeRegion, To as markSameGenerationBag, U as getPriorAttempts, Ua as readConfigString, Un as DBPROXY_TAG_OPTIONS, Ur as s3BucketRegionalDomainName, Ut as getCurrentProducerRegions, V as hasCdkAutoDeleteTag, Va as configIntegerRefusal, Vn as acquireIdempotencyToken, Vr as s3BucketDomainName, W as markRefusedBeforeApplying, Wa as replayWarn, Wn as planTagDiff, Wr as s3BucketWebsiteUrl, Xn as stringifyIfAssigned, Yn as definedAttributes, Za as withRetry, _r as ec2InstanceProtectionSite, a as findNestedTemplateTreeDefect, ar as getCurrentResourceSecrets, ba as withheldAccountClause, br as reDisableInstanceApiTermination, c as renderNestedTemplateTreeDefect, ca as refuseMalformedResourcesForDestroy, cr as slowCcOperationTimeoutMs, eo as sameLambdaFunctionAddress, fr as deleteSkipReason, ft as revertNestedChildFromJournal, gt as withNestedStackContext, hr as markWaitAbandoned, ht as getCurrentNestedStackContext, ii as parseWebACLArn, j as compensateRemovedDeletionProtection, k as DYNAMODB_DELETE_MIN_RESOURCE_TIMEOUT_MS, ko as dynamicReferenceTokens, lo as passedNoEchoParametersOf, lr as unchangedBehindSecretReference, lt as getNestedRevertRun, mo as hasMaskableValues, mr as isWaitAbandonedError, ms as stringifyValue, o as isAbsoluteAssetPath, pi as accountArgs, pr as withIndeterminateGuard, qa as requireConfigString, qn as tagMapAsList, qt as redactedDeleteAddressFields, s as listNestedTemplateRows, si as passedParameterClassesOf, t as DeployEngine, vr as isTerminationProtectionPropagationError, wa as withoutSilentDropProperties, xr as reEnableInstanceApiTermination, yc as decodeListingKey, yr as observeThenDisableInstanceApiTermination, ys as rewriteTemplateAssetReferences, z as ECR_AUTO_DELETE_IMAGES_TAG, za as coerceCfnInteger, zn as reserveStackCreateToken, zr as isSettledInstanceState } from "./deploy-engine-BueFQdfN.js";
6
+ import { n as collectInlinePolicyNamesManagedBySiblings, r as IamCreateClientCache, t as IAMRoleProvider } from "./iam-role-provider-CGY8o8Pv.js";
7
+ import { a as canonicalizeIpProtocolValue, i as resolveSecretDerivedPrincipals, n as runDestroyForStack, o as resolvedResourceTimeoutMs, r as isResolvableSecretPrincipalList, t as canonicalizeIpv4Cidr } from "./program-B6NoMGdN.js";
8
+ import { RDSProvider } from "./rds-provider-Cc9l4-JW.js";
9
+ import { NeptuneProvider } from "./neptune-provider-7hDILb3t.js";
10
+ import { ASGProvider } from "./asg-provider-BYk2trWp.js";
11
11
  import { createHash, randomUUID } from "node:crypto";
12
12
  import { CreateBucketCommand, DeleteBucketAnalyticsConfigurationCommand, DeleteBucketCommand, DeleteBucketCorsCommand, DeleteBucketEncryptionCommand, DeleteBucketIntelligentTieringConfigurationCommand, DeleteBucketInventoryConfigurationCommand, DeleteBucketLifecycleCommand, DeleteBucketMetricsConfigurationCommand, DeleteBucketOwnershipControlsCommand, DeleteBucketPolicyCommand, DeleteBucketReplicationCommand, DeleteBucketTaggingCommand, DeleteBucketWebsiteCommand, DeleteObjectsCommand, GetBucketAccelerateConfigurationCommand, GetBucketCorsCommand, GetBucketEncryptionCommand, GetBucketLifecycleConfigurationCommand, GetBucketLocationCommand, GetBucketLoggingCommand, GetBucketNotificationConfigurationCommand, GetBucketOwnershipControlsCommand, GetBucketPolicyCommand, GetBucketReplicationCommand, GetBucketTaggingCommand, GetBucketVersioningCommand, GetBucketWebsiteCommand, GetObjectCommand, GetObjectLockConfigurationCommand, GetPublicAccessBlockCommand, HeadBucketCommand, ListBucketAnalyticsConfigurationsCommand, ListBucketIntelligentTieringConfigurationsCommand, ListBucketInventoryConfigurationsCommand, ListBucketMetricsConfigurationsCommand, ListBucketsCommand, ListObjectVersionsCommand, ListObjectsV2Command, NoSuchBucket, PutBucketAccelerateConfigurationCommand, PutBucketAnalyticsConfigurationCommand, PutBucketCorsCommand, PutBucketEncryptionCommand, PutBucketIntelligentTieringConfigurationCommand, PutBucketInventoryConfigurationCommand, PutBucketLifecycleConfigurationCommand, PutBucketLoggingCommand, PutBucketMetricsConfigurationCommand, PutBucketNotificationConfigurationCommand, PutBucketOwnershipControlsCommand, PutBucketPolicyCommand, PutBucketReplicationCommand, PutBucketTaggingCommand, PutBucketVersioningCommand, PutBucketWebsiteCommand, PutObjectLockConfigurationCommand, PutPublicAccessBlockCommand, S3Client } from "@aws-sdk/client-s3";
13
13
  import { AddRoleToInstanceProfileCommand, AddUserToGroupCommand, AttachGroupPolicyCommand, AttachRolePolicyCommand, AttachUserPolicyCommand, CreateAccessKeyCommand, CreateGroupCommand, CreateInstanceProfileCommand, CreateLoginProfileCommand, CreatePolicyCommand, CreatePolicyVersionCommand, CreateUserCommand, DeleteAccessKeyCommand, DeleteGroupCommand, DeleteGroupPolicyCommand, DeleteInstanceProfileCommand, DeleteLoginProfileCommand, DeletePolicyCommand, DeletePolicyVersionCommand, DeleteRolePolicyCommand, DeleteUserCommand, DeleteUserPermissionsBoundaryCommand, DeleteUserPolicyCommand, DetachGroupPolicyCommand, DetachRolePolicyCommand, DetachUserPolicyCommand, GetAccessKeyLastUsedCommand, GetGroupCommand, GetGroupPolicyCommand, GetInstanceProfileCommand, GetPolicyCommand, GetPolicyVersionCommand, GetRolePolicyCommand, GetUserCommand, GetUserPolicyCommand, IAMClient, ListAccessKeysCommand, ListAttachedGroupPoliciesCommand, ListAttachedUserPoliciesCommand, ListEntitiesForPolicyCommand, ListGroupPoliciesCommand, ListGroupsForUserCommand, ListPoliciesCommand, ListPolicyTagsCommand, ListPolicyVersionsCommand, ListUserPoliciesCommand, NoSuchEntityException, PutGroupPolicyCommand, PutRolePolicyCommand, PutUserPermissionsBoundaryCommand, PutUserPolicyCommand, RemoveRoleFromInstanceProfileCommand, RemoveUserFromGroupCommand, TagPolicyCommand, TagUserCommand, UntagPolicyCommand, UntagUserCommand, UpdateAccessKeyCommand, UpdateLoginProfileCommand } from "@aws-sdk/client-iam";
@@ -3031,6 +3031,16 @@ function bucketLocationToRegion(constraint) {
3031
3031
  if (value === "eu") return "eu-west-1";
3032
3032
  return value;
3033
3033
  }
3034
+ const FAILED_CREATE_ORPHAN_NOT_EMPTY_SKIP_REASON = "the bucket a failed create left behind is not empty, and cdkd never empties such a bucket: something wrote to it after that create, so it may hold data or have been adopted by another deployment. Empty and delete it yourself if it is not in use";
3035
+ var BucketNotEmptyRefusal = class extends Error {
3036
+ name = "BucketNotEmptyRefusal";
3037
+ };
3038
+ function isPlainBucketName(value) {
3039
+ return typeof value === "string" && /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(value);
3040
+ }
3041
+ const BUCKET_LIST_IDENTITY_ATTEMPTS = 3;
3042
+ const BUCKET_LIST_IDENTITY_DELAY_MS = 1500;
3043
+ const BUCKET_LIST_IDENTITY_BUDGET_MS = 6e3;
3034
3044
  function isNoSuchBucketError(error) {
3035
3045
  return error?.name === "NoSuchBucket";
3036
3046
  }
@@ -3079,6 +3089,23 @@ function holdCreateBucketWindow(logicalId, window) {
3079
3089
  heldAtMs: Date.now()
3080
3090
  });
3081
3091
  }
3092
+ const ownLeftoverBuckets = /* @__PURE__ */ new Map();
3093
+ function holdOwnLeftoverBucket(logicalId, identity) {
3094
+ setBounded(ownLeftoverBuckets, createAttemptKey("CreateBucket", logicalId), {
3095
+ identity,
3096
+ heldAtMs: Date.now()
3097
+ });
3098
+ }
3099
+ const OWN_LEFTOVER_IDENTITY_TIMEOUT_MS = 1e4;
3100
+ function tokenDate(token) {
3101
+ return token.slice(token.lastIndexOf("|") + 1);
3102
+ }
3103
+ function takeOwnLeftoverBucket(logicalId) {
3104
+ const key = createAttemptKey("CreateBucket", logicalId);
3105
+ const held = ownLeftoverBuckets.get(key);
3106
+ ownLeftoverBuckets.delete(key);
3107
+ return held !== void 0 && Date.now() - held.heldAtMs <= 18e5 ? held.identity : void 0;
3108
+ }
3082
3109
  var S3BucketProvider = class S3BucketProvider {
3083
3110
  s3Client;
3084
3111
  createClientHolder = {};
@@ -3137,6 +3164,44 @@ var S3BucketProvider = class S3BucketProvider {
3137
3164
  throw markNameCollision(new ProvisioningError(`Refusing to adopt S3 bucket ${this.shown(bucketName)} for ${displaySafe(logicalId)} (${resourceType}): its BucketName is set explicitly and ${evidence}. S3 does not say who made it, so cdkd cannot tell it from one made outside this stack, and CloudFormation fails the same create. Nothing was applied to it. Choose a bucket name no other bucket holds. If no record of this stack holds that bucket and it is yours (left by an interrupted deploy, or kept by DeletionPolicy: Retain), delete it, or adopt it with \`cdkd import\`, and re-run; confirm it is yours first, since adopting a bucket hands it to this stack's \`cdkd destroy\`.`, resourceType, logicalId, bucketName, "cause" in via ? via.cause : void 0));
3138
3165
  }
3139
3166
  async ownsBucketNamed(bucketName) {
3167
+ const listed = await this.listOwnedBucket(bucketName);
3168
+ return "unknown" in listed ? listed : { owned: listed.bucket !== void 0 };
3169
+ }
3170
+ async boundedIdentity(bucketName, resourceType, region) {
3171
+ let timer;
3172
+ try {
3173
+ return await Promise.race([this.resourceIdentity(bucketName, resourceType, { expectedRegion: region }), new Promise((resolve) => {
3174
+ timer = setTimeout(() => resolve(void 0), OWN_LEFTOVER_IDENTITY_TIMEOUT_MS);
3175
+ })]);
3176
+ } finally {
3177
+ clearTimeout(timer);
3178
+ }
3179
+ }
3180
+ async holdOwnLeftover(logicalId, resourceType, bucketName) {
3181
+ try {
3182
+ const region = canonicalizeRegion(await this.getRegion());
3183
+ const identity = await this.boundedIdentity(bucketName, resourceType, region);
3184
+ if (typeof identity === "string") {
3185
+ holdOwnLeftoverBucket(logicalId, identity);
3186
+ this.logger.debug(safeMsg`Recorded the bucket ${this.shown(bucketName)} this failed create of ${displaySafe(logicalId)} leaves (created ${tokenDate(identity)}), for its retry`);
3187
+ } else this.logger.debug(safeMsg`No identity for the bucket ${this.shown(bucketName)} this failed create of ${displaySafe(logicalId)} leaves; a retry will refuse it`);
3188
+ } catch {}
3189
+ }
3190
+ async isOwnLeftoverBucket(leftover, bucketName, resourceType, region) {
3191
+ if (leftover === void 0) {
3192
+ this.logger.debug(safeMsg`Not this create's own bucket: no earlier attempt recorded ${this.shown(bucketName)}`);
3193
+ return false;
3194
+ }
3195
+ try {
3196
+ const identity = await this.boundedIdentity(bucketName, resourceType, region);
3197
+ if (typeof identity === "string" && identity === leftover) return true;
3198
+ this.logger.debug(safeMsg`Not this create's own bucket: ${this.shown(bucketName)} reads ` + safeMsg`${typeof identity === "string" ? `created ${tokenDate(identity)}` : "no identity"}, ` + safeMsg`the earlier attempt recorded created ${tokenDate(leftover)}`);
3199
+ return false;
3200
+ } catch {
3201
+ return false;
3202
+ }
3203
+ }
3204
+ async listOwnedBucket(bucketName) {
3140
3205
  try {
3141
3206
  let token;
3142
3207
  for (let page = 0; page < 100; page++) {
@@ -3145,13 +3210,14 @@ var S3BucketProvider = class S3BucketProvider {
3145
3210
  MaxBuckets: 1e3,
3146
3211
  ...token !== void 0 ? { ContinuationToken: token } : {}
3147
3212
  }));
3148
- if ((out.Buckets ?? []).some((b) => b.Name === bucketName)) return { owned: true };
3213
+ const found = (out.Buckets ?? []).find((b) => b.Name === bucketName);
3214
+ if (found !== void 0) return { bucket: found };
3149
3215
  token = out.ContinuationToken || void 0;
3150
- if (token === void 0) return { owned: false };
3216
+ if (token === void 0) return { bucket: void 0 };
3151
3217
  }
3152
3218
  return { unknown: "PaginationLimit" };
3153
3219
  } catch (error) {
3154
- this.logger.debug(safeMsg`ListBuckets failed while checking S3 bucket ${this.shown(bucketName)}: ` + safeMsg`${describeAwsFailure(error).detail}`);
3220
+ this.logger.debug(safeMsg`ListBuckets failed while reading this account's bucket list: ` + safeMsg`${describeAwsFailure(error).detail}`);
3155
3221
  return { unknown: error instanceof Error ? error.name : typeof error };
3156
3222
  }
3157
3223
  }
@@ -4327,32 +4393,38 @@ var S3BucketProvider = class S3BucketProvider {
4327
4393
  let createdNewBucket = false;
4328
4394
  const createClient = await this.getCreateClient();
4329
4395
  ambiguousWindow = takeCreateBucketWindow(logicalId);
4396
+ const ownLeftover = takeOwnLeftoverBucket(logicalId);
4397
+ const adoptedOwnLeftover = explicitBucketName && ownLeftover !== void 0 && context?.replayingState !== true && await this.isOwnLeftoverBucket(ownLeftover, bucketName, resourceType, canonicalRegion);
4398
+ if (adoptedOwnLeftover) {
4399
+ createdNewBucket = true;
4400
+ bucketLeftBehind = true;
4401
+ }
4330
4402
  if (ambiguousWindow !== void 0 && (preflight.kind === "indeterminate" || preflight.kind === "region" && preflight.region === "us-east-1")) {
4331
4403
  windowSpent = true;
4332
4404
  this.refuseAmbiguousCreateAdopt(logicalId, resourceType, bucketName, canonicalRegion, { preflight: preflight.kind }, explicitBucketName);
4333
4405
  }
4334
- if (explicitBucketName && preflight.kind === "region" && preflight.region === "us-east-1") this.refuseExplicitNameHeld(logicalId, resourceType, bucketName, { preflightRegion: preflight.region });
4406
+ if (explicitBucketName && preflight.kind === "region" && preflight.region === "us-east-1") {
4407
+ if (!adoptedOwnLeftover) this.refuseExplicitNameHeld(logicalId, resourceType, bucketName, { preflightRegion: preflight.region });
4408
+ }
4335
4409
  let ownershipUnknown;
4336
- let listedFree = false;
4337
- if (explicitBucketName && preflight.kind === "indeterminate") {
4410
+ if (explicitBucketName && preflight.kind === "indeterminate" && !adoptedOwnLeftover) {
4338
4411
  const owned = await this.ownsBucketNamed(bucketName);
4339
4412
  if ("owned" in owned && owned.owned) this.refuseExplicitNameHeld(logicalId, resourceType, bucketName, { listed: true });
4340
4413
  if ("unknown" in owned) ownershipUnknown = owned.unknown;
4341
- else listedFree = true;
4342
4414
  }
4343
4415
  try {
4344
4416
  const attemptStartMs = Date.now();
4345
- try {
4417
+ if (!adoptedOwnLeftover) try {
4346
4418
  await createClient.send(new CreateBucketCommand(createParams));
4347
4419
  } catch (sendError) {
4348
4420
  createBucketLatch.noteFailure(logicalId, sendError, attemptStartMs, ambiguousWindow);
4349
4421
  throw sendError;
4350
4422
  }
4351
- createdNewBucket = preflight.kind === "absent" || listedFree;
4423
+ createdNewBucket = adoptedOwnLeftover || preflight.kind === "absent";
4352
4424
  bucketLeftBehind = createdNewBucket;
4353
4425
  if (createdNewBucket) windowSpent = true;
4354
4426
  if (preflight.kind === "region" && preflight.region !== "us-east-1") this.refuseForeignRegionAdopt(logicalId, resourceType, bucketName, "us-east-1", preflight.region);
4355
- if (preflight.kind === "region") this.logger.warn(`S3 bucket ${this.shown(bucketName)} for ${displaySafe(logicalId)} (${resourceType}) already existed in ${preflight.region} and was ADOPTED, not created. In us-east-1 S3 answers a re-create of a bucket you already own with 200 OK and RESETS that bucket's access control lists, so any ACL previously set on ${this.shown(bucketName)} is now the default. cdkd will not delete this bucket if the rest of this create fails.`);
4427
+ if (preflight.kind === "region" && !adoptedOwnLeftover) this.logger.warn(`S3 bucket ${this.shown(bucketName)} for ${displaySafe(logicalId)} (${resourceType}) already existed in ${preflight.region} and was ADOPTED, not created. In us-east-1 S3 answers a re-create of a bucket you already own with 200 OK and RESETS that bucket's access control lists, so any ACL previously set on ${this.shown(bucketName)} is now the default. cdkd will not delete this bucket if the rest of this create fails.`);
4356
4428
  if (ownershipUnknown !== void 0 && preflight.kind === "indeterminate") this.logger.warn(safeMsg`S3 bucket ${this.shown(bucketName)} for ${displaySafe(logicalId)} (${resourceType}) was ` + `sent to CreateBucket without knowing whether a bucket of that explicit name ` + safeMsg`already existed: the region probe (${preflight.errorName}) and the bucket ` + safeMsg`listing (${ownershipUnknown}) both failed. In us-east-1 CreateBucket answers 200 ` + "OK over a bucket you own, so if one existed it has now been configured and recorded as this stack's. Re-run with --verbose for AWS's own message.");
4357
4429
  this.logger.debug(`Created S3 bucket: ${this.shown(bucketName)}`);
4358
4430
  } catch (createError) {
@@ -4401,7 +4473,10 @@ var S3BucketProvider = class S3BucketProvider {
4401
4473
  } catch (error) {
4402
4474
  if (ambiguousWindow !== void 0 && !windowSpent) holdCreateBucketWindow(logicalId, ambiguousWindow);
4403
4475
  const thrown = this.wrapOperationError("create", logicalId, resourceType, bucketName, error);
4404
- if (bucketLeftBehind) markCreatedBeforeFailure(thrown, logicalId, resourceType, bucketName);
4476
+ if (bucketLeftBehind) {
4477
+ markCreatedBeforeFailure(thrown, logicalId, resourceType, bucketName);
4478
+ if (explicitBucketName) await this.holdOwnLeftover(logicalId, resourceType, bucketName);
4479
+ }
4405
4480
  throw thrown;
4406
4481
  }
4407
4482
  }
@@ -4453,12 +4528,17 @@ var S3BucketProvider = class S3BucketProvider {
4453
4528
  }
4454
4529
  async delete(logicalId, physicalId, resourceType, properties, context) {
4455
4530
  this.logger.debug(`Deleting S3 bucket ${displaySafe(logicalId)}: ${displaySafe(physicalId)}`);
4456
- const allowAutoEmpty = context?.forceDataDelete === true || hasCdkAutoDeleteTag(properties, "aws-cdk:auto-delete-objects");
4531
+ const failedCreateOrphan = context?.failedCreateOrphan === true;
4532
+ const allowAutoEmpty = !failedCreateOrphan && (context?.forceDataDelete === true || hasCdkAutoDeleteTag(properties, "aws-cdk:auto-delete-objects"));
4457
4533
  if (context?.expectedRegion) await this.assertStateBucketRegion("delete", logicalId, resourceType, physicalId, context.expectedRegion, context);
4458
4534
  else this.announceUnverifiedBucketIdentity("delete", logicalId, physicalId, noRecordedRegionCause());
4459
4535
  try {
4460
4536
  await this.deleteBucketWithEmptyRetry(logicalId, physicalId, allowAutoEmpty);
4461
4537
  } catch (error) {
4538
+ if (failedCreateOrphan && error instanceof BucketNotEmptyRefusal) return {
4539
+ outcome: "skipped",
4540
+ reason: FAILED_CREATE_ORPHAN_NOT_EMPTY_SKIP_REASON
4541
+ };
4462
4542
  if (error instanceof NoSuchBucket) {
4463
4543
  const clientRegion = await this.s3Client.config.region();
4464
4544
  assertRegionMatch(clientRegion, context?.expectedRegion, resourceType, logicalId, physicalId);
@@ -5020,6 +5100,34 @@ var S3BucketProvider = class S3BucketProvider {
5020
5100
  if (filter?.["Prefix"] !== void 0) out["Prefix"] = filter["Prefix"];
5021
5101
  return out;
5022
5102
  }
5103
+ async isSameResource(journaledPhysicalId, record, resourceType, context) {
5104
+ if (resourceType !== "AWS::S3::Bucket") return "unknown";
5105
+ if (!isPlainBucketName(journaledPhysicalId) || !isPlainBucketName(record.physicalId)) return "unknown";
5106
+ if (journaledPhysicalId === record.physicalId) return "same";
5107
+ const want = canonicalizeRegion(context.expectedRegion);
5108
+ if (canonicalizeRegion(await this.getRegion()) !== want) return "unknown";
5109
+ const probe = await this.probeBucketRegion(record.physicalId);
5110
+ return probe.kind === "region" && probe.region === want ? "different" : "unknown";
5111
+ }
5112
+ async resourceIdentity(physicalId, resourceType, context) {
5113
+ if (resourceType !== "AWS::S3::Bucket" || !isPlainBucketName(physicalId)) return void 0;
5114
+ const want = canonicalizeRegion(context.expectedRegion);
5115
+ if (canonicalizeRegion(await this.getRegion()) !== want) return void 0;
5116
+ const probe = await this.probeBucketRegion(physicalId);
5117
+ if (probe.kind === "absent") return RESOURCE_NOT_FOUND;
5118
+ if (probe.kind !== "region" || probe.region !== want) return void 0;
5119
+ const started = Date.now();
5120
+ for (let attempt = 0; attempt < BUCKET_LIST_IDENTITY_ATTEMPTS; attempt++) {
5121
+ if (attempt > 0) {
5122
+ if (Date.now() - started > BUCKET_LIST_IDENTITY_BUDGET_MS) return void 0;
5123
+ await new Promise((r) => setTimeout(r, BUCKET_LIST_IDENTITY_DELAY_MS));
5124
+ }
5125
+ const listed = await this.listOwnedBucket(physicalId);
5126
+ if ("unknown" in listed) return void 0;
5127
+ const created = listed.bucket?.CreationDate;
5128
+ if (created instanceof Date && !Number.isNaN(created.getTime())) return `${physicalId}|${want}|${created.toISOString()}`;
5129
+ }
5130
+ }
5023
5131
  async import(input) {
5024
5132
  const explicit = resolveExplicitPhysicalId(input, "BucketName");
5025
5133
  if (explicit) try {
@@ -5044,7 +5152,7 @@ var S3BucketProvider = class S3BucketProvider {
5044
5152
  } catch (error) {
5045
5153
  const msg = describeAwsFailure(error).detail;
5046
5154
  if (msg.includes("not empty") || msg.includes("BucketNotEmpty")) {
5047
- if (!allowAutoEmpty) throw new Error(`bucket ${displaySafe(bucketName)} is not empty. Matching CloudFormation, cdkd does not delete a non-empty bucket unless it opted into automatic emptying (CDK's autoDeleteObjects: true, i.e. the '${S3_AUTO_DELETE_OBJECTS_TAG}' tag). Either empty the bucket first (delete all objects — and for versioned buckets all object versions and delete markers), or redeploy with autoDeleteObjects: true and destroy again.`);
5155
+ if (!allowAutoEmpty) throw new BucketNotEmptyRefusal(`bucket ${displaySafe(bucketName)} is not empty. Matching CloudFormation, cdkd does not delete a non-empty bucket unless it opted into automatic emptying (CDK's autoDeleteObjects: true, i.e. the '${S3_AUTO_DELETE_OBJECTS_TAG}' tag). Either empty the bucket first (delete all objects — and for versioned buckets all object versions and delete markers), or redeploy with autoDeleteObjects: true and destroy again.`);
5048
5156
  this.logger.info(`Bucket ${displaySafe(bucketName)} not empty (attempt ${attempt}/${maxAttempts}), emptying (auto-delete opt-in present)...`);
5049
5157
  await this.emptyBucket(bucketName);
5050
5158
  continue;
@@ -44389,4 +44497,4 @@ var ACMCertificateProvider = class {
44389
44497
 
44390
44498
  //#endregion
44391
44499
  export { ACMCertificateProvider, ASGProvider, AgentCoreBrowserProvider, AgentCoreCodeInterpreterProvider, AgentCoreEvaluatorProvider, AgentCoreRuntimeProvider, ApiGatewayProvider, ApiGatewayV2Provider, AppSyncProvider, BudgetsBudgetProvider, CloudFrontDistributionProvider, CloudFrontOACProvider, CloudFrontOAIProvider, CloudTrailProvider, CloudWatchAlarmProvider, CloudWatchAnomalyDetectorProvider, CodeBuildProvider, CodeCommitRepositoryProvider, CognitoUserPoolProvider, DLMLifecyclePolicyProvider, DocDBProvider, DocDBSubnetGroupProvider, DynamoDBGlobalTableProvider, DynamoDBTableProvider, EC2Provider, ECRProvider, ECSProvider, EFSProvider, ELBv2Provider, EMRClusterProvider, EMRInstanceFleetConfigProvider, EMRInstanceGroupConfigProvider, ElastiCacheProvider, EventBridgeBusProvider, EventBridgeRuleProvider, FSxFileSystemProvider, FirehoseProvider, GlueConnectionProvider, GlueCrawlerProvider, GlueJobProvider, GlueProvider, GlueSecurityConfigurationProvider, GlueTriggerProvider, GlueWorkflowProvider, IAMAccessKeyProvider, IAMInstanceProfileProvider, IAMManagedPolicyProvider, IAMPolicyProvider, IAMRoleProvider, IAMUserGroupProvider, KMSProvider, KinesisStreamConsumerProvider, KinesisStreamProvider, LambdaEventInvokeConfigProvider, LambdaEventSourceMappingProvider, LambdaFunctionProvider, LambdaLayerVersionProvider, LambdaMicrovmImageProvider, LambdaPermissionProvider, LambdaUrlProvider, LogsLogGroupProvider, NeptuneProvider, NestedStackProvider, PipesPipeProvider, RDSDBProxyEndpointProvider, RDSDBProxyProvider, RDSDBProxyTargetGroupProvider, RDSProvider, Route53Provider, S3BucketPolicyProvider, S3BucketProvider, S3DirectoryBucketProvider, S3TablesProvider, S3VectorsProvider, SNSSubscriptionProvider, SNSTopicPolicyProvider, SNSTopicProvider, SQSQueuePolicyProvider, SQSQueueProvider, SSMParameterProvider, SchedulerScheduleProvider, SecretsManagerSecretProvider, ServiceDiscoveryProvider, StepFunctionsProvider, WAFv2WebACLProvider, WaitConditionHandleProvider };
44392
- //# sourceMappingURL=provider-classes-DQRXWyLx.js.map
44500
+ //# sourceMappingURL=provider-classes-SKdRlxGS.js.map