@cdkd/cli 0.348.0 → 0.349.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 (50) hide show
  1. package/dist/{asg-provider-r1ojkIvF.js → asg-provider-Dvy_jqxt.js} +2 -2
  2. package/dist/{asg-provider-r1ojkIvF.js.map → asg-provider-Dvy_jqxt.js.map} +1 -1
  3. package/dist/aws-partition-DA0r2sr-.js +58 -0
  4. package/dist/aws-partition-DA0r2sr-.js.map +1 -0
  5. package/dist/cli.js +2 -2
  6. package/dist/custom-resource-runtime-Dwnnj7bg.js +1104 -0
  7. package/dist/custom-resource-runtime-Dwnnj7bg.js.map +1 -0
  8. package/dist/{db-instance-modify-retry-BaSXzEMy.js → db-instance-modify-retry-pFWx2ED5.js} +2 -2
  9. package/dist/{db-instance-modify-retry-BaSXzEMy.js.map → db-instance-modify-retry-pFWx2ED5.js.map} +1 -1
  10. package/dist/delete-started-Co5Gt1jH.js +169 -0
  11. package/dist/delete-started-Co5Gt1jH.js.map +1 -0
  12. package/dist/{deploy-engine-2XoVAu4C.js → deploy-engine-DeYSJno7.js} +652 -12015
  13. package/dist/deploy-engine-DeYSJno7.js.map +1 -0
  14. package/dist/diff-calculator-CRkRB1Dg.js +4959 -0
  15. package/dist/diff-calculator-CRkRB1Dg.js.map +1 -0
  16. package/dist/ec2-termination-protection-BM1Zt3Fn.js +1277 -0
  17. package/dist/ec2-termination-protection-BM1Zt3Fn.js.map +1 -0
  18. package/dist/{ecr-uri-C1_heDAt.js → ecr-uri-C3_6QVgR.js} +2 -2
  19. package/dist/{ecr-uri-C1_heDAt.js.map → ecr-uri-C3_6QVgR.js.map} +1 -1
  20. package/dist/expected-bucket-owner-CGoY_YS8.js +88 -0
  21. package/dist/expected-bucket-owner-CGoY_YS8.js.map +1 -0
  22. package/dist/{iam-role-provider-BnLtoKcW.js → iam-role-provider-BaN9MMWs.js} +3 -2
  23. package/dist/iam-role-provider-BaN9MMWs.js.map +1 -0
  24. package/dist/image-plan-D4I8-FhR.js +1940 -0
  25. package/dist/image-plan-D4I8-FhR.js.map +1 -0
  26. package/dist/index.d.ts +3 -1
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +3 -2
  29. package/dist/{neptune-provider-lzti8HIF.js → neptune-provider-BYgFNrtZ.js} +3 -3
  30. package/dist/{neptune-provider-lzti8HIF.js.map → neptune-provider-BYgFNrtZ.js.map} +1 -1
  31. package/dist/{program-DSlYCm_d.js → program-BBGm88gl.js} +629 -1858
  32. package/dist/program-BBGm88gl.js.map +1 -0
  33. package/dist/{provider-classes-RMTfwJPz.js → provider-classes-CRCHL04N.js} +33 -17
  34. package/dist/provider-classes-CRCHL04N.js.map +1 -0
  35. package/dist/{rds-provider-COq1pW0G.js → rds-provider-DKZjtd50.js} +62 -40
  36. package/dist/rds-provider-DKZjtd50.js.map +1 -0
  37. package/dist/{read-replica-sjvqi8Of.js → read-replica-C5e4xpYi.js} +2 -2
  38. package/dist/{read-replica-sjvqi8Of.js.map → read-replica-C5e4xpYi.js.map} +1 -1
  39. package/dist/replacement-rules-01_01yDU.js +4937 -0
  40. package/dist/replacement-rules-01_01yDU.js.map +1 -0
  41. package/dist/resource-deadline-TfDpwRQ_.js +423 -0
  42. package/dist/resource-deadline-TfDpwRQ_.js.map +1 -0
  43. package/dist/{version-DXmr3_M4.js → version-DamSnfI_.js} +2 -2
  44. package/dist/{version-DXmr3_M4.js.map → version-DamSnfI_.js.map} +1 -1
  45. package/package.json +3 -2
  46. package/dist/deploy-engine-2XoVAu4C.js.map +0 -1
  47. package/dist/iam-role-provider-BnLtoKcW.js.map +0 -1
  48. package/dist/program-DSlYCm_d.js.map +0 -1
  49. package/dist/provider-classes-RMTfwJPz.js.map +0 -1
  50. package/dist/rds-provider-COq1pW0G.js.map +0 -1
