@cdkd/cli 0.373.1 → 0.373.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/{ambient-client-defaults-BLKND30a.js → ambient-client-defaults-ChOenyD2.js} +18 -4
  2. package/dist/ambient-client-defaults-ChOenyD2.js.map +1 -0
  3. package/dist/{asg-provider-DXL1CE4m.js → asg-provider-Bfinx42n.js} +8 -8
  4. package/dist/{asg-provider-DXL1CE4m.js.map → asg-provider-Bfinx42n.js.map} +1 -1
  5. package/dist/cli.js +3 -3
  6. package/dist/{replacement-rules-BkUZIP44.js → created-resource-sink-D7iM5jwM.js} +1394 -1474
  7. package/dist/created-resource-sink-D7iM5jwM.js.map +1 -0
  8. package/dist/{custom-resource-runtime-DK4-5kRC.js → custom-resource-runtime-9fjsDVrs.js} +6 -6
  9. package/dist/{custom-resource-runtime-DK4-5kRC.js.map → custom-resource-runtime-9fjsDVrs.js.map} +1 -1
  10. package/dist/{db-associated-roles-zv71gI1O.js → db-associated-roles-Bn8HCQ2r.js} +2 -2
  11. package/dist/{db-associated-roles-zv71gI1O.js.map → db-associated-roles-Bn8HCQ2r.js.map} +1 -1
  12. package/dist/{delete-started-E38sSyUX.js → delete-started-CiTP5c3_.js} +4 -4
  13. package/dist/{delete-started-E38sSyUX.js.map → delete-started-CiTP5c3_.js.map} +1 -1
  14. package/dist/{deploy-engine-BDueF79_.js → deploy-engine-D7Iv9v8e.js} +3573 -2888
  15. package/dist/deploy-engine-D7Iv9v8e.js.map +1 -0
  16. package/dist/{ec2-termination-protection-DI-aPxET.js → ec2-termination-protection-BXy91mrW.js} +3 -3
  17. package/dist/{ec2-termination-protection-DI-aPxET.js.map → ec2-termination-protection-BXy91mrW.js.map} +1 -1
  18. package/dist/{ecr-uri-kW_K5U02.js → ecr-uri-DUDwEekn.js} +2 -2
  19. package/dist/{ecr-uri-kW_K5U02.js.map → ecr-uri-DUDwEekn.js.map} +1 -1
  20. package/dist/{emr-cluster-provider-BcqnxYsN.js → emr-cluster-provider-MokUAEGh.js} +11 -11
  21. package/dist/emr-cluster-provider-MokUAEGh.js.map +1 -0
  22. package/dist/{expected-bucket-owner-j5BCLzAB.js → expected-bucket-owner-BrzB1C4p.js} +2 -2
  23. package/dist/{expected-bucket-owner-j5BCLzAB.js.map → expected-bucket-owner-BrzB1C4p.js.map} +1 -1
  24. package/dist/{iam-role-provider-BlUbRjQo.js → iam-role-provider-CB--BYVm.js} +12 -12
  25. package/dist/{iam-role-provider-BlUbRjQo.js.map → iam-role-provider-CB--BYVm.js.map} +1 -1
  26. package/dist/{identity-read-denied-BhnkMyxk.js → identity-read-denied-CoeMBkCz.js} +5 -6
  27. package/dist/identity-read-denied-CoeMBkCz.js.map +1 -0
  28. package/dist/{image-plan-CUvO0Qe2.js → image-plan-RNp8hqc4.js} +8 -8
  29. package/dist/{image-plan-CUvO0Qe2.js.map → image-plan-RNp8hqc4.js.map} +1 -1
  30. package/dist/index.d.ts +13 -1
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +5 -5
  33. package/dist/{logger-B673mhBe.js → logger-Bfz63gW5.js} +2 -2
  34. package/dist/{logger-B673mhBe.js.map → logger-Bfz63gW5.js.map} +1 -1
  35. package/dist/{neptune-provider-BOIjF_i3.js → neptune-provider-BFwovty1.js} +9 -9
  36. package/dist/{neptune-provider-BOIjF_i3.js.map → neptune-provider-BFwovty1.js.map} +1 -1
  37. package/dist/{program-avOxa_7W.js → program-DR3X8-7x.js} +563 -233
  38. package/dist/program-DR3X8-7x.js.map +1 -0
  39. package/dist/{provider-classes-BMrkl7zN.js → provider-classes-BNZGFwNO.js} +375 -129
  40. package/dist/provider-classes-BNZGFwNO.js.map +1 -0
  41. package/dist/{rds-provider-DD8ka8NG.js → rds-provider-evebINWq.js} +13 -13
  42. package/dist/{rds-provider-DD8ka8NG.js.map → rds-provider-evebINWq.js.map} +1 -1
  43. package/dist/{read-replica-Ddvkib9A.js → read-replica-BGoRAh10.js} +3 -3
  44. package/dist/{read-replica-Ddvkib9A.js.map → read-replica-BGoRAh10.js.map} +1 -1
  45. package/dist/{redacted-delete-address-CkcTwr-O.js → redacted-delete-address-rTL8ikg4.js} +5 -5
  46. package/dist/redacted-delete-address-rTL8ikg4.js.map +1 -0
  47. package/dist/replacement-rules-roVU6gYR.js +1967 -0
  48. package/dist/replacement-rules-roVU6gYR.js.map +1 -0
  49. package/dist/{resource-deadline-B2z0yyKo.js → resource-deadline-B4Rp-3f7.js} +2 -2
  50. package/dist/{resource-deadline-B2z0yyKo.js.map → resource-deadline-B4Rp-3f7.js.map} +1 -1
  51. package/dist/{restore-source-guard-1UD7ucv5.js → restore-source-guard-Dz_vQPiM.js} +5 -5
  52. package/dist/restore-source-guard-Dz_vQPiM.js.map +1 -0
  53. package/dist/{run-cli-Dm2l-FUd.js → run-cli-vKsR6JeT.js} +2 -2
  54. package/dist/{run-cli-Dm2l-FUd.js.map → run-cli-vKsR6JeT.js.map} +1 -1
  55. package/dist/{secret-reference-immutable-Bk60ZfqH.js → secret-reference-immutable-BF02Wobz.js} +108 -10
  56. package/dist/{secret-reference-immutable-Bk60ZfqH.js.map → secret-reference-immutable-BF02Wobz.js.map} +1 -1
  57. package/dist/{settle-own-write-members-YQxWAEvB.js → settle-own-write-members-CF-RPYMD.js} +10 -10
  58. package/dist/{settle-own-write-members-YQxWAEvB.js.map → settle-own-write-members-CF-RPYMD.js.map} +1 -1
  59. package/dist/{tag-list-C8pMq_W3.js → tag-list-DbmXev9Z.js} +4 -4
  60. package/dist/{tag-list-C8pMq_W3.js.map → tag-list-DbmXev9Z.js.map} +1 -1
  61. package/dist/{version-D2qdiEuf.js → version-CP9RYTCy.js} +2 -2
  62. package/dist/{version-D2qdiEuf.js.map → version-CP9RYTCy.js.map} +1 -1
  63. package/package.json +1 -1
  64. package/dist/ambient-client-defaults-BLKND30a.js.map +0 -1
  65. package/dist/created-resource-sink-DlVo2nqB.js +0 -1397
  66. package/dist/created-resource-sink-DlVo2nqB.js.map +0 -1
  67. package/dist/deploy-engine-BDueF79_.js.map +0 -1
  68. package/dist/emr-cluster-provider-BcqnxYsN.js.map +0 -1
  69. package/dist/identity-read-denied-BhnkMyxk.js.map +0 -1
  70. package/dist/program-avOxa_7W.js.map +0 -1
  71. package/dist/provider-classes-BMrkl7zN.js.map +0 -1
  72. package/dist/redacted-delete-address-CkcTwr-O.js.map +0 -1
  73. package/dist/replacement-rules-BkUZIP44.js.map +0 -1
  74. package/dist/restore-source-guard-1UD7ucv5.js.map +0 -1
@@ -1,1397 +0,0 @@
1
- import { A as displayStackName, M as isPlainIdent, N as plainIdentOr, P as safeMsg, S as SECRET_REF_MAX_CODE_POINTS, _ as shellQuote, d as pasteableCommand, j as isPasteableIdent, k as displaySafe, m as proseQuoted, p as plainOrDescribed, r as SHELL_ACTIVE, s as commandHole, u as isInertUnquoted, w as UNRENDERABLE } from "./version-D2qdiEuf.js";
2
- import { J as getCurrentStackName, u as describeAwsFailure } from "./logger-B673mhBe.js";
3
- import { B as retryClassificationText, D as markReplayMayCollide, F as isAmbiguousOutcomeError, H as isMarkedNonRetryable, R as isRetryableTransientError, at as ProvisioningError, x as hasReplayMayCollide, z as isTransientServerError } from "./ambient-client-defaults-BLKND30a.js";
4
- import { a as getAssumedRoleCredentials, f as ambientRegion, i as awsEndpointOverrideUrl } from "./aws-client-defaults-DAebi99J.js";
5
- import { AsyncLocalStorage } from "node:async_hooks";
6
-
7
- // src/state/record-keys.ts
8
- function injectivePairKey(first, second) {
9
- return JSON.stringify([first, second]);
10
- }
11
- function injectiveKey(...parts) {
12
- return JSON.stringify(parts);
13
- }
14
- function injectiveKeyPrefix(first) {
15
- return JSON.stringify([first]).slice(0, -1) + ",";
16
- }
17
- function producerRecordKey(stackName, region) {
18
- return injectivePairKey(stackName, region);
19
- }
20
- function producerCoordinateKey(stackName, exportOrOutputName) {
21
- return injectivePairKey(stackName, exportOrOutputName);
22
- }
23
-
24
- // src/utils/pasteable-aws-profile.ts
25
- let explicitProfile;
26
- let emulatorCaBundle;
27
- function setPasteableAwsCaBundle(path) {
28
- emulatorCaBundle = path;
29
- }
30
- function setPasteableAwsProfile(profile) {
31
- explicitProfile = profile;
32
- }
33
- function pasteableAwsProfileFlag() {
34
- const emulator = awsEndpointOverrideUrl();
35
- if (emulator !== void 0) {
36
- const endpoint = `--endpoint-url ${isInertUnquoted(emulator) ? emulator : commandHole("endpoint-url")}`;
37
- const ca = emulatorCaBundle;
38
- if (ca === void 0) return endpoint;
39
- return `${endpoint} --ca-bundle ${isInertUnquoted(ca) ? ca : commandHole("ca-bundle")}`;
40
- }
41
- if (getAssumedRoleCredentials() !== void 0) return `--profile ${commandHole("role-profile")}`;
42
- const profile = explicitProfile;
43
- if (profile === void 0 || profile === "") return "";
44
- if (displaySafe(profile) !== profile || profile.startsWith("-") || SHELL_ACTIVE.test(profile)) return `--profile ${commandHole("profile")}`;
45
- return `--profile ${shellQuote(profile)}`;
46
- }
47
- function withPasteableAwsProfile(literal) {
48
- const flag = pasteableAwsProfileFlag();
49
- if (flag === "") return literal;
50
- return literal.replace(/(^|[\s;&|(])aws (?=[a-z]|$)/g, (_m, pre) => `${pre}aws ${flag} `);
51
- }
52
-
53
- // src/state/state-prefix.ts
54
- const DEFAULT_STATE_PREFIX = "cdkd";
55
- const CUSTOM_RESOURCE_RESPONSE_PREFIX = "custom-resource-responses";
56
- const WAIT_CONDITION_SIGNAL_PREFIX = "wait-condition-signals";
57
-
58
- // src/state/lock-contention-message.ts
59
- function formatLockExpiry(expiresAt) {
60
- if (!Number.isFinite(expiresAt)) return "expires at an unknown time";
61
- const remainingMs = expiresAt - Date.now();
62
- return remainingMs > 0 ? `expires in ${formatDuration(remainingMs)}` : `expired ${formatDuration(-remainingMs)} ago`;
63
- }
64
- const LOCK_OWNER_DESCRIBED = "a lock owner that is not a plain identifier";
65
- const LOCK_OPERATION_DESCRIBED = "a lock operation that is not a plain identifier";
66
- function formatLockOwner(owner) {
67
- if (owner === "") return "an unnamed holder";
68
- return owner.includes(",") ? LOCK_OWNER_DESCRIBED : plainIdentOr(owner, LOCK_OWNER_DESCRIBED);
69
- }
70
- function formatLockOperation(operation) {
71
- return operation.includes(",") ? LOCK_OPERATION_DESCRIBED : plainIdentOr(operation, LOCK_OPERATION_DESCRIBED);
72
- }
73
- function formatDuration(ms) {
74
- const seconds = Math.floor(ms / 1e3);
75
- if (seconds < 60) return `${seconds}s`;
76
- return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
77
- }
78
- function buildForceUnlockCommand(stackName, region, recovery) {
79
- const recoveryFlags = recoveryCommandFlags(recovery);
80
- const built = pasteableCommand("cdkd force-unlock", region === void 0 ? [{
81
- value: stackName,
82
- hole: "stack",
83
- opts: { plainIdent: true }
84
- }] : [{
85
- value: stackName,
86
- hole: "stack",
87
- opts: { plainIdent: true }
88
- }, {
89
- flag: "--stack-region",
90
- value: region,
91
- hole: "region",
92
- opts: { plainIdent: true }
93
- }], recoveryFlags.flags);
94
- if (!built.exact || !recoveryFlags.exact) return "";
95
- return built.command;
96
- }
97
- function recoveryCommandFlags(recovery) {
98
- const gated = (value) => {
99
- const v = sanitizeRecoveryValue(value);
100
- return {
101
- text: v.text,
102
- exact: v.exact && isInertUnquoted(v.text)
103
- };
104
- };
105
- const profile = gated(recovery?.profile);
106
- const stateBucket = gated(recovery?.stateBucket);
107
- const statePrefix = gated(recovery?.statePrefix);
108
- const flags = [];
109
- if (profile.text || !profile.exact) flags.push(profile.exact ? `--profile ${shellQuote(profile.text)}` : `--profile ${commandHole("profile")}`);
110
- if (stateBucket.text || !stateBucket.exact) flags.push(stateBucket.exact ? `--state-bucket ${shellQuote(stateBucket.text)}` : `--state-bucket ${commandHole("bucket")}`);
111
- const prefix = recovery?.statePrefix;
112
- if (prefix !== void 0 && prefix !== "cdkd") flags.push(statePrefix.exact ? `--state-prefix ${shellQuote(statePrefix.text)}` : `--state-prefix ${commandHole("prefix")}`);
113
- return {
114
- flags,
115
- exact: profile.exact && stateBucket.exact && statePrefix.exact
116
- };
117
- }
118
- function sanitizeRecoveryValue(value) {
119
- if (value === void 0) return {
120
- text: "",
121
- exact: true
122
- };
123
- const text = displaySafe(value);
124
- return {
125
- text,
126
- exact: text === value
127
- };
128
- }
129
- const UNREPRODUCIBLE_LOCK_VALUES = "the name, region, profile, state bucket or state prefix";
130
- const UNREPRODUCIBLE_LOCK_CLAUSE = `Inspect the lock object directly: ${UNREPRODUCIBLE_LOCK_VALUES} recorded for this stack cannot be reproduced safely on a command line (changed by sanitizing, unrenderable, empty, too long, not a plain identifier, beginning with '-', which cdkd refuses rather than risk it parsing as an option, or holding whitespace or a character a shell treats specially), so no command is shown: one built from it could address a different lock or run part of it as shell.`;
131
- function forceQuitRecoveryClause(stackName, region, recovery) {
132
- const command = buildForceUnlockCommand(stackName, region, recovery);
133
- return command ? ` If the next run reports a lock, run: ${command}` : ` ${UNREPRODUCIBLE_LOCK_CLAUSE}`;
134
- }
135
- async function buildLockContentionMessage(args) {
136
- const { lockManager, stackName, region, subject = "stack", recovery, heldClause, suffix } = args;
137
- let held = heldClause ?? "another cdkd process holds it";
138
- let sawHolder = false;
139
- try {
140
- const info = await lockManager.getLockInfo(stackName, region);
141
- if (info) {
142
- const operation = info.operation ? `, operation: ${formatLockOperation(info.operation)}` : "";
143
- const expires = formatLockExpiry(info.expiresAt);
144
- const owner = displaySafe(info.owner);
145
- const holder = owner ? `held by ${formatLockOwner(owner)}${operation}` : `held by an unnamed holder`;
146
- held = `${heldClause ? `${heldClause} — ` : ""}${holder}, ${expires}`;
147
- if (owner) sawHolder = true;
148
- }
149
- } catch {}
150
- const advice = sawHolder ? `That process is still running — wait for it to finish. Only if you are certain it is gone` : `Wait for it to finish, or if you are certain no other process is active`;
151
- const recoveryCommand = buildForceUnlockCommand(stackName, region, recovery);
152
- const safeRegion = displaySafe(region, { asciiOnly: true }) || "<unrenderable>";
153
- const head = `Could not acquire lock for ${subject} ${displayStackName(stackName)} (${safeRegion}) — ${held}.` + (suffix ? ` ${suffix}` : "");
154
- if (!recoveryCommand) return `${head} ${advice}. No recovery command can be shown: ${UNREPRODUCIBLE_LOCK_VALUES} recorded for this lock cannot be reproduced safely on a command line (changed by sanitizing, unrenderable, empty, too long, not a plain identifier, beginning with '-', which cdkd refuses rather than risk it parsing as an option, or holding whitespace or a character a shell treats specially), so no command is shown: one built from it could address a different lock or run part of it as shell — inspect the lock object directly.`;
155
- return `${head} ${advice}, run: ${recoveryCommand}`;
156
- }
157
-
158
- // src/provisioning/auxiliary-failure.ts
159
- const AUXILIARY_LOGICAL_ID_SUFFIX = "/auxiliary";
160
- const MAX_DEPTH$1 = 5;
161
- function auxiliaryLogicalId(ownerLogicalId) {
162
- return `${ownerLogicalId}${AUXILIARY_LOGICAL_ID_SUFFIX}`;
163
- }
164
- const RETRY_AUXILIARY_OWNER = "withRetry";
165
- function isAuxiliaryMarkOf(link, ownerLogicalId) {
166
- try {
167
- if (typeof link !== "object" && typeof link !== "function" || link === null) return false;
168
- const own = Object.getOwnPropertyDescriptor(link, "logicalId");
169
- return isAuxiliaryMark(own) && own?.value === auxiliaryLogicalId(ownerLogicalId);
170
- } catch {
171
- return false;
172
- }
173
- }
174
- function isAuxiliaryMark(descriptor) {
175
- return descriptor !== void 0 && descriptor.enumerable === false && descriptor.writable === false && typeof descriptor.value === "string" && descriptor.value.endsWith(AUXILIARY_LOGICAL_ID_SUFFIX);
176
- }
177
- function isAuxiliaryFailure(error) {
178
- try {
179
- let current = error;
180
- for (let depth = 0; depth < MAX_DEPTH$1 && typeof current === "object" && current !== null; depth++) {
181
- if (isAuxiliaryMark(Object.getOwnPropertyDescriptor(current, "logicalId"))) return true;
182
- current = current.cause;
183
- }
184
- } catch {}
185
- return false;
186
- }
187
- const CREATED_BEFORE_FAILURE = Symbol.for("cdkd.createdBeforeFailure");
188
- function markCreatedBeforeFailure(error, ownerLogicalId, resourceType, physicalId, createdResourceIdentity) {
189
- try {
190
- if (typeof error !== "object" || error === null || !Object.isExtensible(error)) return error;
191
- if (physicalId === "") return error;
192
- Object.defineProperty(error, CREATED_BEFORE_FAILURE, {
193
- value: Object.freeze({
194
- logicalId: ownerLogicalId,
195
- resourceType,
196
- physicalId,
197
- ...typeof createdResourceIdentity === "string" && createdResourceIdentity !== "" && { createdResourceIdentity }
198
- }),
199
- enumerable: false,
200
- writable: false,
201
- configurable: true
202
- });
203
- } catch {}
204
- return error;
205
- }
206
- function createdMarkOn(link) {
207
- const value = link[CREATED_BEFORE_FAILURE];
208
- if (typeof value !== "object" || value === null) return void 0;
209
- const { logicalId, resourceType, physicalId, createdResourceIdentity } = value;
210
- if (typeof logicalId !== "string" || typeof resourceType !== "string" || typeof physicalId !== "string" || physicalId === "") return;
211
- return typeof createdResourceIdentity === "string" && createdResourceIdentity !== "" ? {
212
- logicalId,
213
- resourceType,
214
- physicalId,
215
- createdResourceIdentity
216
- } : {
217
- logicalId,
218
- resourceType,
219
- physicalId
220
- };
221
- }
222
- function createdBeforeFailure(error, logicalId, resourceType) {
223
- return anchoredCreatedMark(error, logicalId, resourceType)?.physicalId;
224
- }
225
- function createdResourceIdentityBeforeFailure(error, logicalId, resourceType) {
226
- return anchoredCreatedMark(error, logicalId, resourceType)?.createdResourceIdentity;
227
- }
228
- function anchoredCreatedMark(error, logicalId, resourceType) {
229
- try {
230
- let current = error;
231
- for (let depth = 0; depth < 10 && typeof current === "object" && current !== null; depth++) {
232
- const mark = createdMarkOn(current);
233
- if (mark) return mark.logicalId === logicalId && mark.resourceType === resourceType ? mark : void 0;
234
- const own = Object.getOwnPropertyDescriptor(current, "logicalId");
235
- if (typeof own?.value === "string" && own.value !== logicalId && !isAuxiliaryMarkOf(current, logicalId)) return;
236
- current = current.cause;
237
- }
238
- } catch {}
239
- }
240
- function clearCreatedBeforeFailure(error) {
241
- try {
242
- let current = error;
243
- for (let depth = 0; depth < 10 && typeof current === "object" && current !== null; depth++) {
244
- if (Object.getOwnPropertyDescriptor(current, CREATED_BEFORE_FAILURE)?.configurable) delete current[CREATED_BEFORE_FAILURE];
245
- current = current.cause;
246
- }
247
- } catch {}
248
- return error;
249
- }
250
- function hasCreatedBeforeFailure(error) {
251
- try {
252
- let current = error;
253
- for (let depth = 0; depth < 10 && typeof current === "object" && current !== null; depth++) {
254
- if (createdMarkOn(current)) return true;
255
- current = current.cause;
256
- }
257
- } catch {}
258
- return false;
259
- }
260
- function firstCreatedMark(error) {
261
- let current = error;
262
- for (let depth = 0; depth < 10 && typeof current === "object" && current !== null; depth++) {
263
- const mark = createdMarkOn(current);
264
- if (mark) return mark;
265
- current = current.cause;
266
- }
267
- }
268
- const SUPERSEDES_EARLIER_CREATE = Symbol.for("cdkd.supersedesEarlierCreate");
269
- function markSupersedesEarlierCreate(error) {
270
- try {
271
- if (typeof error !== "object" || error === null || !Object.isExtensible(error)) return error;
272
- Object.defineProperty(error, SUPERSEDES_EARLIER_CREATE, {
273
- value: true,
274
- enumerable: false,
275
- writable: false,
276
- configurable: true
277
- });
278
- } catch {}
279
- return error;
280
- }
281
- function supersedesEarlierCreate(error) {
282
- let current = error;
283
- for (let depth = 0; depth < 10 && typeof current === "object" && current !== null; depth++) {
284
- if (current[SUPERSEDES_EARLIER_CREATE] === true) return true;
285
- current = current.cause;
286
- }
287
- return false;
288
- }
289
- function replayMadeAnotherResource(earlier, later) {
290
- try {
291
- const before = firstCreatedMark(earlier);
292
- const after = firstCreatedMark(later);
293
- if (before === void 0 || after === void 0 || before.logicalId !== after.logicalId || before.resourceType !== after.resourceType || supersedesEarlierCreate(later)) return false;
294
- const members = (id) => id.split(",").filter((member) => member !== "");
295
- const earlierMembers = new Set(members(before.physicalId));
296
- return !members(after.physicalId).some((member) => earlierMembers.has(member));
297
- } catch {
298
- return false;
299
- }
300
- }
301
- function carryCreatedBeforeFailure(from, to) {
302
- try {
303
- if (typeof to !== "object" || to === null) return to;
304
- let current = from;
305
- let mark;
306
- for (let depth = 0; depth < 10 && typeof current === "object" && current !== null && !mark; depth++) {
307
- mark = createdMarkOn(current);
308
- current = current.cause;
309
- }
310
- if (!mark) return to;
311
- let probe = to;
312
- for (let depth = 0; depth < 10 && typeof probe === "object" && probe !== null; depth++) {
313
- if (createdMarkOn(probe)) return to;
314
- probe = probe.cause;
315
- }
316
- return markCreatedBeforeFailure(to, mark.logicalId, mark.resourceType, mark.physicalId, mark.createdResourceIdentity);
317
- } catch {
318
- return to;
319
- }
320
- }
321
- function markAuxiliaryFailure(error, ownerLogicalId) {
322
- try {
323
- let current = error;
324
- for (let depth = 0; depth < MAX_DEPTH$1 && typeof current === "object" && current !== null; depth++) {
325
- const own = Object.getOwnPropertyDescriptor(current, "logicalId");
326
- if (typeof own?.value === "string") {
327
- if (isAuxiliaryMark(own)) return error;
328
- } else {
329
- if (Object.isExtensible(current) && own?.configurable !== false) Object.defineProperty(current, "logicalId", {
330
- value: auxiliaryLogicalId(ownerLogicalId),
331
- enumerable: false,
332
- writable: false,
333
- configurable: true
334
- });
335
- return error;
336
- }
337
- current = current.cause;
338
- }
339
- } catch {}
340
- return error;
341
- }
342
-
343
- // src/provisioning/masked-retry-logger.ts
344
- function maskerOrIdentity(maskSecrets) {
345
- return maskSecrets ?? ((text) => text);
346
- }
347
- function createMaskedRetryLogger(logger, maskSecrets) {
348
- const mask = maskerOrIdentity(maskSecrets);
349
- return {
350
- debug: (message) => logger.debug(mask(message)),
351
- warn: (message) => logger.warn(mask(message))
352
- };
353
- }
354
- function createMaskedLogSinks(logger, maskSecrets) {
355
- const mask = maskerOrIdentity(maskSecrets);
356
- return {
357
- mask,
358
- value: (value) => mask(String(value)),
359
- debug: (message) => logger.debug(mask(message)),
360
- warn: (message) => logger.warn(mask(message))
361
- };
362
- }
363
- function isSecretDerivedValue(raw, mask) {
364
- return typeof raw === "string" && raw !== "" && (mask(raw) !== raw || raw.includes("{{resolve:") || raw === "***");
365
- }
366
- function withDerivedNameMasks(logger, sinks, pairs) {
367
- const base = sinks.mask;
368
- const derivedNames = pairs.filter((pair) => typeof pair[0] === "string" && pair[0] !== "" && typeof pair[1] === "string" && pair[1] !== "" && isSecretDerivedValue(pair[0], base)).map(([, derived]) => derived);
369
- if (derivedNames.length === 0) return sinks;
370
- const mask = (text) => {
371
- const masked = base(text);
372
- const needles = [];
373
- for (const derived of new Set(derivedNames)) {
374
- if (derived.length < 4) {
375
- needles.push(derived);
376
- continue;
377
- }
378
- const rendered = base(derived);
379
- if (rendered === "***") continue;
380
- for (let i = text.indexOf(derived); i !== -1;) {
381
- const j = i + derived.length;
382
- if (masked !== base(text.slice(0, i)) + rendered + base(text.slice(j))) return "***";
383
- i = text.indexOf(derived, i + 1);
384
- }
385
- needles.push(rendered);
386
- }
387
- let out = masked;
388
- for (const needle of needles.sort((a, b) => b.length - a.length)) out = out.split(needle).join("***");
389
- return out;
390
- };
391
- return {
392
- mask,
393
- value: (value) => mask(String(value)),
394
- debug: (message) => logger.debug(mask(message)),
395
- warn: (message) => logger.warn(mask(message))
396
- };
397
- }
398
- const MASK_WALK_MAX_DEPTH = 8;
399
- const MASK_WALK_DEPTH_CAP_MARKER = "***";
400
- const BASE_MASKER_SUBSTRING_FLOOR = 4;
401
- function maskDeep(value, mask, depth = 0) {
402
- if (typeof value === "string") return mask(value);
403
- if (depth >= 8) return "***";
404
- if (Array.isArray(value)) return value.map((entry) => maskDeep(entry, mask, depth + 1));
405
- if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [mask(k), maskDeep(v, mask, depth + 1)]));
406
- return value;
407
- }
408
-
409
- // src/provisioning/state-orphan-remedy.ts
410
- function stateOrphanRecordRemedy(context, logicalId) {
411
- const resource = {
412
- flag: "--resource",
413
- value: logicalId,
414
- hole: "logicalId",
415
- opts: { plainIdent: true }
416
- };
417
- const target = [{ hole: "stack" }, {
418
- flag: "--stack-region",
419
- hole: "region"
420
- }];
421
- if (context?.stackDestroy === true) {
422
- const resourceArg = `--resource ${pasteableCommand("cdkd state orphan", [resource]).withheld.length === 0 ? logicalId : commandHole("logicalId")}`;
423
- return `${pasteableCommand("cdkd state orphan", [...target]).command}, which drops every record the stack still has in that region, not just this one (add ${proseQuoted(resourceArg)} to drop only this one)`;
424
- }
425
- return `${pasteableCommand("cdkd state orphan", [...target, resource]).command}, which drops only this record — never run it without --resource on a stack that is still deployed, where that drops every resource's record and the next deploy re-creates or collides with all of them`;
426
- }
427
-
428
- // src/provisioning/composite-id.ts
429
- const COMPOSITE_ID_SEPARATOR = "|";
430
- function canonicalizeRoute53QueryName(name) {
431
- const lowered = name.toLowerCase().replaceAll("*", "\\052").replaceAll("|", "\\174");
432
- return lowered.endsWith(".") ? lowered : `${lowered}.`;
433
- }
434
- function segmentAfterAnchor(physicalId, anchor) {
435
- if (typeof anchor !== "string" || anchor === "") return void 0;
436
- const prefix = `${anchor}${"|"}`;
437
- if (!physicalId.startsWith(prefix)) return void 0;
438
- const rest = physicalId.slice(prefix.length);
439
- return rest === "" ? void 0 : rest;
440
- }
441
- const QUOTABLE_VALUE = /^(?:[A-Za-z0-9:_@./+=,~|*-]+| *)$/;
442
- function quotedOr(value, quote, description) {
443
- return QUOTABLE_VALUE.test(value) ? `${quote}${value}${quote}` : description;
444
- }
445
- function logicalIdShown(logicalId) {
446
- return plainOrDescribed(logicalId, "logical id");
447
- }
448
- const RESOURCE_TYPE_SHAPE = /^[A-Za-z0-9]+(?:::[A-Za-z0-9_@-]+)+$/;
449
- function resourceTypeShown(resourceType) {
450
- return RESOURCE_TYPE_SHAPE.test(resourceType) && plainIdentOr(resourceType, "") === resourceType ? resourceType : "a resource type that is not a plain identifier";
451
- }
452
- function idShape(segments) {
453
- return segments.map((segment) => `<${segment.name}>`).join("|");
454
- }
455
- function compositeIdSeparatorRefusal(resourceType, logicalId, segments, maskSecrets) {
456
- const offending = segments.filter((segment) => String(segment.value).includes("|"));
457
- if (offending.length === 0) return void 0;
458
- const mask = maskerOrIdentity(maskSecrets);
459
- const named = offending.map((segment) => `${segment.name} ${quotedOr(mask(String(segment.value)), "'", "(its value is not shown: it is not a plain identifier)")}`).join(" and ");
460
- return `${resourceTypeShown(resourceType)} ${logicalIdShown(logicalId)}: ${named} contains '${"|"}', which cdkd uses as the separator in this type's physical id (${idShape(segments)}). Recording it would produce an id that decodes back to a DIFFERENT resource, so a later cdkd destroy / drift / update would target the wrong one — or silently skip it while the real resource stays alive. cdkd cannot record a value containing '${"|"}' in this position. Change the named value so it does not contain '${"|"}', or manage the resource outside cdkd.`;
461
- }
462
- function packCompositeId(resourceType, logicalId, segments, options) {
463
- const refusal = compositeIdSeparatorRefusal(resourceType, logicalId, segments, options?.maskSecrets);
464
- if (refusal !== void 0) {
465
- if (options?.onRefusal) options.onRefusal(`${refusal} Continuing with the ambiguous id because the value comes from a cdkd state record, which no template edit can repair; the same value is REFUSED on a template-path create.`);
466
- else throw new ProvisioningError(refusal, resourceType, logicalId);
467
- }
468
- return segments.map((segment) => String(segment.value)).join("|");
469
- }
470
- function formatShape(segments) {
471
- return segments.map((segment) => `<${segment}>`).join("|");
472
- }
473
- function compositeIdFormatMessage(format, logicalId, physicalId, options) {
474
- const accepted = format.alsoAccepts ? `"${formatShape(format.segments)}" or ${format.alsoAccepts}` : `"${formatShape(format.segments)}"`;
475
- const head = `Invalid physicalId format for ${format.label} ${logicalIdShown(logicalId)}: expected ${accepted}, got ${quotedOr(physicalId, "\"", "an id that is not a plain identifier")}`;
476
- if (!options?.skipping) return head;
477
- return `${head}. Skipping the delete — no AWS call is issued, so the resource is LEFT IN PLACE. The state record is KEPT and the run reports the skip: on 'cdkd destroy' / 'cdkd state destroy' (which exits non-zero) and, since issue 1762, on the plain DELETE of a resource removed from the template during cdkd deploy (which re-attempts it on the next deploy). So repair the id in state.json and re-run, or delete the resource by hand and drop the record with ${stateOrphanRecordRemedy(options.context, logicalId)}. NOTE a deploy-side REPLACEMENT or rollback delete instead FAILS the resource (https://github.com/go-to-k/cdkd/issues/1762) — the old resource is left untracked there, so delete it by hand.`;
478
- }
479
- const COMPOSITE_ID_SKIP_REASON = "malformed physicalId in state — no delete issued";
480
- function compositeIdSkipResult() {
481
- return {
482
- outcome: "skipped",
483
- reason: COMPOSITE_ID_SKIP_REASON
484
- };
485
- }
486
-
487
- // src/provisioning/interrupt-watch.ts
488
- var InterruptedWaitError = class InterruptedWaitError extends Error {
489
- constructor(what) {
490
- super(`${what} interrupted by user (SIGINT)`);
491
- this.name = "InterruptedWaitError";
492
- Object.setPrototypeOf(this, InterruptedWaitError.prototype);
493
- }
494
- };
495
- function isInterruptedWaitError(error) {
496
- const seen = /* @__PURE__ */ new Set();
497
- let current = error;
498
- while (current !== void 0 && current !== null) {
499
- if (current instanceof InterruptedWaitError) return true;
500
- if (!(current instanceof Error)) return false;
501
- if (seen.has(current)) return false;
502
- seen.add(current);
503
- current = current.cause;
504
- }
505
- return false;
506
- }
507
- const liveWatches = /* @__PURE__ */ new Set();
508
- let sharedSigintHandler;
509
- let sigintLatched = false;
510
- const interruptWatchTestSeam = {};
511
- let commandInterruptScopeDepth = 0;
512
- function commandOwnsInterrupts() {
513
- const override = interruptWatchTestSeam.commandOwnsInterrupts;
514
- if (override !== void 0) return override();
515
- return commandInterruptScopeDepth > 0;
516
- }
517
- function armSharedSigintHandler() {
518
- if (sharedSigintHandler !== void 0) return;
519
- if (!commandOwnsInterrupts()) return;
520
- const handler = () => {
521
- sigintLatched = true;
522
- for (const live of liveWatches) live.interrupted = true;
523
- if (process.listeners("SIGINT").filter((l) => l !== handler).length === 0) {
524
- process.stderr.write(`
525
- Interrupted.
526
- If the next run reports a stack lock, release it with: ${pasteableCommand("cdkd force-unlock", [{ hole: "stack-name" }]).command}\n`);
527
- (interruptWatchTestSeam.forceQuit ?? ((code) => process.exit(code)))(130);
528
- }
529
- };
530
- sharedSigintHandler = handler;
531
- process.on("SIGINT", handler);
532
- }
533
- function startInterruptWatch(what) {
534
- armSharedSigintHandler();
535
- const state = { interrupted: sigintLatched };
536
- liveWatches.add(state);
537
- let disposed = false;
538
- return {
539
- isInterrupted: () => state.interrupted,
540
- onInterrupted: () => new InterruptedWaitError(what),
541
- dispose: () => {
542
- if (disposed) return;
543
- disposed = true;
544
- liveWatches.delete(state);
545
- }
546
- };
547
- }
548
- function resetInterruptWatchLatch() {
549
- sigintLatched = false;
550
- for (const live of liveWatches) live.interrupted = false;
551
- }
552
- function beginCommandInterruptScope() {
553
- commandInterruptScopeDepth += 1;
554
- if (commandInterruptScopeDepth === 1) resetInterruptWatchLatch();
555
- }
556
- function endCommandInterruptScope() {
557
- commandInterruptScopeDepth = Math.max(0, commandInterruptScopeDepth - 1);
558
- if (commandInterruptScopeDepth > 0) return;
559
- if (sharedSigintHandler !== void 0) {
560
- process.removeListener("SIGINT", sharedSigintHandler);
561
- sharedSigintHandler = void 0;
562
- }
563
- resetInterruptWatchLatch();
564
- }
565
- function interruptWatchListenerCount() {
566
- return sharedSigintHandler === void 0 ? 0 : 1;
567
- }
568
-
569
- // src/provisioning/iam-policy-targets.ts
570
- const IAM_PRINCIPAL_NAME = /^[\w+=,.@-]{1,128}$/;
571
- function diffPrincipalNames(desired, recorded) {
572
- const keys = (names) => new Set((names ?? []).map((name) => name.toLowerCase()));
573
- const unique = (names) => {
574
- const seen = /* @__PURE__ */ new Set();
575
- return (names ?? []).filter((name) => {
576
- const key = name.toLowerCase();
577
- if (seen.has(key)) return false;
578
- seen.add(key);
579
- return true;
580
- });
581
- };
582
- const desiredKeys = keys(desired);
583
- const recordedKeys = keys(recorded);
584
- return {
585
- added: unique(desired).filter((name) => !recordedKeys.has(name.toLowerCase())),
586
- removed: unique(recorded).filter((name) => !desiredKeys.has(name.toLowerCase()))
587
- };
588
- }
589
- function readRecordedPrincipals(value) {
590
- if (value === void 0 || value === null) return { kind: "absent" };
591
- if (!Array.isArray(value)) return {
592
- kind: "malformed",
593
- detail: `found ${typeof value}`
594
- };
595
- if (!value.every((v) => typeof v === "string" && IAM_PRINCIPAL_NAME.test(v))) return {
596
- kind: "malformed",
597
- detail: `a ${value.length}-element list holding a non-name entry`
598
- };
599
- return {
600
- kind: "names",
601
- names: value
602
- };
603
- }
604
- function readPrincipalLists(values) {
605
- const lists = {};
606
- const malformed = [];
607
- const secretDerived = [];
608
- for (const key of Object.keys(values)) {
609
- const value = values[key];
610
- const recorded = readRecordedPrincipals(value);
611
- if (recorded.kind === "malformed") {
612
- malformed.push(key);
613
- if (holdsSecretDerivedEntry(value)) secretDerived.push(key);
614
- } else lists[key] = recorded.kind === "names" ? recorded.names : void 0;
615
- }
616
- return malformed.length > 0 ? {
617
- lists,
618
- malformed,
619
- secretDerived
620
- } : { lists };
621
- }
622
- const SECRET_MASK = "***";
623
- function holdsSecretDerivedEntry(value) {
624
- const seen = /* @__PURE__ */ new Set();
625
- const walk = (v, depth) => {
626
- if (typeof v === "string") return v === SECRET_MASK || v.includes("{{resolve:");
627
- if (typeof v !== "object" || v === null || depth > 64 || seen.has(v)) return false;
628
- seen.add(v);
629
- if (Array.isArray(v)) return v.some((e) => walk(e, depth + 1));
630
- return Object.entries(v).some(([k, e]) => walk(k, depth + 1) || walk(e, depth + 1));
631
- };
632
- return walk(value, 0);
633
- }
634
- function onlySecretDerived(read) {
635
- return "malformed" in read && read.malformed.every((k) => read.secretDerived.includes(k));
636
- }
637
- function recordedPrincipalsRepair(malformed, secretDerived, what, secretDerivedRepair) {
638
- const plain = malformed.filter((k) => !secretDerived.includes(k));
639
- const parts = [];
640
- if (plain.length > 0) parts.push(`repair the recorded ${plain.join(" / ")} in state.json to a list of ${what} and re-run`);
641
- if (secretDerived.length > 0) parts.push(`the recorded ${secretDerived.join(" / ")} is secret-derived (cdkd keeps the dynamic reference or its mask in state), so do not write the name into state.json; ` + secretDerivedRepair);
642
- return parts.join("; ");
643
- }
644
- const SECRET_DERIVED_READ_LIVE = "cdkd reads it from IAM instead once every other list is well-formed";
645
- const RESOLVED_PREVIOUS_PRINCIPAL_KEYS = {
646
- "AWS::IAM::Policy": [
647
- "Roles",
648
- "Groups",
649
- "Users"
650
- ],
651
- "AWS::IAM::UserToGroupAddition": ["Users"]
652
- };
653
- const ATTACHMENT_TARGET_KEY = {
654
- "AWS::IAM::Policy": "PolicyName",
655
- "AWS::IAM::UserToGroupAddition": "GroupName"
656
- };
657
- function holdsMask(value) {
658
- if (typeof value === "string") return value === SECRET_MASK;
659
- if (Array.isArray(value)) return value.some(holdsMask);
660
- if (typeof value === "object" && value !== null) return Object.values(value).some(holdsMask);
661
- return false;
662
- }
663
- function providerRecordedTarget(resourceType, physicalId) {
664
- if (resourceType !== "AWS::IAM::Policy") return void 0;
665
- return physicalId.includes(":") ? physicalId.split(":")[0] : physicalId;
666
- }
667
- function withUnchangedSecretPrincipalLists(resourceType, physicalId, previous, desiredRedacted) {
668
- const untouched = {
669
- previous,
670
- dropped: []
671
- };
672
- const keys = Object.prototype.hasOwnProperty.call(RESOLVED_PREVIOUS_PRINCIPAL_KEYS, resourceType) ? RESOLVED_PREVIOUS_PRINCIPAL_KEYS[resourceType] : [];
673
- if (keys.length === 0) return untouched;
674
- const target = ATTACHMENT_TARGET_KEY[resourceType];
675
- const recordedTarget = previous[target];
676
- const derivedTarget = providerRecordedTarget(resourceType, physicalId);
677
- if (holdsSecretDerivedEntry(recordedTarget) || JSON.stringify(recordedTarget) !== JSON.stringify(desiredRedacted[target]) || derivedTarget !== void 0 && recordedTarget !== derivedTarget) return untouched;
678
- const rewritten = [];
679
- for (const key of keys) {
680
- if (!Object.prototype.hasOwnProperty.call(previous, key)) continue;
681
- const recorded = previous[key];
682
- if (!holdsSecretDerivedEntry(recorded)) continue;
683
- const redacted = desiredRedacted[key];
684
- if (!Array.isArray(recorded) || !Array.isArray(redacted) || holdsMask(recorded)) return untouched;
685
- const kept = [];
686
- for (const entry of recorded) {
687
- if (!holdsSecretDerivedEntry(entry)) {
688
- kept.push(entry);
689
- continue;
690
- }
691
- if (typeof entry !== "string" || !redacted.includes(entry)) return untouched;
692
- }
693
- rewritten.push([key, kept]);
694
- }
695
- if (rewritten.length === 0) return untouched;
696
- const out = { ...previous };
697
- for (const [key, kept] of rewritten) out[key] = kept;
698
- return {
699
- previous: out,
700
- dropped: rewritten.map(([key]) => key)
701
- };
702
- }
703
-
704
- // src/provisioning/replacement-protection-advice.ts
705
- const DELETION_PROTECTION_DOC_POINTER = "\"Deletion protection blocks a replacement, and deploy cannot clear it\" at https://cdkd.dev/cli-deploy-safety/#deletion-protection-blocks-a-replacement-and-deploy-cannot-clear-it";
706
- const UNNAMEABLE_ID_CLAUSE = "Then disable protection out of band, via the console: the physical id cdkd recorded for this resource cannot be reproduced safely on a command line (sanitizing would change it, so a command would act on a different resource, or it holds a character or prefix a pasted shell line, or the AWS CLI itself, would act on, or it is derived from a secret, which a pasted command would print).";
707
- const AWS_CLI_ACTIVE_ARG = /^-|^(?:fileb?|https?):\/\/|@=/i;
708
- function isAwsCliLiteral(value) {
709
- return !AWS_CLI_ACTIVE_ARG.test(value);
710
- }
711
- function renderDisableCommand(disable) {
712
- const resolved = disable;
713
- const quoted = pasteableArg(resolved.identifier, resolved.maskSecrets);
714
- if (quoted === void 0) return "";
715
- const tail = resolved.after ? ` ${resolved.after}` : "";
716
- return `${withPasteableAwsProfile(resolved.before)} ${quoted}${tail}`;
717
- }
718
- function pasteableArg(value, maskSecrets) {
719
- if (typeof value !== "string") return void 0;
720
- const safe = displaySafe(value, { asciiOnly: true });
721
- if (!safe || safe !== value) return void 0;
722
- if (maskSecrets && maskSecrets(safe) !== safe) return void 0;
723
- if (!isInertUnquoted(safe)) return void 0;
724
- if (!isAwsCliLiteral(safe)) return void 0;
725
- return shellQuote(safe);
726
- }
727
- var PasteableAwsCommand = class {
728
- text;
729
- #origin;
730
- constructor(text, origin) {
731
- this.text = text;
732
- this.#origin = origin;
733
- }
734
- builtBy(tag) {
735
- return this.#origin === tag;
736
- }
737
- render() {
738
- return this.text ?? "[command withheld: a name or id it would carry cannot be printed safely on a command line (inexact, so a pasted copy could act on a different resource, or holding a character or prefix a pasted shell line, or the AWS CLI itself, would act on); use the console]";
739
- }
740
- };
741
- const WITHHELD_AWS_COMMAND = "[command withheld: a name or id it would carry cannot be printed safely on a command line (inexact, so a pasted copy could act on a different resource, or holding a character or prefix a pasted shell line, or the AWS CLI itself, would act on); use the console]";
742
- function pasteableAwsCommand(maskSecrets) {
743
- const tag = (strings, ...values) => {
744
- let text = withPasteableAwsProfile(strings[0] ?? "");
745
- for (let i = 0; i < values.length; i++) {
746
- const value = values[i];
747
- const rendered = value instanceof PasteableAwsCommand ? value.builtBy(tag) ? value.text : void 0 : pasteableArg(value, maskSecrets);
748
- if (rendered === void 0) return new PasteableAwsCommand(void 0, tag);
749
- text += rendered + withPasteableAwsProfile(strings[i + 1] ?? "");
750
- }
751
- return new PasteableAwsCommand(text, tag);
752
- };
753
- return tag;
754
- }
755
- function protectedReplacementAdvice(args) {
756
- const { evidence, replaceFlags } = args;
757
- const command = renderDisableCommand(args.disable);
758
- const disable = args.disable;
759
- const head = `${evidence}, so ${replaceFlags} alone will NOT succeed while AWS still has protection on: the replacement DELETES the resource, AWS refuses that delete while protection is on, and cdkd deploy has no --remove-protection flag to clear it (only cdkd destroy and cdkd state destroy act on one). Read ${DELETION_PROTECTION_DOC_POINTER} BEFORE you disable anything: whether disabling helps at all, and what the flag ends up as, depend on your UpdateReplacePolicy and on whether the deploy completes — neither of which this refusal can see.`;
760
- if (!command) return `${head} ${UNNAMEABLE_ID_CLAUSE} Then re-run with ${replaceFlags}.`;
761
- return `${head} Then disable protection out of band — \`${command}\`, or via the console.${disable.caveat ? ` ${disable.caveat}` : ""} Then re-run with ${replaceFlags}.`;
762
- }
763
-
764
- // src/utils/elapsed-budget.ts
765
- const monotonicNowMs = typeof globalThis.performance?.now === "function" ? () => globalThis.performance.now() : () => Date.now();
766
- var ElapsedBudget = class {
767
- totalMs;
768
- clock;
769
- startedAt;
770
- constructor(totalMs, clock = monotonicNowMs) {
771
- if (!Number.isFinite(totalMs) || totalMs <= 0) throw new RangeError(`ElapsedBudget: totalMs must be a positive finite number (got ${totalMs})`);
772
- this.totalMs = totalMs;
773
- this.clock = clock;
774
- this.startedAt = clock();
775
- }
776
- elapsedMs() {
777
- return Math.max(0, this.clock() - this.startedAt);
778
- }
779
- remainingMs() {
780
- return Math.max(0, this.totalMs - this.elapsedMs());
781
- }
782
- isExhausted() {
783
- return this.remainingMs() <= 0;
784
- }
785
- attemptsWithin(cap, perAttemptMs, minAttempts = 1) {
786
- if (!Number.isFinite(cap) || cap <= 0) return 0;
787
- if (!Number.isFinite(perAttemptMs) || perAttemptMs <= 0) return Math.min(minAttempts, cap);
788
- const affordable = Math.floor(this.remainingMs() / perAttemptMs);
789
- return Math.max(Math.min(minAttempts, cap), Math.min(cap, affordable));
790
- }
791
- };
792
- var ElapsedBudgetRegistry = class {
793
- budgets = /* @__PURE__ */ new Map();
794
- acquire(key, totalMs, clock = monotonicNowMs, reuseWithinMs) {
795
- const existing = this.budgets.get(key);
796
- if (existing) {
797
- if (!(reuseWithinMs !== void 0 && existing.elapsedMs() > reuseWithinMs)) return existing;
798
- this.budgets.delete(key);
799
- }
800
- const created = new ElapsedBudget(totalMs, clock);
801
- this.budgets.set(key, created);
802
- return created;
803
- }
804
- release(key) {
805
- this.budgets.delete(key);
806
- }
807
- get size() {
808
- return this.budgets.size;
809
- }
810
- clear() {
811
- this.budgets.clear();
812
- }
813
- };
814
-
815
- // src/provisioning/providers/deletion-protection-compensation/flip-record.ts
816
- var ProtectionFlipRegistry = class {
817
- records = /* @__PURE__ */ new Map();
818
- acquire(key, reuseWithinMs, clock = monotonicNowMs) {
819
- const existing = this.records.get(key);
820
- if (existing) {
821
- if (existing.idle.elapsedMs() <= reuseWithinMs) {
822
- existing.idle = new ElapsedBudget(reuseWithinMs, clock);
823
- return existing.record;
824
- }
825
- this.records.delete(key);
826
- }
827
- const created = {
828
- record: {
829
- flippedOffByThisRun: false,
830
- deleteAccepted: false
831
- },
832
- idle: new ElapsedBudget(reuseWithinMs, clock)
833
- };
834
- this.records.set(key, created);
835
- return created.record;
836
- }
837
- release(key) {
838
- this.records.delete(key);
839
- }
840
- get size() {
841
- return this.records.size;
842
- }
843
- clear() {
844
- this.records.clear();
845
- }
846
- };
847
- function protectionFlipKey(resourceType, physicalId, region) {
848
- return injectiveKey(resourceType, region ?? "", physicalId);
849
- }
850
- const PROTECTION_FLIP_REUSE_WINDOW_MS = 18e5;
851
- const finalDeleteAttempt = new AsyncLocalStorage();
852
- function runDeleteAttempt(isFinal, attempt) {
853
- return finalDeleteAttempt.run(isFinal, attempt);
854
- }
855
- function isTerminalDeleteFailure(error) {
856
- if (isInterruptedWaitError(error)) return true;
857
- if (finalDeleteAttempt.getStore() === true) return true;
858
- if (isMarkedNonRetryable(error)) return true;
859
- const classify = retryClassificationText(error);
860
- return !(isRetryableTransientError(error, classify) || classify.includes("Too Many Requests"));
861
- }
862
-
863
- // src/provisioning/providers/deletion-protection-compensation/final-snapshot-wait.ts
864
- const PROTECTION_FLIP_RETRY_WAIT_MS = 6e5;
865
- const FINAL_SNAPSHOT_SETTLE_WAIT_MS = 9e5;
866
- const FINAL_SNAPSHOT_COMPENSATION_MARGIN_MS = 6e4;
867
- const FLIP_TRANSITION_GRACE_MS = 3e4;
868
- function finalSnapshotWaitBudgetMs(opts) {
869
- const budgetMs = Math.min(opts.maxWaitMs ?? 9e5, opts.remainingMs - FINAL_SNAPSHOT_COMPENSATION_MARGIN_MS);
870
- if (budgetMs <= 0) throw new Error(`--remove-protection turned DeletionProtection off, but the resource timeout leaves no time to wait for the ${opts.noun} to return to 'available', which the final snapshot its DeletionPolicy asks for needs. The delete was not sent and the guard is put back; re-run the destroy with a longer --resource-timeout`);
871
- return budgetMs;
872
- }
873
- const TERMINAL_DB_STATUSES = /* @__PURE__ */ new Set([
874
- "deleting",
875
- "failed",
876
- "stopped",
877
- "storage-full",
878
- "insufficient-capacity",
879
- "restore-error"
880
- ]);
881
- const PROCEED_DB_STATUSES = /* @__PURE__ */ new Set(["storage-optimization", "storage-initialization"]);
882
- function isProceedDbStatus(status) {
883
- return status === "available" || status !== void 0 && PROCEED_DB_STATUSES.has(status);
884
- }
885
- function isTerminalDbStatus(status) {
886
- if (status === void 0) return false;
887
- return TERMINAL_DB_STATUSES.has(status) || status.startsWith("inaccessible-") || status.startsWith("incompatible-") || status.endsWith("-failed");
888
- }
889
- function isTerminalDbWaitStatus(status) {
890
- return status !== "inaccessible-encryption-credentials-recoverable" && isTerminalDbStatus(status);
891
- }
892
- async function settleBeforeFinalSnapshot(opts, startTime, budgetMs) {
893
- const { noun, label, logicalId } = opts;
894
- let delay = 5e3;
895
- let graceSleptMs = 0;
896
- let sawOff = false;
897
- let sawTransitional = false;
898
- for (;;) {
899
- const current = await opts.read();
900
- if (current === void 0) return;
901
- const terminal = isTerminalDbStatus(current.status);
902
- const operational = current.status !== "available" && isProceedDbStatus(current.status);
903
- if (!isProceedDbStatus(current.status) && !terminal) sawTransitional = true;
904
- if (current.deletionProtection === false) sawOff = true;
905
- if (current.deletionProtection === false && (terminal || operational)) return;
906
- if (current.deletionProtection === true && terminal) throw new Error(`--remove-protection turned DeletionProtection off, but the ${noun} still reads it ON in status '${current.status ?? "unknown"}', which does not change on its own, and the final snapshot its DeletionPolicy asks for needs it 'available'. The delete was not sent and the guard is put back; re-run the destroy once the ${noun} is 'available'`);
907
- const settled = current.deletionProtection === false && current.status === "available";
908
- const inGrace = !sawTransitional && graceSleptMs < 3e4;
909
- if (settled && !inGrace) return;
910
- const step = inGrace ? Math.min(delay, FLIP_TRANSITION_GRACE_MS - graceSleptMs) : delay;
911
- if (Date.now() - startTime + step >= budgetMs) {
912
- if (settled) return;
913
- if (current.deletionProtection === false && current.status !== void 0 && current.status !== "modifying") return;
914
- break;
915
- }
916
- opts.logger.debug(safeMsg`${label} ${logicalId}: waiting for the DeletionProtection change to settle before the final snapshot (status ${current.status ?? "unknown"})`);
917
- await opts.sleep(step);
918
- if (sawOff) graceSleptMs += step;
919
- delay = Math.min(delay * 2, 1e4);
920
- }
921
- throw new Error(`--remove-protection turned DeletionProtection off, but the ${noun} did not return to 'available' within ${Math.max(1, Math.round(budgetMs / 6e4))} minutes, and the final snapshot its DeletionPolicy asks for needs it. The delete was not sent and the guard is put back; re-run the destroy once the ${noun} is 'available'`);
922
- }
923
- function isFinalSnapshotNotAvailableRefusal(error, stateFault) {
924
- if (!(error instanceof Error) || error.name !== stateFault) return false;
925
- return /(?:isn't|is not|isn’t) (?:currently )?in (?:the )?available state/i.test(error.message);
926
- }
927
- async function deleteAfterProtectionFlipWithFinalSnapshot(opts) {
928
- const budgetMs = finalSnapshotWaitBudgetMs(opts);
929
- const startTime = Date.now();
930
- await settleBeforeFinalSnapshot(opts, startTime, budgetMs);
931
- let delay = 5e3;
932
- let refusals = 0;
933
- for (;;) try {
934
- await opts.send();
935
- return;
936
- } catch (error) {
937
- if (!isFinalSnapshotNotAvailableRefusal(error, opts.stateFault)) throw error;
938
- refusals += 1;
939
- opts.logger.debug(safeMsg`${opts.label} ${opts.logicalId}: final-snapshot delete refused as not 'available' (refusal ${String(refusals)}); waiting for it to return to 'available' before retrying`);
940
- for (;;) {
941
- if (Date.now() - startTime + delay >= budgetMs) throw error;
942
- await opts.sleep(delay);
943
- delay = Math.min(delay * 2, 1e4);
944
- const current = await opts.read();
945
- if (current === void 0) break;
946
- if (current.deletionProtection === false && isProceedDbStatus(current.status)) break;
947
- if (current.deletionProtection === true || isTerminalDbStatus(current.status)) throw error;
948
- }
949
- }
950
- }
951
-
952
- // src/provisioning/providers/deletion-protection-compensation.ts
953
- function rdsFamilyProtectionSite(opts) {
954
- return {
955
- subject: `${opts.serviceLabel} ${opts.kind === "cluster" ? "DBCluster" : "DBInstance"}`,
956
- guardName: "DeletionProtection",
957
- noun: opts.kind,
958
- isNotFound: opts.isNotFound,
959
- notFoundMeaning: `${opts.serviceLabel} answered ${opts.notFoundFault}. That most commonly means the ${opts.kind} is gone, and it can also mean it is not in this region or account.`,
960
- commands: () => {
961
- const aws = pasteableAwsCommand();
962
- const regionArg = opts.region ? aws` --region ${opts.region}` : aws``;
963
- const id = opts.physicalId;
964
- const svc = opts.cliService;
965
- const service = svc === "rds" ? aws`rds` : svc === "docdb" ? aws`docdb` : aws`neptune`;
966
- const check = opts.kind === "cluster" ? aws`aws ${service} describe-db-clusters --db-cluster-identifier ${id}${regionArg}` : aws`aws ${service} describe-db-instances --db-instance-identifier ${id}${regionArg}`;
967
- const restore = opts.kind === "cluster" ? aws`aws ${service} modify-db-cluster --db-cluster-identifier ${id}${regionArg} --deletion-protection --apply-immediately` : aws`aws ${service} modify-db-instance --db-instance-identifier ${id}${regionArg} --deletion-protection --apply-immediately`;
968
- return {
969
- check: check.render(),
970
- restoreAfterNotFound: restore.render(),
971
- restoreLive: restore.render()
972
- };
973
- }
974
- };
975
- }
976
- function isResourceNotFoundException(error) {
977
- return typeof error === "object" && error !== null && error.name === "ResourceNotFoundException";
978
- }
979
- function logGroupProtectionSite(physicalId, region) {
980
- return {
981
- subject: "Log group",
982
- guardName: "DeletionProtectionEnabled",
983
- noun: "log group",
984
- isNotFound: isResourceNotFoundException,
985
- notFoundMeaning: "CloudWatch Logs answered ResourceNotFoundException. That most commonly means the log group is gone, and it can also mean it is not in this region or account.",
986
- commands: () => {
987
- const aws = pasteableAwsCommand();
988
- const regionArg = region ? aws` --region ${region}` : aws``;
989
- const restore = aws`aws logs put-log-group-deletion-protection --log-group-identifier ${physicalId}${regionArg} --deletion-protection-enabled`;
990
- return {
991
- check: aws`aws logs describe-log-groups --log-group-identifiers ${physicalId}${regionArg}`.render(),
992
- restoreAfterNotFound: restore.render(),
993
- restoreLive: restore.render()
994
- };
995
- }
996
- };
997
- }
998
- function userPoolProtectionSite(physicalId, region) {
999
- return {
1000
- subject: "Cognito User Pool",
1001
- guardName: "DeletionProtection",
1002
- noun: "user pool",
1003
- isNotFound: isResourceNotFoundException,
1004
- notFoundMeaning: "Cognito answered ResourceNotFoundException. That most commonly means the user pool is gone, and it can also mean it is not in this region or account.",
1005
- commands: () => {
1006
- const aws = pasteableAwsCommand();
1007
- const regionArg = region ? aws` --region ${region}` : aws``;
1008
- const restore = aws`aws cognito-idp update-user-pool --user-pool-id ${physicalId}${regionArg} --deletion-protection ACTIVE`;
1009
- return {
1010
- check: aws`aws cognito-idp describe-user-pool --user-pool-id ${physicalId}${regionArg}`.render(),
1011
- restoreAfterNotFound: restore.render(),
1012
- restoreLive: restore.render()
1013
- };
1014
- },
1015
- restoreCaveat: "Note UpdateUserPool resets some members a call omits (self sign-up, Lambda triggers, advanced security, AutoVerifiedAttributes and a customer-managed KeyConfiguration among them), so send your complete pool configuration alongside that flag rather than the flag alone."
1016
- };
1017
- }
1018
- async function compensateProtectionFlip(opts) {
1019
- if (!opts.flip.flippedOffByThisRun) return "not-applicable";
1020
- if (opts.flip.deleteAccepted) return "not-applicable";
1021
- if (!isTerminalDeleteFailure(opts.error)) return "not-applicable";
1022
- const { site } = opts;
1023
- try {
1024
- const result = await opts.reEnable();
1025
- if (result === "read-on-write-failed") {
1026
- opts.logger.warn(safeMsg`${site.subject} ${opts.logicalId}: the delete failed after ` + safeMsg`--remove-protection tried to turn ${site.guardName} off; ${opts.physicalId} ` + safeMsg`read it on afterwards, but writing it back failed, so cdkd cannot confirm ` + safeMsg`it. Check with: ${site.commands().check}. The delete failure below is the outcome.`);
1027
- return "failed";
1028
- }
1029
- opts.logger.warn(result === "already-on" ? safeMsg`${site.subject} ${opts.logicalId}: the delete failed after ` + safeMsg`--remove-protection tried to turn ${site.guardName} off; ${opts.physicalId} ` + safeMsg`already read it on, and cdkd wrote it back (AWS accepted the write). The ` + safeMsg`delete failure below is the outcome.` : safeMsg`${site.subject} ${opts.logicalId}: the delete failed after ` + safeMsg`--remove-protection had turned ${site.guardName} off, so it was ` + safeMsg`re-enabled on ${opts.physicalId}. The delete failure below is the outcome.`);
1030
- return "restored";
1031
- } catch (reEnableError) {
1032
- const mask = maskerOrIdentity(opts.mask);
1033
- const failure = describeAwsFailure(reEnableError);
1034
- const detail = mask(failure.summary);
1035
- if (failure.redacted) opts.logger.debug(mask(safeMsg`${site.subject} ${opts.logicalId}: re-enabling ${site.guardName} on ` + safeMsg`${opts.physicalId} failed: ${mask(failure.detail)}`));
1036
- const commands = site.commands();
1037
- const caveat = site.restoreCaveat ? ` ${site.restoreCaveat}` : "";
1038
- if (site.isNotFound(reEnableError)) {
1039
- opts.logger.warn(safeMsg`${site.subject} ${opts.logicalId}: could not re-enable ` + safeMsg`${site.guardName} on ${opts.physicalId} after the delete failed — ` + safeMsg`${site.notFoundMeaning} If it still exists, its deletion protection is OFF. ` + safeMsg`Check with: ${commands.check} and if it is there, restore it with: ` + safeMsg`${commands.restoreAfterNotFound}.${caveat} (${detail})`);
1040
- return "failed";
1041
- }
1042
- opts.logger.error(safeMsg`${site.subject} ${opts.logicalId}: could NOT re-enable ` + safeMsg`${site.guardName} on ${opts.physicalId} after the delete failed — ` + safeMsg`that ${site.noun} is LIVE with its deletion protection still off. Restore it with: ` + safeMsg`${commands.restoreLive}.${caveat} (${detail})`);
1043
- return "failed";
1044
- }
1045
- }
1046
- async function observeThenDisableProtection(opts) {
1047
- let observedOn = false;
1048
- try {
1049
- observedOn = await opts.observe();
1050
- } catch (observeError) {
1051
- const mask = maskerOrIdentity(opts.mask);
1052
- opts.logger.debug(mask(safeMsg`Could not read ${opts.guardName} on ${mask(opts.physicalId)} before disabling it: ${mask(describeAwsFailure(observeError).detail)}`));
1053
- }
1054
- await opts.disable();
1055
- if (observedOn) opts.flip.flippedOffByThisRun = true;
1056
- }
1057
- async function deleteWithProtectionCompensation(opts) {
1058
- const flip = opts.registry.acquire(opts.key, opts.reuseWithinMs ?? 18e5, opts.clock);
1059
- try {
1060
- await opts.run(flip);
1061
- } catch (error) {
1062
- await settleProtectionFlip({
1063
- registry: opts.registry,
1064
- key: opts.key,
1065
- flip,
1066
- error,
1067
- compensation: opts.compensation
1068
- });
1069
- throw error;
1070
- }
1071
- opts.registry.release(opts.key);
1072
- }
1073
- async function settleProtectionFlip(opts) {
1074
- let outcome = "failed";
1075
- try {
1076
- outcome = await compensateProtectionFlip({
1077
- ...opts.compensation,
1078
- flip: opts.flip,
1079
- error: opts.error
1080
- });
1081
- } catch {}
1082
- if (isTerminalDeleteFailure(opts.error) && outcome !== "failed") {
1083
- opts.registry.release(opts.key);
1084
- return true;
1085
- }
1086
- return false;
1087
- }
1088
-
1089
- // src/provisioning/not-gone.ts
1090
- const NOT_GONE = Symbol.for("cdkd.notGone");
1091
- const MAX_DEPTH = 10;
1092
- function markNotGone(error) {
1093
- try {
1094
- if (typeof error !== "object" || error === null || !Object.isExtensible(error)) return error;
1095
- Object.defineProperty(error, NOT_GONE, {
1096
- value: true,
1097
- enumerable: false,
1098
- writable: false,
1099
- configurable: true
1100
- });
1101
- } catch {}
1102
- return error;
1103
- }
1104
- function isMarkedNotGone(error) {
1105
- try {
1106
- let current = error;
1107
- for (let depth = 0; depth < MAX_DEPTH && typeof current === "object" && current !== null; depth++) {
1108
- if (Object.prototype.hasOwnProperty.call(current, NOT_GONE)) return true;
1109
- current = current.cause;
1110
- }
1111
- } catch {}
1112
- return false;
1113
- }
1114
-
1115
- // src/provisioning/import-helpers.ts
1116
- function remedyLogicalId(logicalId) {
1117
- return isPasteableIdent(logicalId) ? logicalId : commandHole("logicalId");
1118
- }
1119
- function importRemedyCommand(stackName, assignment) {
1120
- return pasteableCommand("cdkd import", [
1121
- stackName !== void 0 && isPasteableIdent(stackName) ? { literal: stackName } : { hole: "stackName" },
1122
- { literal: "--resource" },
1123
- { literal: assignment.replace(/(?<!')<([A-Za-z]+)>(?!')/g, (_m, n) => commandHole(n)) }
1124
- ]).command;
1125
- }
1126
- function isPlainImportValue(value) {
1127
- return isPlainIdent(value, { maxCodePoints: SECRET_REF_MAX_CODE_POINTS });
1128
- }
1129
- function isQuotableImportValue(value) {
1130
- return value.split("|").every((segment) => segment === "" || isPlainImportValue(segment));
1131
- }
1132
- function quotedRemedyLogicalId(logicalId) {
1133
- return isPasteableIdent(logicalId) ? logicalId : "<logicalId>";
1134
- }
1135
- function refusalTypeShown(resourceType) {
1136
- return resourceTypeShown(resourceType) === resourceType ? resourceType : "(resource type not shown: it is not a plain identifier)";
1137
- }
1138
- const VALUE_NOT_SHOWN = "(not shown: it is not a plain identifier)";
1139
- const PLAIN_JSON = /^[A-Za-z0-9"{}[\]:,._@/+=~-]+$/;
1140
- function isPlainImportJson(value) {
1141
- const json = JSON.stringify(value);
1142
- return typeof json === "string" && json.length <= 2048 && PLAIN_JSON.test(json);
1143
- }
1144
- function readNameProperty(input, propertyName) {
1145
- const value = input.properties?.[propertyName];
1146
- return typeof value === "string" && value.length > 0 ? value : void 0;
1147
- }
1148
- function resolveExplicitPhysicalId(input, nameProperty) {
1149
- if (input.knownPhysicalId) return input.knownPhysicalId;
1150
- if (nameProperty) {
1151
- const name = readNameProperty(input, nameProperty);
1152
- if (name) return name;
1153
- }
1154
- }
1155
- function normalizeAwsTagsToCfn(tags) {
1156
- if (!tags) return [];
1157
- const out = [];
1158
- if (Array.isArray(tags)) for (const t of tags) {
1159
- const obj = t;
1160
- const k = (typeof obj["Key"] === "string" ? obj["Key"] : void 0) ?? (typeof obj["TagKey"] === "string" ? obj["TagKey"] : void 0) ?? (typeof obj["key"] === "string" ? obj["key"] : void 0);
1161
- const v = (typeof obj["Value"] === "string" ? obj["Value"] : void 0) ?? (typeof obj["TagValue"] === "string" ? obj["TagValue"] : void 0) ?? (typeof obj["value"] === "string" ? obj["value"] : void 0);
1162
- if (typeof k !== "string" || k.length === 0) continue;
1163
- if (k.startsWith("aws:")) continue;
1164
- out.push({
1165
- Key: k,
1166
- Value: typeof v === "string" ? v : ""
1167
- });
1168
- }
1169
- else for (const [k, v] of Object.entries(tags)) {
1170
- if (!k || k.startsWith("aws:")) continue;
1171
- out.push({
1172
- Key: k,
1173
- Value: typeof v === "string" ? v : ""
1174
- });
1175
- }
1176
- out.sort((a, b) => a.Key < b.Key ? -1 : a.Key > b.Key ? 1 : 0);
1177
- return out;
1178
- }
1179
-
1180
- // src/provisioning/region-check.ts
1181
- function holderRefusalRun(context) {
1182
- return context?.stackDestroy === true ? {
1183
- noun: "destroy",
1184
- again: "destroy again",
1185
- rerun: "run the destroy again"
1186
- } : {
1187
- noun: "run",
1188
- again: "run the command again",
1189
- rerun: "run the command again"
1190
- };
1191
- }
1192
- function holderRefusalMask(context, mask) {
1193
- const stack = context?.maskStackSecretNames;
1194
- return stack === void 0 ? mask : (text) => mask(stack(text));
1195
- }
1196
- function assertRegionMatch(clientRegion, expectedRegion, resourceType, logicalId, physicalId, phase = "not-found", endpoint = "regional") {
1197
- if (!expectedRegion) return;
1198
- if (!clientRegion) throw new ProvisioningError(phase === "not-found" ? `Refusing to treat NotFound as idempotent delete success for ${logicalId} (${resourceType}): AWS client region is unknown but stack state expects ${expectedRegion}. The resource may exist in ${expectedRegion} and would be silently removed from state if this NotFound were trusted.` : `Refusing to ${phaseVerb(phase)} ${logicalId} (${resourceType}): AWS client region is unknown but stack state records the resource in ${expectedRegion}. ` + (endpoint === "global" ? `cdkd cannot confirm that this client was built for the stack this record belongs to, so the ${phaseVerb(phase)} is not issued. Point the ` : `cdkd cannot confirm that the physical id recorded in state names the resource this client would act on, so the ${phaseVerb(phase)} is not issued. Point the `) + `AWS client at ${expectedRegion} (AWS_REGION or your AWS profile) and re-run.`, resourceType, logicalId, physicalId);
1199
- if (clientRegion !== expectedRegion) throw new ProvisioningError(phase === "not-found" ? `Refusing to treat NotFound as idempotent delete success for ${logicalId} (${resourceType}): AWS client region ${clientRegion} does not match stack state region ${expectedRegion}. The resource likely still exists in ${expectedRegion}; rerun the destroy with the correct region (e.g. --region ${expectedRegion}).` : `Refusing to ${phaseVerb(phase)} ${logicalId} (${resourceType}): AWS client region ${clientRegion} does not match stack state region ${expectedRegion}. ` + (endpoint === "global" ? `This service has one global endpoint, so the call would reach the same resource, but a client in ${clientRegion} was not built for the stack this ${expectedRegion} record belongs to, so the ${phaseVerb(phase)} is not issued. ` : `The physical id recorded in cdkd state names a resource in ${expectedRegion}, so this ${phaseVerb(phase)} would act on whatever carries that id in ${clientRegion} instead — which for a name-shaped physical id is a different resource that usually exists. `) + `Point the AWS client at ${expectedRegion} (AWS_REGION or your AWS profile) and re-run; when the run spans several regions at once (cdkd drift --all), select the stacks in one region per run, because no single client region is correct for all of them. If the recorded region is the wrong one, correct the state record (cdkd state show).`, resourceType, logicalId, physicalId);
1200
- }
1201
- function phaseVerb(phase) {
1202
- return phase === "pre-update" ? "update" : "delete";
1203
- }
1204
-
1205
- // src/types/resource/read-state.ts
1206
- const RESOURCE_NOT_FOUND = Symbol("cdkd.resourceNotFound");
1207
- var DriftReadRefusedError = class extends Error {
1208
- name = "DriftReadRefusedError";
1209
- };
1210
-
1211
- // src/provisioning/providers/ambiguous-create.ts
1212
- const CREATION_DATE_SKEW_MARGIN_MS = 5e3;
1213
- const AMBIGUOUS_LATCH_TTL_MS = 18e5;
1214
- const MAX_TRACKED = 1e4;
1215
- const createAttemptKey = (scope, logicalId) => injectiveKey(scope, ambientRegion() ?? "", getCurrentStackName() ?? "", logicalId);
1216
- const setBounded = (map, key, value) => {
1217
- if (!map.has(key) && map.size >= MAX_TRACKED) {
1218
- const oldest = map.keys().next();
1219
- if (!oldest.done) map.delete(oldest.value);
1220
- }
1221
- map.set(key, value);
1222
- };
1223
- const replayedInSend = (output) => {
1224
- const attempts = output?.$metadata?.attempts;
1225
- return typeof attempts === "number" && attempts > 1;
1226
- };
1227
- const isObject = (value) => typeof value === "object" && value !== null;
1228
- const sendsAfterAmbiguous = /* @__PURE__ */ new WeakSet();
1229
- const outputsAfterAmbiguous = /* @__PURE__ */ new WeakSet();
1230
- const markReplayFollowedAmbiguous = (output) => {
1231
- if (isObject(output)) outputsAfterAmbiguous.add(output);
1232
- };
1233
- const replayFollowedAmbiguousAttempt = (output) => isObject(output) && outputsAfterAmbiguous.has(output);
1234
- const AMBIGUOUS_REPLAY_MIDDLEWARE = "cdkdAmbiguousReplayMiddleware";
1235
- const trackAmbiguousReplays = (client) => {
1236
- const stack = client.middlewareStack;
1237
- if (typeof stack?.addRelativeTo !== "function") return;
1238
- stack.addRelativeTo((next) => async (args) => {
1239
- try {
1240
- const result = await next(args);
1241
- if (sendsAfterAmbiguous.has(args)) markReplayFollowedAmbiguous(result.output);
1242
- return result;
1243
- } catch (error) {
1244
- if (isAmbiguousOutcomeError(error)) sendsAfterAmbiguous.add(args);
1245
- throw error;
1246
- }
1247
- }, {
1248
- name: AMBIGUOUS_REPLAY_MIDDLEWARE,
1249
- relation: "after",
1250
- toMiddleware: "retryMiddleware",
1251
- override: true
1252
- });
1253
- };
1254
- const replayedSendWindow = (output, attemptStartMs) => replayedInSend(output) ? {
1255
- floorMs: attemptStartMs - CREATION_DATE_SKEW_MARGIN_MS,
1256
- ceilingMs: Date.now() + CREATION_DATE_SKEW_MARGIN_MS,
1257
- replayedInSend: true
1258
- } : void 0;
1259
- const ambiguousAttemptLead = (action, logicalId, window) => window.replayedInSend === true ? `The ${action} call for ${logicalId} succeeded only after the AWS SDK sent it again, following an attempt that failed without a definite answer` : `An earlier ${action} attempt for ${logicalId} failed without a definite answer`;
1260
- const mergeWindow = (existing, next, armedAtMs) => existing === void 0 ? {
1261
- floorMs: next.floorMs,
1262
- ceilingMs: next.ceilingMs,
1263
- armedAtMs
1264
- } : {
1265
- floorMs: Math.min(existing.floorMs, next.floorMs),
1266
- ceilingMs: Math.max(existing.ceilingMs, next.ceilingMs),
1267
- armedAtMs: Math.max(existing.armedAtMs, armedAtMs)
1268
- };
1269
- var AmbiguousCreateLatch = class {
1270
- entries = /* @__PURE__ */ new Map();
1271
- scope;
1272
- constructor(scope) {
1273
- this.scope = scope;
1274
- }
1275
- noteFailure(logicalId, error, attemptStartMs, carried) {
1276
- if (!isAmbiguousOutcomeError(error) && !hasReplayMayCollide(error)) return;
1277
- const key = createAttemptKey(this.scope, logicalId);
1278
- const now = Date.now();
1279
- let entry = mergeWindow(this.entries.get(key), {
1280
- floorMs: attemptStartMs - CREATION_DATE_SKEW_MARGIN_MS,
1281
- ceilingMs: now + CREATION_DATE_SKEW_MARGIN_MS
1282
- }, now);
1283
- if (carried !== void 0) entry = mergeWindow(entry, carried, now);
1284
- setBounded(this.entries, key, entry);
1285
- }
1286
- take(logicalId) {
1287
- const key = createAttemptKey(this.scope, logicalId);
1288
- const entry = this.entries.get(key);
1289
- this.entries.delete(key);
1290
- if (entry === void 0 || Date.now() - entry.armedAtMs > 18e5) return;
1291
- return {
1292
- floorMs: entry.floorMs,
1293
- ceilingMs: entry.ceilingMs
1294
- };
1295
- }
1296
- resetForTests() {
1297
- this.entries.clear();
1298
- }
1299
- };
1300
- const isInsideWindow = (date, window) => date !== void 0 && date.getTime() >= window.floorMs && date.getTime() <= window.ceilingMs;
1301
- var RecentIdSet = class {
1302
- ids = /* @__PURE__ */ new Map();
1303
- add(id) {
1304
- setBounded(this.ids, id, true);
1305
- }
1306
- has(id) {
1307
- return this.ids.has(id);
1308
- }
1309
- resetForTests() {
1310
- this.ids.clear();
1311
- }
1312
- };
1313
- const isRetryStrategyV2 = (value) => typeof value === "object" && value !== null && typeof value.acquireInitialRetryToken === "function" && typeof value.refreshRetryTokenForRetry === "function" && typeof value.recordSuccess === "function";
1314
- function withoutServerErrorRetries(client) {
1315
- const config = client.config;
1316
- const base = config?.retryStrategy;
1317
- if (config === void 0 || typeof base !== "function") return client;
1318
- trackAmbiguousReplays(client);
1319
- const resolveBase = base;
1320
- const afterAmbiguous = /* @__PURE__ */ new WeakSet();
1321
- config.retryStrategy = async () => {
1322
- const strategy = await resolveBase();
1323
- if (!isRetryStrategyV2(strategy)) return strategy;
1324
- return {
1325
- acquireInitialRetryToken: (scope) => strategy.acquireInitialRetryToken(scope),
1326
- refreshRetryTokenForRetry: async (token, errorInfo) => {
1327
- const ambiguous = isAmbiguousOutcomeError(errorInfo.error);
1328
- const replayed = isObject(token) && afterAmbiguous.has(token);
1329
- if (replayed) markReplayMayCollide(errorInfo.error);
1330
- if (ambiguous && isTransientServerError(errorInfo.error)) throw new Error("cdkd: no SDK retry of a 5xx on a tokenless create");
1331
- const next = await strategy.refreshRetryTokenForRetry(token, errorInfo);
1332
- if ((ambiguous || replayed) && isObject(next)) afterAmbiguous.add(next);
1333
- return next;
1334
- },
1335
- recordSuccess: (token) => strategy.recordSuccess(token)
1336
- };
1337
- };
1338
- return client;
1339
- }
1340
-
1341
- // src/provisioning/created-resource-sink.ts
1342
- var CreatedResourceSink = class {
1343
- logicalId;
1344
- resourceType;
1345
- reports = [];
1346
- constructor(logicalId, resourceType) {
1347
- this.logicalId = logicalId;
1348
- this.resourceType = resourceType;
1349
- }
1350
- get report() {
1351
- return this.reports.at(-1);
1352
- }
1353
- record(report) {
1354
- this.reports.push(report);
1355
- }
1356
- clear() {
1357
- this.reports.length = 0;
1358
- }
1359
- retract(physicalId) {
1360
- for (let i = this.reports.length - 1; i >= 0; i--) if (this.reports[i].physicalId === physicalId) this.reports.splice(i, 1);
1361
- }
1362
- };
1363
- const storage = new AsyncLocalStorage();
1364
- function collectCreatedResources(sink, fn) {
1365
- return storage.run(sink, fn);
1366
- }
1367
- function clearCreatedReport() {
1368
- storage.getStore()?.clear();
1369
- }
1370
- function anchoredSink(ownerLogicalId, resourceType) {
1371
- const sink = storage.getStore();
1372
- return sink !== void 0 && sink.logicalId === ownerLogicalId && sink.resourceType === resourceType ? sink : void 0;
1373
- }
1374
- function reportCreatedResource(ownerLogicalId, resourceType, physicalId, createdResourceIdentity) {
1375
- try {
1376
- if (typeof physicalId !== "string" || physicalId === "") return;
1377
- anchoredSink(ownerLogicalId, resourceType)?.record({
1378
- physicalId,
1379
- ...typeof createdResourceIdentity === "string" && createdResourceIdentity !== "" && { createdResourceIdentity }
1380
- });
1381
- } catch {}
1382
- }
1383
- function reportedCreatedResource(ownerLogicalId, resourceType) {
1384
- try {
1385
- return anchoredSink(ownerLogicalId, resourceType)?.report;
1386
- } catch {
1387
- return;
1388
- }
1389
- }
1390
- function retractCreatedResource(ownerLogicalId, resourceType, physicalId) {
1391
- try {
1392
- anchoredSink(ownerLogicalId, resourceType)?.retract(physicalId);
1393
- } catch {}
1394
- }
1395
-
1396
- export { ElapsedBudget as $, buildLockContentionMessage as $t, readNameProperty as A, resourceTypeShown as At, rdsFamilyProtectionSite as B, carryCreatedBeforeFailure as Bt, VALUE_NOT_SHOWN as C, startInterruptWatch as Ct, isQuotableImportValue as D, compositeIdSkipResult as Dt, isPlainImportValue as E, compositeIdSeparatorRefusal as Et, markNotGone as F, isSecretDerivedValue as Ft, isFinalSnapshotNotAvailableRefusal as G, isAuxiliaryFailure as Gt, userPoolProtectionSite as H, createdBeforeFailure as Ht, compensateProtectionFlip as I, maskDeep as It, PROTECTION_FLIP_REUSE_WINDOW_MS as J, markCreatedBeforeFailure as Jt, isProceedDbStatus as K, isAuxiliaryMarkOf as Kt, deleteWithProtectionCompensation as L, maskerOrIdentity as Lt, remedyLogicalId as M, stateOrphanRecordRemedy as Mt, resolveExplicitPhysicalId as N, createMaskedLogSinks as Nt, normalizeAwsTagsToCfn as O, logicalIdShown as Ot, isMarkedNotGone as P, createMaskedRetryLogger as Pt, runDeleteAttempt as Q, buildForceUnlockCommand as Qt, logGroupProtectionSite as R, withDerivedNameMasks as Rt, holderRefusalRun as S, isInterruptedWaitError as St, isPlainImportJson as T, compositeIdFormatMessage as Tt, PROTECTION_FLIP_RETRY_WAIT_MS as U, createdResourceIdentityBeforeFailure as Ut, settleProtectionFlip as V, clearCreatedBeforeFailure as Vt, deleteAfterProtectionFlipWithFinalSnapshot as W, hasCreatedBeforeFailure as Wt, isTerminalDeleteFailure as X, replayMadeAnotherResource as Xt, ProtectionFlipRegistry as Y, markSupersedesEarlierCreate as Yt, protectionFlipKey as Z, UNREPRODUCIBLE_LOCK_CLAUSE as Zt, withoutServerErrorRetries as _, recordedPrincipalsRepair as _t, reportedCreatedResource as a, sanitizeRecoveryValue as an, isAwsCliLiteral as at, assertRegionMatch as b, endCommandInterruptScope as bt, AmbiguousCreateLatch as c, WAIT_CONDITION_SIGNAL_PREFIX as cn, renderDisableCommand as ct, ambiguousAttemptLead as d, withPasteableAwsProfile as dn, SECRET_DERIVED_READ_LIVE as dt, forceQuitRecoveryClause as en, ElapsedBudgetRegistry as et, createAttemptKey as f, injectiveKey as fn, diffPrincipalNames as ft, setBounded as g, readRecordedPrincipals as gt, replayedSendWindow as h, producerRecordKey as hn, readPrincipalLists as ht, reportCreatedResource as i, recoveryCommandFlags as in, WITHHELD_AWS_COMMAND as it, refusalTypeShown as j, segmentAfterAnchor as jt, quotedRemedyLogicalId as k, packCompositeId as kt, CREATION_DATE_SKEW_MARGIN_MS as l, setPasteableAwsCaBundle as ln, IAM_PRINCIPAL_NAME as lt, replayFollowedAmbiguousAttempt as m, producerCoordinateKey as mn, onlySecretDerived as mt, clearCreatedReport as n, formatLockOperation as nn, DELETION_PROTECTION_DOC_POINTER as nt, retractCreatedResource as o, CUSTOM_RESOURCE_RESPONSE_PREFIX as on, pasteableAwsCommand as ot, isInsideWindow as p, injectiveKeyPrefix as pn, holdsSecretDerivedEntry as pt, isTerminalDbWaitStatus as q, markAuxiliaryFailure as qt, collectCreatedResources as r, formatLockOwner as rn, UNNAMEABLE_ID_CLAUSE as rt, AMBIGUOUS_LATCH_TTL_MS as s, DEFAULT_STATE_PREFIX as sn, protectedReplacementAdvice as st, CreatedResourceSink as t, formatLockExpiry as tn, monotonicNowMs as tt, RecentIdSet as u, setPasteableAwsProfile as un, RESOLVED_PREVIOUS_PRINCIPAL_KEYS as ut, DriftReadRefusedError as v, withUnchangedSecretPrincipalLists as vt, importRemedyCommand as w, canonicalizeRoute53QueryName as wt, holderRefusalMask as x, interruptWatchListenerCount as xt, RESOURCE_NOT_FOUND as y, beginCommandInterruptScope as yt, observeThenDisableProtection as z, RETRY_AUXILIARY_OWNER as zt };
1397
- //# sourceMappingURL=created-resource-sink-DlVo2nqB.js.map