@@ -0,0 +1,1277 @@
1
+ import { it as UNRENDERABLE, lt as displaySafe, mt as safeMsg, n as getLogger, u as describeAwsFailure } from "./logger-DmQRya0S.js";
2
+ import { B as retryClassificationText, C as isNameCooldownError, D as markReplayMayCollide, F as isAmbiguousOutcomeError, H as isMarkedNonRetryable, L as isIamPropagationError, N as formatRetryClassificationSignals, R as isRetryableTransientError, U as isThrottlingError, x as hasReplayMayCollide, z as isTransientServerError } from "./ambient-client-defaults-7acjxfyN.js";
3
+ import { r as getAwsClients } from "./aws-clients-DOkPjjAW.js";
4
+ import { It as maskerOrIdentity, J as observeThenDisableProtection, Kt as markAuxiliaryFailure, Pt as isSecretDerivedValue, Rt as RETRY_AUXILIARY_OWNER, Ut as hasCreatedBeforeFailure, Wt as isAuxiliaryFailure, Yt as replayMadeAnotherResource, ht as pasteableAwsCommand, zt as carryCreatedBeforeFailure } from "./update-removal-D-FspP88.js";
5
+ import { Nt as dynamicReferenceTokens, t as ReplacementRulesRegistry } from "./replacement-rules-01_01yDU.js";
6
+ import { DescribeInstanceAttributeCommand, ModifyInstanceAttributeCommand } from "@aws-sdk/client-ec2";
7
+ import { DescribeTypeCommand } from "@aws-sdk/client-cloudformation";
8
+
9
+ // src/utils/json-parse-failure.ts
10
+ function describeJsonParseFailure(err, bytes) {
11
+ const raw = describeAwsFailure(err).detail;
12
+ const at = / (?:in|after) JSON at position (\d+)(?: \(line \d+ column \d+\))?$/.exec(raw);
13
+ return `invalid JSON${at ? ` at code-unit position ${at[1]}` : ""}; ${bytes} byte(s) read`;
14
+ }
15
+ function utf8ByteLength(body) {
16
+ return Buffer.byteLength(body, "utf8");
17
+ }
18
+ function parseFailureDebugDetail(err) {
19
+ return displaySafe(describeAwsFailure(err).detail, { asciiOnly: true }) || "<unrenderable>";
20
+ }
21
+ function jsonParseFailureStandIn(err, bytes) {
22
+ return new SyntaxError(describeJsonParseFailure(err, bytes));
23
+ }
24
+ function parseJsonNamingNoBody(body, subject, debug) {
25
+ try {
26
+ return JSON.parse(body);
27
+ } catch (err) {
28
+ debug(`${subject} failed to parse: ${parseFailureDebugDetail(err)}`);
29
+ throw new Error(`${subject} is not valid JSON: ${describeJsonParseFailure(err, utf8ByteLength(body))}`);
30
+ }
31
+ }
32
+
33
+ // src/utils/phase-timings.ts
34
+ const now = () => globalThis.performance.now();
35
+ const PHASE_TIMINGS_ENV = "CDKD_PHASE_TIMINGS";
36
+ function phaseTimingsEnabled() {
37
+ return process.env[PHASE_TIMINGS_ENV] === "1";
38
+ }
39
+ function phaseScopeForStack(stackName, region) {
40
+ return `stack ${stackName} (${region})`;
41
+ }
42
+ const entries = /* @__PURE__ */ new Map();
43
+ function entryFor(scope, phase, kind) {
44
+ let byPhase = entries.get(scope);
45
+ if (byPhase === void 0) {
46
+ byPhase = /* @__PURE__ */ new Map();
47
+ entries.set(scope, byPhase);
48
+ }
49
+ let entry = byPhase.get(phase);
50
+ if (entry === void 0) {
51
+ entry = {
52
+ scope,
53
+ phase,
54
+ kind,
55
+ count: 0,
56
+ totalMs: 0,
57
+ maxMs: 0,
58
+ maxLabel: void 0
59
+ };
60
+ byPhase.set(phase, entry);
61
+ }
62
+ return entry;
63
+ }
64
+ function add(scope, phase, kind, ms, label) {
65
+ const entry = entryFor(scope, phase, kind);
66
+ entry.count += 1;
67
+ entry.totalMs += ms;
68
+ if (ms >= entry.maxMs) {
69
+ entry.maxMs = ms;
70
+ entry.maxLabel = label;
71
+ }
72
+ }
73
+ function recordPhase(scope, phase, ms, label) {
74
+ if (!phaseTimingsEnabled()) return;
75
+ add(scope, phase, "aggregate", ms, label);
76
+ }
77
+ async function timePhase(scope, phase, fn, label) {
78
+ if (!phaseTimingsEnabled()) return fn();
79
+ const start = now();
80
+ try {
81
+ return await fn();
82
+ } finally {
83
+ add(scope, phase, "aggregate", now() - start, label);
84
+ }
85
+ }
86
+ function timePhaseSync(scope, phase, fn, label) {
87
+ if (!phaseTimingsEnabled()) return fn();
88
+ const start = now();
89
+ try {
90
+ return fn();
91
+ } finally {
92
+ add(scope, phase, "aggregate", now() - start, label);
93
+ }
94
+ }
95
+ var PhaseClock = class {
96
+ last;
97
+ enabled;
98
+ scope;
99
+ constructor(scope, options = {}) {
100
+ this.scope = scope;
101
+ this.enabled = phaseTimingsEnabled();
102
+ this.last = this.enabled && options.fromProcessStart !== true ? now() : 0;
103
+ }
104
+ lap(phase) {
105
+ if (!this.enabled) return;
106
+ const at = now();
107
+ add(this.scope, phase, "lap", at - this.last);
108
+ this.last = at;
109
+ }
110
+ };
111
+ function formatMs(ms) {
112
+ return ms >= 1e3 ? `${(ms / 1e3).toFixed(2)}s` : `${Math.round(ms)}ms`;
113
+ }
114
+ function renderPhaseTimings() {
115
+ if (entries.size === 0) return [];
116
+ const all = [...entries.values()].flatMap((byPhase) => [...byPhase.values()]);
117
+ const phaseWidth = Math.max(...all.map((e) => e.phase.length));
118
+ const lines = ["Phase timings (CDKD_PHASE_TIMINGS=1):"];
119
+ for (const [scope, byPhase] of entries) {
120
+ const list = [...byPhase.values()];
121
+ const laps = list.filter((e) => e.kind === "lap");
122
+ const lapTotal = laps.reduce((sum, e) => sum + e.totalMs, 0);
123
+ lines.push(` ${scope}${laps.length > 0 ? ` (${formatMs(lapTotal)} wall)` : ""}`);
124
+ for (const e of list) {
125
+ const name = e.phase.padEnd(phaseWidth);
126
+ if (e.kind === "lap" && e.count === 1) {
127
+ const share = lapTotal > 0 ? ` ${String(Math.round(e.totalMs / lapTotal * 100)).padStart(3)}%` : "";
128
+ lines.push(` ${name} ${formatMs(e.totalMs).padStart(8)}${share}`);
129
+ } else {
130
+ const slowest = e.count > 1 ? `, max ${formatMs(e.maxMs)}${e.maxLabel !== void 0 ? ` (${e.maxLabel})` : ""}` : "";
131
+ lines.push(` ${name} ${formatMs(e.totalMs).padStart(8)} x${e.count}${slowest}`);
132
+ }
133
+ }
134
+ }
135
+ return lines;
136
+ }
137
+
138
+ // src/provisioning/create-only-snapshot.generated.ts
139
+ const CREATE_ONLY_PATHS_SNAPSHOT = /* @__PURE__ */ new Map([
140
+ ["AWS::ApiGateway::Account", []],
141
+ ["AWS::ApiGateway::Authorizer", [["RestApiId"]]],
142
+ ["AWS::ApiGateway::Deployment", [["DeploymentCanarySettings"], ["RestApiId"]]],
143
+ ["AWS::ApiGateway::Method", [
144
+ ["HttpMethod"],
145
+ ["ResourceId"],
146
+ ["RestApiId"]
147
+ ]],
148
+ ["AWS::ApiGateway::Resource", [
149
+ ["ParentId"],
150
+ ["PathPart"],
151
+ ["RestApiId"]
152
+ ]],
153
+ ["AWS::ApiGateway::RestApi", []],
154
+ ["AWS::ApiGateway::Stage", [["RestApiId"], ["StageName"]]],
155
+ ["AWS::ApiGatewayV2::Api", [["ProtocolType"]]],
156
+ ["AWS::ApiGatewayV2::Authorizer", [["ApiId"]]],
157
+ ["AWS::ApiGatewayV2::Integration", [["ApiId"]]],
158
+ ["AWS::ApiGatewayV2::Route", [["ApiId"]]],
159
+ ["AWS::ApiGatewayV2::Stage", [["ApiId"], ["StageName"]]],
160
+ ["AWS::AppConfig::Environment", [["ApplicationId"]]],
161
+ ["AWS::AppSync::ApiKey", [["ApiId"]]],
162
+ ["AWS::AppSync::DataSource", [["ApiId"], ["Name"]]],
163
+ ["AWS::AppSync::GraphQLApi", []],
164
+ ["AWS::AppSync::GraphQLSchema", []],
165
+ ["AWS::AppSync::Resolver", [
166
+ ["ApiId"],
167
+ ["FieldName"],
168
+ ["TypeName"]
169
+ ]],
170
+ ["AWS::AutoScaling::AutoScalingGroup", [["AutoScalingGroupName"], ["InstanceId"]]],
171
+ ["AWS::BedrockAgentCore::Browser", []],
172
+ ["AWS::BedrockAgentCore::CodeInterpreter", []],
173
+ ["AWS::BedrockAgentCore::Evaluator", [[
174
+ "EvaluatorConfig",
175
+ "Derived",
176
+ "BaseEvaluatorId"
177
+ ], ["EvaluatorName"]]],
178
+ ["AWS::BedrockAgentCore::Runtime", [["AgentRuntimeName"]]],
179
+ ["AWS::Budgets::Budget", [["Budget", "BudgetName"], ["NotificationsWithSubscribers"]]],
180
+ ["AWS::CertificateManager::Certificate", [
181
+ ["CertificateAuthorityArn"],
182
+ ["CertificateExport"],
183
+ ["DomainName"],
184
+ ["DomainValidationOptions"],
185
+ ["KeyAlgorithm"],
186
+ ["SubjectAlternativeNames"]
187
+ ]],
188
+ ["AWS::CloudFormation::Stack", [["StackName"]]],
189
+ ["AWS::CloudFormation::WaitConditionHandle", []],
190
+ ["AWS::CloudFront::CloudFrontOriginAccessIdentity", []],
191
+ ["AWS::CloudFront::Distribution", []],
192
+ ["AWS::CloudFront::OriginAccessControl", []],
193
+ ["AWS::CloudTrail::Trail", [["TrailName"]]],
194
+ ["AWS::CloudWatch::Alarm", [["AlarmName"]]],
195
+ ["AWS::CloudWatch::AnomalyDetector", [
196
+ ["Dimensions"],
197
+ ["MetricCharacteristics"],
198
+ ["MetricMathAnomalyDetector"],
199
+ ["MetricName"],
200
+ ["Namespace"],
201
+ ["SingleMetricAnomalyDetector"],
202
+ ["Stat"]
203
+ ]],
204
+ ["AWS::CodeBuild::Project", [["Name"]]],
205
+ ["AWS::CodeCommit::Repository", []],
206
+ ["AWS::Cognito::UserPool", []],
207
+ ["AWS::DLM::LifecyclePolicy", []],
208
+ ["AWS::DocDB::DBCluster", [
209
+ ["AvailabilityZones"],
210
+ ["DBClusterIdentifier"],
211
+ ["DBSubnetGroupName"],
212
+ ["KmsKeyId"],
213
+ ["MasterUsername"],
214
+ ["SnapshotIdentifier"],
215
+ ["SourceDBClusterIdentifier"],
216
+ ["StorageEncrypted"]
217
+ ]],
218
+ ["AWS::DocDB::DBInstance", [
219
+ ["AvailabilityZone"],
220
+ ["DBClusterIdentifier"],
221
+ ["DBInstanceIdentifier"]
222
+ ]],
223
+ ["AWS::DocDB::DBSubnetGroup", [["DBSubnetGroupName"]]],
224
+ ["AWS::DynamoDB::GlobalTable", [["TableName"]]],
225
+ ["AWS::DynamoDB::Table", [["ImportSourceSpecification"], ["TableName"]]],
226
+ ["AWS::EC2::EIP", [
227
+ ["Address"],
228
+ ["IpamPoolId"],
229
+ ["NetworkBorderGroup"],
230
+ ["TransferAddress"]
231
+ ]],
232
+ ["AWS::EC2::Instance", [
233
+ ["AvailabilityZone"],
234
+ ["CpuOptions"],
235
+ ["ElasticGpuSpecifications"],
236
+ ["ElasticInferenceAccelerators"],
237
+ ["EnclaveOptions"],
238
+ ["HibernationOptions"],
239
+ ["HostResourceGroupArn"],
240
+ ["ImageId"],
241
+ ["Ipv6AddressCount"],
242
+ ["Ipv6Addresses"],
243
+ ["KeyName"],
244
+ ["LaunchTemplate"],
245
+ ["LicenseSpecifications"],
246
+ ["NetworkInterfaces"],
247
+ ["PlacementGroupName"],
248
+ ["PrivateIpAddress"],
249
+ ["SecurityGroups"],
250
+ ["SubnetId"]
251
+ ]],
252
+ ["AWS::EC2::InternetGateway", []],
253
+ ["AWS::EC2::NatGateway", [
254
+ ["AllocationId"],
255
+ ["AvailabilityMode"],
256
+ ["ConnectivityType"],
257
+ ["PrivateIpAddress"],
258
+ ["SubnetId"],
259
+ ["VpcId"]
260
+ ]],
261
+ ["AWS::EC2::NetworkAcl", [["VpcId"]]],
262
+ ["AWS::EC2::NetworkAclEntry", [
263
+ ["Egress"],
264
+ ["NetworkAclId"],
265
+ ["RuleNumber"]
266
+ ]],
267
+ ["AWS::EC2::Route", [
268
+ ["DestinationCidrBlock"],
269
+ ["DestinationIpv6CidrBlock"],
270
+ ["DestinationPrefixListId"],
271
+ ["RouteTableId"]
272
+ ]],
273
+ ["AWS::EC2::RouteTable", [["VpcId"]]],
274
+ ["AWS::EC2::SecurityGroup", [
275
+ ["GroupDescription"],
276
+ ["GroupName"],
277
+ ["VpcId"]
278
+ ]],
279
+ ["AWS::EC2::SecurityGroupIngress", [
280
+ ["CidrIp"],
281
+ ["CidrIpv6"],
282
+ ["FromPort"],
283
+ ["GroupId"],
284
+ ["GroupName"],
285
+ ["IpProtocol"],
286
+ ["SourcePrefixListId"],
287
+ ["SourceSecurityGroupId"],
288
+ ["SourceSecurityGroupName"],
289
+ ["SourceSecurityGroupOwnerId"],
290
+ ["ToPort"]
291
+ ]],
292
+ ["AWS::EC2::Subnet", [
293
+ ["AvailabilityZone"],
294
+ ["AvailabilityZoneId"],
295
+ ["CidrBlock"],
296
+ ["Ipv4IpamPoolId"],
297
+ ["Ipv4NetmaskLength"],
298
+ ["Ipv6IpamPoolId"],
299
+ ["Ipv6Native"],
300
+ ["Ipv6NetmaskLength"],
301
+ ["OutpostArn"],
302
+ ["VpcId"]
303
+ ]],
304
+ ["AWS::EC2::SubnetNetworkAclAssociation", [["NetworkAclId"], ["SubnetId"]]],
305
+ ["AWS::EC2::SubnetRouteTableAssociation", [["RouteTableId"], ["SubnetId"]]],
306
+ ["AWS::EC2::VPC", [
307
+ ["CidrBlock"],
308
+ ["Ipv4IpamPoolId"],
309
+ ["Ipv4NetmaskLength"],
310
+ ["VpcEncryptionControl"]
311
+ ]],
312
+ ["AWS::EC2::VPCGatewayAttachment", [["VpcId"]]],
313
+ ["AWS::ECR::Repository", [
314
+ ["EncryptionConfiguration"],
315
+ ["EncryptionConfiguration", "EncryptionType"],
316
+ ["EncryptionConfiguration", "KmsKey"],
317
+ ["RepositoryName"]
318
+ ]],
319
+ ["AWS::ECS::Cluster", [["ClusterName"]]],
320
+ ["AWS::ECS::Service", [
321
+ ["Cluster"],
322
+ ["Role"],
323
+ ["SchedulingStrategy"],
324
+ ["ServiceName"]
325
+ ]],
326
+ ["AWS::ECS::TaskDefinition", [
327
+ ["ContainerDefinitions"],
328
+ ["Cpu"],
329
+ ["EnableFaultInjection"],
330
+ ["EphemeralStorage"],
331
+ ["ExecutionRoleArn"],
332
+ ["Family"],
333
+ ["InferenceAccelerators"],
334
+ ["IpcMode"],
335
+ ["Memory"],
336
+ ["NetworkMode"],
337
+ ["PidMode"],
338
+ ["PlacementConstraints"],
339
+ ["ProxyConfiguration"],
340
+ ["RequiresCompatibilities"],
341
+ ["RuntimePlatform"],
342
+ ["TaskRoleArn"],
343
+ ["Volumes"]
344
+ ]],
345
+ ["AWS::EFS::AccessPoint", [
346
+ ["ClientToken"],
347
+ ["CreationInfo"],
348
+ ["CreationInfo", "OwnerGid"],
349
+ ["CreationInfo", "OwnerUid"],
350
+ ["CreationInfo", "Permissions"],
351
+ ["FileSystemId"],
352
+ ["PosixUser"],
353
+ ["PosixUser", "Gid"],
354
+ ["PosixUser", "SecondaryGids"],
355
+ ["PosixUser", "Uid"],
356
+ ["RootDirectory"],
357
+ ["RootDirectory", "CreationInfo"],
358
+ ["RootDirectory", "Path"]
359
+ ]],
360
+ ["AWS::EFS::FileSystem", [
361
+ ["AvailabilityZoneName"],
362
+ ["Encrypted"],
363
+ ["KmsKeyId"],
364
+ ["PerformanceMode"]
365
+ ]],
366
+ ["AWS::EFS::MountTarget", [
367
+ ["FileSystemId"],
368
+ ["IpAddress"],
369
+ ["IpAddressType"],
370
+ ["Ipv6Address"],
371
+ ["SubnetId"]
372
+ ]],
373
+ ["AWS::ElastiCache::CacheCluster", [
374
+ ["CacheSubnetGroupName"],
375
+ ["ClusterName"],
376
+ ["Engine"],
377
+ ["NetworkType"],
378
+ ["Port"],
379
+ ["SnapshotArns"],
380
+ ["SnapshotName"]
381
+ ]],
382
+ ["AWS::ElastiCache::SubnetGroup", [["CacheSubnetGroupName"]]],
383
+ ["AWS::ElasticLoadBalancingV2::Listener", [["LoadBalancerArn"]]],
384
+ ["AWS::ElasticLoadBalancingV2::LoadBalancer", [
385
+ ["Name"],
386
+ ["Scheme"],
387
+ ["Type"]
388
+ ]],
389
+ ["AWS::ElasticLoadBalancingV2::TargetGroup", [
390
+ ["IpAddressType"],
391
+ ["Name"],
392
+ ["Port"],
393
+ ["Protocol"],
394
+ ["ProtocolVersion"],
395
+ ["TargetType"],
396
+ ["VpcId"]
397
+ ]],
398
+ ["AWS::EMR::Cluster", [
399
+ ["AdditionalInfo"],
400
+ ["Applications"],
401
+ ["AutoScalingRole"],
402
+ ["BootstrapActions"],
403
+ ["Configurations"],
404
+ ["CustomAmiId"],
405
+ ["EbsRootVolumeIops"],
406
+ ["EbsRootVolumeSize"],
407
+ ["EbsRootVolumeThroughput"],
408
+ ["JobFlowRole"],
409
+ ["KerberosAttributes"],
410
+ ["LogEncryptionKmsKeyId"],
411
+ ["LogUri"],
412
+ ["MonitoringConfiguration"],
413
+ ["Name"],
414
+ ["OSReleaseLabel"],
415
+ ["PlacementGroupConfigs"],
416
+ ["ReleaseLabel"],
417
+ ["ScaleDownBehavior"],
418
+ ["SecurityConfiguration"],
419
+ ["ServiceRole"],
420
+ ["SessionEnabled"],
421
+ ["Steps"]
422
+ ]],
423
+ ["AWS::EMR::InstanceFleetConfig", [
424
+ ["ClusterId"],
425
+ ["InstanceFleetType"],
426
+ ["LaunchSpecifications"],
427
+ ["Name"]
428
+ ]],
429
+ ["AWS::EMR::InstanceGroupConfig", [
430
+ ["BidPrice"],
431
+ ["Configurations"],
432
+ ["CustomAmiId"],
433
+ ["EbsConfiguration"],
434
+ ["InstanceRole"],
435
+ ["InstanceType"],
436
+ ["JobFlowId"],
437
+ ["Market"],
438
+ ["Name"]
439
+ ]],
440
+ ["AWS::Events::EventBus", [["Name"]]],
441
+ ["AWS::Events::Rule", [["Name"]]],
442
+ ["AWS::FSx::FileSystem", [
443
+ ["BackupId"],
444
+ ["FileSystemType"],
445
+ ["KmsKeyId"],
446
+ ["SecurityGroupIds"],
447
+ ["SubnetIds"]
448
+ ]],
449
+ ["AWS::Glue::Connection", [["CatalogId"], ["ConnectionInput", "Name"]]],
450
+ ["AWS::Glue::Crawler", [["Name"]]],
451
+ ["AWS::Glue::Database", [["DatabaseName"]]],
452
+ ["AWS::Glue::Job", [["Name"]]],
453
+ ["AWS::Glue::SecurityConfiguration", [["Name"]]],
454
+ ["AWS::Glue::Table", [
455
+ ["CatalogId"],
456
+ ["DatabaseName"],
457
+ ["Name"],
458
+ ["TableInput", "Name"]
459
+ ]],
460
+ ["AWS::Glue::Trigger", [
461
+ ["Name"],
462
+ ["Type"],
463
+ ["WorkflowName"]
464
+ ]],
465
+ ["AWS::Glue::Workflow", [["Name"]]],
466
+ ["AWS::IAM::AccessKey", [["Serial"], ["UserName"]]],
467
+ ["AWS::IAM::Group", [["GroupName"]]],
468
+ ["AWS::IAM::InstanceProfile", [["InstanceProfileName"], ["Path"]]],
469
+ ["AWS::IAM::ManagedPolicy", [
470
+ ["Description"],
471
+ ["ManagedPolicyName"],
472
+ ["Path"]
473
+ ]],
474
+ ["AWS::IAM::Policy", []],
475
+ ["AWS::IAM::Role", [["Path"], ["RoleName"]]],
476
+ ["AWS::IAM::User", [["UserName"]]],
477
+ ["AWS::IAM::UserToGroupAddition", []],
478
+ ["AWS::Kinesis::Stream", [["Name"]]],
479
+ ["AWS::Kinesis::StreamConsumer", [
480
+ ["ConsumerName"],
481
+ ["StreamARN"],
482
+ ["Tags"]
483
+ ]],
484
+ ["AWS::KinesisFirehose::DeliveryStream", [
485
+ ["AmazonOpenSearchServerlessDestinationConfiguration", "VpcConfiguration"],
486
+ ["AmazonopensearchserviceDestinationConfiguration", "VpcConfiguration"],
487
+ ["DatabaseSourceConfiguration"],
488
+ ["DeliveryStreamName"],
489
+ ["DeliveryStreamType"],
490
+ ["DirectPutSourceConfiguration"],
491
+ ["ElasticsearchDestinationConfiguration", "VpcConfiguration"],
492
+ ["IcebergDestinationConfiguration", "CatalogConfiguration"],
493
+ ["KinesisStreamSourceConfiguration"],
494
+ ["MSKSourceConfiguration"],
495
+ ["SnowflakeDestinationConfiguration", "SnowflakeVpcConfiguration"]
496
+ ]],
497
+ ["AWS::KMS::Alias", [["AliasName"]]],
498
+ ["AWS::KMS::Key", []],
499
+ ["AWS::Lambda::EventInvokeConfig", [["FunctionName"], ["Qualifier"]]],
500
+ ["AWS::Lambda::EventSourceMapping", [
501
+ ["EventSourceArn"],
502
+ ["SelfManagedEventSource"],
503
+ ["StartingPosition"],
504
+ ["StartingPositionTimestamp"]
505
+ ]],
506
+ ["AWS::Lambda::Function", [
507
+ ["FunctionName"],
508
+ ["PackageType"],
509
+ ["TenancyConfig"]
510
+ ]],
511
+ ["AWS::Lambda::LayerVersion", [
512
+ ["CompatibleArchitectures"],
513
+ ["CompatibleRuntimes"],
514
+ ["Content"],
515
+ ["Description"],
516
+ ["LayerName"],
517
+ ["LicenseInfo"]
518
+ ]],
519
+ ["AWS::Lambda::MicrovmImage", [["Name"]]],
520
+ ["AWS::Lambda::NetworkConnector", [["Name"]]],
521
+ ["AWS::Lambda::Permission", [
522
+ ["Action"],
523
+ ["EventSourceToken"],
524
+ ["FunctionName"],
525
+ ["FunctionUrlAuthType"],
526
+ ["InvokedViaFunctionUrl"],
527
+ ["Principal"],
528
+ ["PrincipalOrgID"],
529
+ ["SourceAccount"],
530
+ ["SourceArn"]
531
+ ]],
532
+ ["AWS::Lambda::Url", [["Qualifier"], ["TargetFunctionArn"]]],
533
+ ["AWS::Lambda::WebFunctionEndpoint", [
534
+ ["EndpointName"],
535
+ ["EndpointType"],
536
+ ["FunctionName"],
537
+ ["Regions"]
538
+ ]],
539
+ ["AWS::Lambda::WebFunctionRevision", [
540
+ ["BuildConfig"],
541
+ ["Description"],
542
+ ["FunctionName"],
543
+ ["KmsKeyArn"],
544
+ ["ServiceConfig"]
545
+ ]],
546
+ ["AWS::Logs::LogGroup", [["LogGroupName"]]],
547
+ ["AWS::Neptune::DBCluster", [
548
+ ["AvailabilityZones"],
549
+ ["DBClusterIdentifier"],
550
+ ["DBSubnetGroupName"],
551
+ ["GlobalClusterIdentifier"],
552
+ ["KmsKeyId"],
553
+ ["RestoreToTime"],
554
+ ["RestoreType"],
555
+ ["SnapshotIdentifier"],
556
+ ["SourceDBClusterIdentifier"],
557
+ ["StorageEncrypted"],
558
+ ["UseLatestRestorableTime"]
559
+ ]],
560
+ ["AWS::Neptune::DBInstance", [
561
+ ["AvailabilityZone"],
562
+ ["DBClusterIdentifier"],
563
+ ["DBInstanceIdentifier"],
564
+ ["DBSnapshotIdentifier"],
565
+ ["DBSubnetGroupName"]
566
+ ]],
567
+ ["AWS::Neptune::DBSubnetGroup", [["DBSubnetGroupName"]]],
568
+ ["AWS::Pipes::Pipe", [
569
+ ["Name"],
570
+ ["Source"],
571
+ [
572
+ "SourceParameters",
573
+ "ActiveMQBrokerParameters",
574
+ "QueueName"
575
+ ],
576
+ [
577
+ "SourceParameters",
578
+ "DynamoDBStreamParameters",
579
+ "StartingPosition"
580
+ ],
581
+ [
582
+ "SourceParameters",
583
+ "KinesisStreamParameters",
584
+ "StartingPosition"
585
+ ],
586
+ [
587
+ "SourceParameters",
588
+ "KinesisStreamParameters",
589
+ "StartingPositionTimestamp"
590
+ ],
591
+ [
592
+ "SourceParameters",
593
+ "ManagedStreamingKafkaParameters",
594
+ "ConsumerGroupID"
595
+ ],
596
+ [
597
+ "SourceParameters",
598
+ "ManagedStreamingKafkaParameters",
599
+ "StartingPosition"
600
+ ],
601
+ [
602
+ "SourceParameters",
603
+ "ManagedStreamingKafkaParameters",
604
+ "TopicName"
605
+ ],
606
+ [
607
+ "SourceParameters",
608
+ "RabbitMQBrokerParameters",
609
+ "QueueName"
610
+ ],
611
+ [
612
+ "SourceParameters",
613
+ "RabbitMQBrokerParameters",
614
+ "VirtualHost"
615
+ ],
616
+ [
617
+ "SourceParameters",
618
+ "SelfManagedKafkaParameters",
619
+ "AdditionalBootstrapServers"
620
+ ],
621
+ [
622
+ "SourceParameters",
623
+ "SelfManagedKafkaParameters",
624
+ "ConsumerGroupID"
625
+ ],
626
+ [
627
+ "SourceParameters",
628
+ "SelfManagedKafkaParameters",
629
+ "StartingPosition"
630
+ ],
631
+ [
632
+ "SourceParameters",
633
+ "SelfManagedKafkaParameters",
634
+ "TopicName"
635
+ ]
636
+ ]],
637
+ ["AWS::RDS::DBCluster", [
638
+ ["ClusterScalabilityType"],
639
+ ["DBClusterIdentifier"],
640
+ ["DBSubnetGroupName"],
641
+ ["DBSystemId"],
642
+ ["DatabaseName"],
643
+ ["EngineMode"],
644
+ ["KmsKeyId"],
645
+ ["PubliclyAccessible"],
646
+ ["RestoreToTime"],
647
+ ["RestoreType"],
648
+ ["SnapshotIdentifier"],
649
+ ["SourceDBClusterIdentifier"],
650
+ ["SourceDbClusterResourceId"],
651
+ ["SourceRegion"],
652
+ ["StorageEncrypted"],
653
+ ["UseLatestRestorableTime"],
654
+ ["WithExpressConfiguration"]
655
+ ]],
656
+ ["AWS::RDS::DBInstance", [
657
+ ["BackupTarget"],
658
+ ["CharacterSetName"],
659
+ ["CustomIAMInstanceProfile"],
660
+ ["DBClusterIdentifier"],
661
+ ["DBInstanceIdentifier"],
662
+ ["DBName"],
663
+ ["DBSubnetGroupName"],
664
+ ["DBSystemId"],
665
+ ["KmsKeyId"],
666
+ ["MasterUsername"],
667
+ ["NcharCharacterSetName"],
668
+ ["SourceRegion"],
669
+ ["StorageEncrypted"],
670
+ ["Timezone"]
671
+ ]],
672
+ ["AWS::RDS::DBProxy", [
673
+ ["DBProxyName"],
674
+ ["EndpointNetworkType"],
675
+ ["EngineFamily"],
676
+ ["TargetConnectionNetworkType"],
677
+ ["VpcSubnetIds"]
678
+ ]],
679
+ ["AWS::RDS::DBProxyEndpoint", [
680
+ ["DBProxyEndpointName"],
681
+ ["DBProxyName"],
682
+ ["EndpointNetworkType"],
683
+ ["VpcSubnetIds"]
684
+ ]],
685
+ ["AWS::RDS::DBProxyTargetGroup", [["DBProxyName"], ["TargetGroupName"]]],
686
+ ["AWS::RDS::DBSubnetGroup", [["DBSubnetGroupName"]]],
687
+ ["AWS::Route53::HostedZone", [["DelegationSetId"], ["Name"]]],
688
+ ["AWS::Route53::RecordSet", [["HostedZoneId"], ["HostedZoneName"]]],
689
+ ["AWS::S3::Bucket", [
690
+ ["BucketName"],
691
+ ["BucketNamePrefix"],
692
+ ["BucketNamespace"]
693
+ ]],
694
+ ["AWS::S3::BucketPolicy", [["Bucket"]]],
695
+ ["AWS::S3Express::DirectoryBucket", [
696
+ ["BucketName"],
697
+ ["DataRedundancy"],
698
+ ["LocationName"]
699
+ ]],
700
+ ["AWS::S3Tables::Namespace", [["Namespace"], ["TableBucketARN"]]],
701
+ ["AWS::S3Tables::Table", [
702
+ ["IcebergMetadata"],
703
+ ["OpenTableFormat"],
704
+ ["StorageClassConfiguration"],
705
+ ["TableBucketARN"],
706
+ ["WithoutMetadata"]
707
+ ]],
708
+ ["AWS::S3Tables::TableBucket", [["TableBucketName"]]],
709
+ ["AWS::S3Vectors::VectorBucket", [["EncryptionConfiguration"], ["VectorBucketName"]]],
710
+ ["AWS::Scheduler::Schedule", [["Name"]]],
711
+ ["AWS::SecretsManager::Secret", [["Name"]]],
712
+ ["AWS::ServiceDiscovery::HttpNamespace", [["Name"]]],
713
+ ["AWS::ServiceDiscovery::PrivateDnsNamespace", [["Name"], ["Vpc"]]],
714
+ ["AWS::ServiceDiscovery::PublicDnsNamespace", [["Name"]]],
715
+ ["AWS::ServiceDiscovery::Service", [
716
+ ["HealthCheckCustomConfig"],
717
+ ["Name"],
718
+ ["NamespaceId"],
719
+ ["Type"]
720
+ ]],
721
+ ["AWS::SNS::Subscription", [
722
+ ["Endpoint"],
723
+ ["Protocol"],
724
+ ["TopicArn"]
725
+ ]],
726
+ ["AWS::SNS::Topic", [["FifoTopic"], ["TopicName"]]],
727
+ ["AWS::SNS::TopicPolicy", []],
728
+ ["AWS::SQS::Queue", [["FifoQueue"], ["QueueName"]]],
729
+ ["AWS::SQS::QueuePolicy", []],
730
+ ["AWS::SSM::Parameter", [["Name"]]],
731
+ ["AWS::StepFunctions::StateMachine", [["StateMachineName"], ["StateMachineType"]]],
732
+ ["AWS::WAFv2::WebACL", [["Name"], ["Scope"]]]
733
+ ]);
734
+
735
+ // src/deployment/retry.ts
736
+ const IAM_PROPAGATION_INITIAL_DELAY_MS = 250;
737
+ const IAM_PROPAGATION_MAX_DELAY_MS = 2e3;
738
+ const IAM_PROPAGATION_MAX_RETRIES = 26;
739
+ const NAME_COOLDOWN_INITIAL_DELAY_MS = 2e3;
740
+ const NAME_COOLDOWN_MAX_DELAY_MS = 1e4;
741
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
742
+ async function withRetry(operation, logicalId, opts = {}) {
743
+ const shownId = displaySafe(logicalId, { asciiOnly: true }) || "<unrenderable>";
744
+ const maxRetries = opts.maxRetries ?? 8;
745
+ const initialDelayMs = opts.initialDelayMs ?? 1e3;
746
+ const maxDelayMs = opts.maxDelayMs ?? 8e3;
747
+ const sleep = opts.sleep ?? defaultSleep;
748
+ const defaultSchedule = opts.maxRetries === void 0 && opts.initialDelayMs === void 0 && opts.maxDelayMs === void 0 && opts.isRetryable === void 0;
749
+ const attemptCeiling = defaultSchedule ? Math.max(maxRetries, 26) : maxRetries;
750
+ let lastError;
751
+ let sawPropagation = false;
752
+ let propagationRetries = 0;
753
+ let propagationSleptMs = 0;
754
+ let nameCooldownRetries = 0;
755
+ let nameCooldownSleptMs = 0;
756
+ let serverErrorRetries = 0;
757
+ let replayMayCollide = false;
758
+ let previousError;
759
+ const settle = (error) => replayMayCollide ? markReplayMayCollide(markAuxiliaryFailure(error, RETRY_AUXILIARY_OWNER)) : error;
760
+ for (let attempt = 0; attempt <= attemptCeiling; attempt++) try {
761
+ return await operation();
762
+ } catch (error) {
763
+ lastError = error;
764
+ const replayMadeAnother = replayMadeAnotherResource(previousError, error);
765
+ const carried = carryCreatedBeforeFailure(previousError, error);
766
+ if (hasCreatedBeforeFailure(carried) || !hasCreatedBeforeFailure(previousError)) previousError = carried;
767
+ if (isAuxiliaryFailure(error) || hasReplayMayCollide(error) || isAmbiguousOutcomeError(error)) replayMayCollide = true;
768
+ const message = describeAwsFailure(error).detail;
769
+ const classifyText = retryClassificationText(error);
770
+ if (isMarkedNonRetryable(error)) throw settle(error);
771
+ if (replayMadeAnother) {
772
+ try {
773
+ opts.logger?.warn?.(safeMsg`${shownId}: not retrying - a retried create made another resource instead of resuming the one an earlier attempt left behind, and only the latest is recorded for \`cdkd rollback --revert-failed\`. Find the earlier one and delete it by hand`);
774
+ } catch {}
775
+ throw settle(error);
776
+ }
777
+ const retryable = opts.isRetryable ? opts.isRetryable(classifyText, error) : isRetryableTransientError(error, classifyText);
778
+ const propagation = defaultSchedule && isIamPropagationError(classifyText);
779
+ if (propagation) sawPropagation = true;
780
+ const nameCooldown = defaultSchedule && !propagation && isNameCooldownError(classifyText);
781
+ const attemptLimit = sawPropagation ? 26 : maxRetries;
782
+ if (!retryable || attempt >= attemptLimit) {
783
+ if (propagationRetries > 0 || serverErrorRetries > 0 || nameCooldownRetries > 0) {
784
+ const budgetExhausted = sawPropagation && attempt >= attemptLimit;
785
+ const nameCooldownBudgetExhausted = nameCooldownRetries >= maxRetries && attempt >= attemptLimit;
786
+ const spent = [];
787
+ if (propagationRetries > 0) spent.push(`${propagationRetries} IAM-propagation ${propagationRetries === 1 ? "retry" : "retries"} over ${(propagationSleptMs / 1e3).toFixed(2)}s of propagation backoff${budgetExhausted ? " (the full propagation budget)" : ""}`);
788
+ if (nameCooldownRetries > 0) spent.push(`${nameCooldownRetries} name-cooldown ${nameCooldownRetries === 1 ? "retry" : "retries"} over ${(nameCooldownSleptMs / 1e3).toFixed(2)}s waiting for the name to be released${nameCooldownBudgetExhausted ? " (the full name-cooldown budget)" : ""}`);
789
+ if (serverErrorRetries > 0) spent.push(`${serverErrorRetries} transient server-error ${serverErrorRetries === 1 ? "retry" : "retries"} (HTTP 5xx)`);
790
+ const summary = () => `${shownId}: gave up after ${spent.join(" and ")} - ${message}` + formatRetryClassificationSignals(error);
791
+ try {
792
+ opts.logger?.warn?.(summary());
793
+ } catch {}
794
+ }
795
+ throw settle(error);
796
+ }
797
+ const delay = propagation ? Math.min(250 * Math.pow(2, attempt), IAM_PROPAGATION_MAX_DELAY_MS) : nameCooldown ? Math.min(NAME_COOLDOWN_INITIAL_DELAY_MS * Math.pow(2, attempt), NAME_COOLDOWN_MAX_DELAY_MS) : Math.min(initialDelayMs * Math.pow(2, attempt), maxDelayMs);
798
+ const backoffThroughThisAttemptMs = propagation ? propagationSleptMs + delay : propagationSleptMs;
799
+ if (phaseTimingsEnabled()) recordPhase("retries (every stack)", `retry after ${retryErrorClass(error)}`, delay, shownId);
800
+ opts.logger?.debug(` ⏳ Retrying ${shownId} in ${delay / 1e3}s (attempt ${attempt + 1}/${attemptLimit}${propagation ? `, ${(backoffThroughThisAttemptMs / 1e3).toFixed(2)}s backoff through this attempt` : ""}) - ${message}`);
801
+ for (let waited = 0; waited < delay; waited += 1e3) {
802
+ if (opts.isInterrupted?.()) throw carryCreatedBeforeFailure(previousError, opts.onInterrupted ? opts.onInterrupted() : /* @__PURE__ */ new Error("Interrupted"));
803
+ await sleep(Math.min(1e3, delay - waited));
804
+ }
805
+ if (propagation) {
806
+ propagationRetries++;
807
+ propagationSleptMs = backoffThroughThisAttemptMs;
808
+ } else if (nameCooldown) {
809
+ nameCooldownRetries++;
810
+ nameCooldownSleptMs += delay;
811
+ } else if (opts.isRetryable === void 0 && isTransientServerError(error)) serverErrorRetries++;
812
+ }
813
+ throw lastError;
814
+ }
815
+ function retryErrorClass(error) {
816
+ const ident = (value) => typeof value === "string" && /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(value) ? value : void 0;
817
+ const name = ident(error?.name) ?? "Error";
818
+ const code = ident(error?.ccErrorCode);
819
+ let root;
820
+ let current = error?.cause;
821
+ for (let depth = 0; depth < 5 && current !== null && typeof current === "object"; depth++) {
822
+ root = ident(current.name) ?? root;
823
+ const next = current.cause;
824
+ if (next === current) break;
825
+ current = next;
826
+ }
827
+ const parts = [code, root !== void 0 && root !== name ? root : void 0].filter((part) => part !== void 0);
828
+ return parts.length > 0 ? `${name} (${parts.join(", ")})` : name;
829
+ }
830
+
831
+ // src/utils/concurrency-limiter.ts
832
+ var BackgroundTaskCancelledError = class extends Error {
833
+ constructor() {
834
+ super("Background task cancelled");
835
+ this.name = "BackgroundTaskCancelledError";
836
+ }
837
+ };
838
+ function createConcurrencyLimiter(limit) {
839
+ if (!Number.isInteger(limit) || limit < 1) throw new Error(`Concurrency limit must be a positive integer, got ${String(limit)}`);
840
+ let active = 0;
841
+ const queue = [];
842
+ const urgentWaiterListeners = /* @__PURE__ */ new Set();
843
+ const urgentQueued = () => queue.length > 0 && queue[0].urgent;
844
+ const notifyUrgentWaiter = () => {
845
+ for (const listener of [...urgentWaiterListeners]) listener();
846
+ };
847
+ const insert = (entry) => {
848
+ if (!entry.urgent) {
849
+ queue.push(entry);
850
+ return;
851
+ }
852
+ const firstBackground = queue.findIndex((e) => !e.urgent);
853
+ if (firstBackground === -1) queue.push(entry);
854
+ else queue.splice(firstBackground, 0, entry);
855
+ };
856
+ const drain = () => {
857
+ while (active < limit && queue.length > 0) queue.shift().start();
858
+ };
859
+ return {
860
+ schedule(task, options) {
861
+ let resolveTask;
862
+ let rejectTask;
863
+ const promise = new Promise((resolve, reject) => {
864
+ resolveTask = resolve;
865
+ rejectTask = reject;
866
+ });
867
+ const controller = new AbortController();
868
+ let settled = false;
869
+ let released = false;
870
+ const release = () => {
871
+ if (released) return;
872
+ released = true;
873
+ active--;
874
+ drain();
875
+ };
876
+ const promoteListeners = /* @__PURE__ */ new Set();
877
+ const urgency = {
878
+ get urgent() {
879
+ return entry.urgent;
880
+ },
881
+ get awaited() {
882
+ return entry.urgent || urgentQueued();
883
+ },
884
+ onAwaited: (listener) => {
885
+ if (urgency.awaited) {
886
+ listener();
887
+ return () => {};
888
+ }
889
+ const remove = () => {
890
+ promoteListeners.delete(once);
891
+ urgentWaiterListeners.delete(once);
892
+ };
893
+ const once = () => {
894
+ remove();
895
+ listener();
896
+ };
897
+ promoteListeners.add(once);
898
+ urgentWaiterListeners.add(once);
899
+ return remove;
900
+ }
901
+ };
902
+ const entry = {
903
+ urgent: options?.background !== true,
904
+ start: () => {
905
+ active++;
906
+ Promise.resolve().then(() => task(controller.signal, urgency)).then((value) => {
907
+ if (settled) return;
908
+ settled = true;
909
+ resolveTask(value);
910
+ }, (error) => {
911
+ if (settled) return;
912
+ settled = true;
913
+ rejectTask(error);
914
+ }).finally(release);
915
+ }
916
+ };
917
+ insert(entry);
918
+ drain();
919
+ if (entry.urgent && queue.includes(entry)) notifyUrgentWaiter();
920
+ return {
921
+ promise,
922
+ promote: () => {
923
+ if (entry.urgent) return;
924
+ entry.urgent = true;
925
+ for (const listener of [...promoteListeners]) listener();
926
+ const index = queue.indexOf(entry);
927
+ if (index === -1) return;
928
+ queue.splice(index, 1);
929
+ insert(entry);
930
+ notifyUrgentWaiter();
931
+ },
932
+ cancel: () => {
933
+ if (entry.urgent || settled) return false;
934
+ settled = true;
935
+ const index = queue.indexOf(entry);
936
+ if (index !== -1) queue.splice(index, 1);
937
+ else {
938
+ controller.abort();
939
+ release();
940
+ }
941
+ rejectTask(new BackgroundTaskCancelledError());
942
+ return true;
943
+ }
944
+ };
945
+ },
946
+ get activeCount() {
947
+ return active;
948
+ },
949
+ get pendingCount() {
950
+ return queue.length;
951
+ }
952
+ };
953
+ }
954
+
955
+ // src/provisioning/describe-type.ts
956
+ const describeTypeRetryDelays = {};
957
+ const MAX_THROTTLE_RETRIES = 4;
958
+ const DESCRIBE_TYPE_MAX_IN_FLIGHT = 20;
959
+ const describeTypeLimiter = createConcurrencyLimiter(20);
960
+ function describeTypeWithThrottleRetry(resourceType, client) {
961
+ return scheduleDescribeType(resourceType, { ...client && { client } }).promise;
962
+ }
963
+ function scheduleDescribeType(resourceType, options = {}) {
964
+ const { client, background } = options;
965
+ let cfn;
966
+ let clientError;
967
+ try {
968
+ cfn = client ?? getAwsClients().cloudFormation;
969
+ } catch (error) {
970
+ clientError = error;
971
+ }
972
+ return describeTypeLimiter.schedule((signal, urgency) => withRetry(() => {
973
+ if (cfn === void 0) throw clientError;
974
+ const command = new DescribeTypeCommand({
975
+ Type: "RESOURCE",
976
+ TypeName: resourceType
977
+ });
978
+ return urgency.urgent ? cfn.send(command) : cfn.send(command, { abortSignal: signal });
979
+ }, resourceType, {
980
+ maxRetries: MAX_THROTTLE_RETRIES,
981
+ isRetryable: (_message, error) => !signal.aborted && isThrottlingError(error),
982
+ logger: getLogger().child("DescribeType"),
983
+ sleep: describeTypeRetryDelays.sleep ?? ((ms) => backoffSleep(ms, signal, urgency))
984
+ }), { background: background === true });
985
+ }
986
+ function backoffSleep(ms, signal, urgency) {
987
+ if (urgency.urgent) return new Promise((resolve) => setTimeout(resolve, ms));
988
+ return new Promise((resolve, reject) => {
989
+ if (signal.aborted) {
990
+ reject(/* @__PURE__ */ new Error("DescribeType prefetch cancelled"));
991
+ return;
992
+ }
993
+ const timer = setTimeout(() => {
994
+ signal.removeEventListener("abort", onAbort);
995
+ stopFollowingPromotion();
996
+ resolve();
997
+ }, ms);
998
+ timer.unref?.();
999
+ const stopFollowingPromotion = urgency.onAwaited(() => timer.ref?.());
1000
+ const onAbort = () => {
1001
+ clearTimeout(timer);
1002
+ stopFollowingPromotion();
1003
+ reject(/* @__PURE__ */ new Error("DescribeType prefetch cancelled"));
1004
+ };
1005
+ signal.addEventListener("abort", onAbort, { once: true });
1006
+ });
1007
+ }
1008
+ function hasNoRegistrySchema(resourceType) {
1009
+ return resourceType === "AWS::CDK::Metadata" || resourceType === "AWS::CloudFormation::CustomResource" || resourceType.startsWith("Custom::");
1010
+ }
1011
+
1012
+ // src/provisioning/create-only-paths.ts
1013
+ function parseCreateOnlyPropertyPointers(createOnly) {
1014
+ const result = [];
1015
+ if (!Array.isArray(createOnly)) return result;
1016
+ for (const path of createOnly) {
1017
+ if (typeof path !== "string") continue;
1018
+ if (!path.startsWith("/properties/")) continue;
1019
+ const segments = path.slice(12).split("/").map(unescapeJsonPointerSegment).filter((segment) => segment.length > 0);
1020
+ if (segments.length > 0) result.push(segments);
1021
+ }
1022
+ return result;
1023
+ }
1024
+ function unescapeJsonPointerSegment(segment) {
1025
+ return segment.replace(/~1/g, "/").replace(/~0/g, "~");
1026
+ }
1027
+
1028
+ // src/provisioning/create-only-properties.ts
1029
+ const createOnlyPropertiesCache = /* @__PURE__ */ new Map();
1030
+ const inFlightLookups = /* @__PURE__ */ new Map();
1031
+ function getCreateOnlyPropertyPaths(resourceType) {
1032
+ return lookupCreateOnlyPropertyPaths(resourceType, false);
1033
+ }
1034
+ function cachedCreateOnlyPropertyPaths(resourceType) {
1035
+ if (hasNoRegistrySchema(resourceType)) return Promise.resolve([]);
1036
+ if (inFlightLookups.has(resourceType)) return void 0;
1037
+ const cached = createOnlyPropertiesCache.get(resourceType);
1038
+ if (cached !== void 0) return cached;
1039
+ const snapshot = CREATE_ONLY_PATHS_SNAPSHOT.get(resourceType);
1040
+ return snapshot === void 0 ? void 0 : Promise.resolve(snapshot);
1041
+ }
1042
+ function prefetchCreateOnlyPropertyPaths(resourceTypes) {
1043
+ const started = [];
1044
+ for (const type of new Set(resourceTypes)) {
1045
+ if (hasNoRegistrySchema(type) || createOnlyPropertiesCache.has(type)) continue;
1046
+ lookupCreateOnlyPropertyPaths(type, true).catch(() => {});
1047
+ const lookup = inFlightLookups.get(type);
1048
+ if (lookup) started.push([type, lookup]);
1049
+ }
1050
+ return { cancel: () => {
1051
+ for (const [type, lookup] of started.splice(0).reverse()) {
1052
+ if (inFlightLookups.get(type) !== lookup || !lookup.scheduled.cancel()) continue;
1053
+ inFlightLookups.delete(type);
1054
+ createOnlyPropertiesCache.delete(type);
1055
+ }
1056
+ } };
1057
+ }
1058
+ function templateResourceTypes(resources) {
1059
+ if (resources === null || typeof resources !== "object") return [];
1060
+ const types = /* @__PURE__ */ new Set();
1061
+ for (const resource of Object.values(resources)) {
1062
+ if (resource === null || typeof resource !== "object") continue;
1063
+ const type = resource.Type;
1064
+ if (typeof type === "string") types.add(type);
1065
+ }
1066
+ return [...types];
1067
+ }
1068
+ function lookupCreateOnlyPropertyPaths(resourceType, background) {
1069
+ if (hasNoRegistrySchema(resourceType)) return Promise.resolve([]);
1070
+ const cached = createOnlyPropertiesCache.get(resourceType);
1071
+ if (cached) {
1072
+ const inFlight = inFlightLookups.get(resourceType);
1073
+ if (!background && inFlight) {
1074
+ inFlight.awaited = true;
1075
+ inFlight.scheduled.promote();
1076
+ }
1077
+ return cached;
1078
+ }
1079
+ const scheduled = scheduleDescribeType(resourceType, { background });
1080
+ const lookup = {
1081
+ scheduled,
1082
+ awaited: !background
1083
+ };
1084
+ inFlightLookups.set(resourceType, lookup);
1085
+ const entry = scheduled.promise.then((response) => parseCreateOnlyResponse(resourceType, response.Schema)).catch((error) => {
1086
+ if (error instanceof BackgroundTaskCancelledError) return [];
1087
+ if (createOnlyPropertiesCache.get(resourceType) === entry) createOnlyPropertiesCache.delete(resourceType);
1088
+ return fallBackToSnapshot(resourceType, error, lookup.awaited);
1089
+ }).finally(() => {
1090
+ if (inFlightLookups.get(resourceType) === lookup) inFlightLookups.delete(resourceType);
1091
+ });
1092
+ createOnlyPropertiesCache.set(resourceType, entry);
1093
+ return entry;
1094
+ }
1095
+ function fallBackToSnapshot(resourceType, error, awaited) {
1096
+ const message = describeAwsFailure(error).detail;
1097
+ const child = getLogger().child("CreateOnlyProperties");
1098
+ const report = (line) => awaited ? child.warn(line) : child.debug(line);
1099
+ const snapshot = CREATE_ONLY_PATHS_SNAPSHOT.get(resourceType);
1100
+ if (snapshot) {
1101
+ report(`Failed to resolve create-only properties for ${resourceType} via cloudformation:DescribeType (${message}). Falling back to cdkd's bundled schema snapshot for this resource — it can lag AWS's current schema, so a property AWS has since made updatable may be classified as a replacement. Grant cloudformation:DescribeType to use the live schema.`);
1102
+ return snapshot;
1103
+ }
1104
+ report(`Failed to resolve create-only properties for ${resourceType} via cloudformation:DescribeType (${message}). Falling back to the registry-only replacement classification for this resource — an immutable-property change may be mis-classified as an in-place update. Grant cloudformation:DescribeType to enable schema-driven replacement detection.`);
1105
+ return [];
1106
+ }
1107
+ function createOnlyChangeRequiresReplacement(createOnlyPaths, topLevelKey, oldValue, newValue, valuesEqual) {
1108
+ for (const path of createOnlyPaths) {
1109
+ if (path[0] !== topLevelKey) continue;
1110
+ if (path.length === 1) return true;
1111
+ const oldSub = valueAtPath(oldValue, path.slice(1));
1112
+ const newSub = valueAtPath(newValue, path.slice(1));
1113
+ if (!oldSub.resolved || !newSub.resolved) return true;
1114
+ if (!valuesEqual(oldSub.value, newSub.value)) return true;
1115
+ }
1116
+ return false;
1117
+ }
1118
+ function valueAtPath(value, segments) {
1119
+ let current = value;
1120
+ for (const segment of segments) {
1121
+ if (segment === "*") return { resolved: false };
1122
+ if (current === void 0 || current === null) return {
1123
+ resolved: true,
1124
+ value: void 0
1125
+ };
1126
+ if (typeof current !== "object" || Array.isArray(current)) return { resolved: false };
1127
+ if (isIntrinsicShaped(current)) return { resolved: false };
1128
+ current = current[segment];
1129
+ }
1130
+ return {
1131
+ resolved: true,
1132
+ value: current
1133
+ };
1134
+ }
1135
+ function isIntrinsicShaped(value) {
1136
+ const keys = Object.keys(value);
1137
+ return keys.length === 1 && (keys[0] === "Ref" || keys[0].startsWith("Fn::"));
1138
+ }
1139
+ function parseRegistrySchema(resourceType, schema) {
1140
+ return parseJsonNamingNoBody(schema, "the DescribeType schema", (line) => getLogger().child("CreateOnlyProperties").debug(safeMsg`${resourceType}: ${line}`));
1141
+ }
1142
+ function parseCreateOnlyResponse(resourceType, schema) {
1143
+ const result = schema ? parseCreateOnlyPropertyPointers(parseRegistrySchema(resourceType, schema).createOnlyProperties) : [];
1144
+ getLogger().child("CreateOnlyProperties").debug(`Resolved ${result.length} create-only property paths for ${resourceType}` + (result.length > 0 ? `: ${result.map((p) => p.join(".")).join(", ")}` : ""));
1145
+ return result;
1146
+ }
1147
+
1148
+ // src/provisioning/secret-reference-immutable.ts
1149
+ const IDENTITY = maskerOrIdentity(void 0);
1150
+ async function unchangedBehindSecretReference(evidence) {
1151
+ const { resourceType, key, desired, previous, physicalName, maskSecrets } = evidence;
1152
+ if (physicalName !== void 0 && physicalName !== "") return isSecretDerivedValue(previous, IDENTITY) && desired === physicalName;
1153
+ if (!onlySecretReferencesDiffer(desired, previous, maskSecrets)) return false;
1154
+ return await engineReplacesOnAnyChange(resourceType, key);
1155
+ }
1156
+ let registry;
1157
+ async function engineReplacesOnAnyChange(resourceType, key) {
1158
+ registry ??= new ReplacementRulesRegistry();
1159
+ if (registry.isClassified(resourceType, key)) return registry.conditionalReplacementVerdict(resourceType, key, void 0, void 0) === void 0 && registry.requiresReplacement(resourceType, key, void 0, void 0);
1160
+ return (await getCreateOnlyPropertyPaths(resourceType)).some((path) => path.length === 1 && path[0] === key);
1161
+ }
1162
+ function onlySecretReferencesDiffer(desired, previous, maskSecrets) {
1163
+ return compare(desired, previous, maskerOrIdentity(maskSecrets)) === "references-only";
1164
+ }
1165
+ function compare(desired, previous, mask) {
1166
+ if (typeof previous === "string") {
1167
+ if (desired === previous) return "equal";
1168
+ return resolvesReference(desired, previous, mask) ? "references-only" : "differs";
1169
+ }
1170
+ if (Array.isArray(previous)) {
1171
+ if (!Array.isArray(desired) || desired.length !== previous.length) return "differs";
1172
+ return combine(previous.map((item, i) => compare(desired[i], item, mask)));
1173
+ }
1174
+ if (isPlainObject(previous)) {
1175
+ if (!isPlainObject(desired)) return "differs";
1176
+ if (!Object.keys(desired).every((k) => Object.prototype.hasOwnProperty.call(previous, k))) return "differs";
1177
+ return combine(Object.keys(previous).map((k) => compare(desired[k], previous[k], mask)));
1178
+ }
1179
+ return JSON.stringify(desired) === JSON.stringify(previous) ? "equal" : "differs";
1180
+ }
1181
+ function combine(verdicts) {
1182
+ if (verdicts.includes("differs")) return "differs";
1183
+ return verdicts.includes("references-only") ? "references-only" : "equal";
1184
+ }
1185
+ function resolvesReference(desired, previous, mask) {
1186
+ if (typeof desired !== "string" || desired === "") return false;
1187
+ const tokens = dynamicReferenceTokens(previous);
1188
+ if (tokens.length === 0) return false;
1189
+ if (mask(desired) === desired) return false;
1190
+ const literals = [];
1191
+ let rest = previous;
1192
+ for (const token of tokens) {
1193
+ const at = rest.indexOf(token);
1194
+ literals.push(rest.slice(0, at));
1195
+ rest = rest.slice(at + token.length);
1196
+ }
1197
+ literals.push(rest);
1198
+ const pattern = literals.map(escapeRegExp).join("[\\s\\S]*");
1199
+ return new RegExp(`^${pattern}$`).test(desired);
1200
+ }
1201
+ function isPlainObject(value) {
1202
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1203
+ }
1204
+ function escapeRegExp(text) {
1205
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1206
+ }
1207
+
1208
+ // src/provisioning/ec2-termination-protection.ts
1209
+ async function disableInstanceApiTermination(client, instanceId, logger) {
1210
+ try {
1211
+ await client.send(new ModifyInstanceAttributeCommand({
1212
+ InstanceId: instanceId,
1213
+ DisableApiTermination: { Value: false }
1214
+ }));
1215
+ logger.debug(`Disabled DisableApiTermination on EC2 Instance ${instanceId} before deletion`);
1216
+ return true;
1217
+ } catch (flipError) {
1218
+ logger.debug(`Could not disable DisableApiTermination on ${instanceId}: ${describeAwsFailure(flipError).detail}`);
1219
+ return false;
1220
+ }
1221
+ }
1222
+ function isTerminationProtectionPropagationError(message) {
1223
+ return /may not be terminated|disableApiTermination/i.test(message);
1224
+ }
1225
+ async function observeThenDisableInstanceApiTermination(client, instanceId, flip, logger) {
1226
+ let observedOn = false;
1227
+ try {
1228
+ await observeThenDisableProtection({
1229
+ flip,
1230
+ logger,
1231
+ physicalId: instanceId,
1232
+ guardName: "DisableApiTermination",
1233
+ observe: async () => {
1234
+ observedOn = (await client.send(new DescribeInstanceAttributeCommand({
1235
+ InstanceId: instanceId,
1236
+ Attribute: "disableApiTermination"
1237
+ }))).DisableApiTermination?.Value === true;
1238
+ return observedOn;
1239
+ },
1240
+ disable: async () => {
1241
+ if (!await disableInstanceApiTermination(client, instanceId, logger)) throw new Error("the DisableApiTermination flip-off was not accepted");
1242
+ }
1243
+ });
1244
+ } catch {}
1245
+ return observedOn;
1246
+ }
1247
+ async function reDisableInstanceApiTermination(client, instanceId, flip, observedOn, logger) {
1248
+ if (await disableInstanceApiTermination(client, instanceId, logger) && observedOn) flip.flippedOffByThisRun = true;
1249
+ }
1250
+ async function reEnableInstanceApiTermination(client, instanceId) {
1251
+ await client.send(new ModifyInstanceAttributeCommand({
1252
+ InstanceId: instanceId,
1253
+ DisableApiTermination: { Value: true }
1254
+ }));
1255
+ }
1256
+ function ec2InstanceProtectionSite(instanceId, region) {
1257
+ return {
1258
+ subject: "EC2 Instance",
1259
+ guardName: "DisableApiTermination",
1260
+ noun: "instance",
1261
+ isNotFound: (error) => typeof error === "object" && error !== null && error.name === "InvalidInstanceID.NotFound",
1262
+ notFoundMeaning: "EC2 answered InvalidInstanceID.NotFound. That most commonly means the instance is gone, and it can also mean it is not in this region or account.",
1263
+ commands: () => {
1264
+ const aws = pasteableAwsCommand();
1265
+ const regionArg = region ? aws` --region ${region}` : aws``;
1266
+ const restore = aws`aws ec2 modify-instance-attribute --instance-id ${instanceId}${regionArg} --disable-api-termination`;
1267
+ return {
1268
+ check: aws`aws ec2 describe-instance-attribute --instance-id ${instanceId}${regionArg} --attribute disableApiTermination`.render(),
1269
+ restoreAfterNotFound: restore.render(),
1270
+ restoreLive: restore.render()
1271
+ };
1272
+ }
1273
+ };
1274
+ }
1275
+
1276
+ export { parseFailureDebugDetail as A, phaseTimingsEnabled as C, timePhaseSync as D, timePhase as E, utf8ByteLength as M, describeJsonParseFailure as O, phaseScopeForStack as S, renderPhaseTimings as T, hasNoRegistrySchema as _, reDisableInstanceApiTermination as a, CREATE_ONLY_PATHS_SNAPSHOT as b, unchangedBehindSecretReference as c, getCreateOnlyPropertyPaths as d, isIntrinsicShaped as f, describeTypeWithThrottleRetry as g, parseCreateOnlyPropertyPointers as h, observeThenDisableInstanceApiTermination as i, parseJsonNamingNoBody as j, jsonParseFailureStandIn as k, cachedCreateOnlyPropertyPaths as l, templateResourceTypes as m, ec2InstanceProtectionSite as n, reEnableInstanceApiTermination as o, prefetchCreateOnlyPropertyPaths as p, isTerminationProtectionPropagationError as r, onlySecretReferencesDiffer as s, disableInstanceApiTermination as t, createOnlyChangeRequiresReplacement as u, IAM_PROPAGATION_MAX_DELAY_MS as v, recordPhase as w, PhaseClock as x, withRetry as y };
1277
+ //# sourceMappingURL=ec2-termination-protection-BM1Zt3Fn.js.map