@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,1940 @@
1
+ import { ct as displayIdent, mt as safeMsg, n as getLogger, r as isStdoutReservedForPayload, rt as STACK_REF_MAX_CODE_POINTS, u as describeAwsFailure } from "./logger-DmQRya0S.js";
2
+ import { et as CdkdError, mt as commandHole, rt as LocalInvokeBuildError$1, ut as TIMEOUT_FLAG_RESOURCE_TYPE, xt as shellBoundedDisplay, yt as plainOrDescribed } from "./ambient-client-defaults-7acjxfyN.js";
3
+ import { a as getAssumedRoleCredentials, h as formatAuthority, n as awsClientDefaults, o as getPreAssumeEnvCredentials, s as runWithRealAws } from "./aws-client-defaults-DAebi99J.js";
4
+ import { Al as nullPrototypeRecord, Fl as displayAssemblyPath, Ga as applyRoleArnIfSet, Ja as explicitRoleArnOrThrow, Ll as renderAssemblyPathEscape, Ml as absoluteAssemblyPathEscape, Or as removeProtectionTypeList, Rl as resolveAssemblyPath, Ya as isIamRoleArn, ai as DEFAULT_RESOURCE_WARN_AFTER_MS, hl as getDockerImageBySourceHash, ii as DEFAULT_RESOURCE_TIMEOUT_MS, ml as AssetManifestLoader, qc as stringifyValue } from "./deploy-engine-DeYSJno7.js";
5
+ import { $ as injectedAwsRegionValue, C as runDockerForeground, Q as injectAwsRegion, S as getDockerCmd, _ as partitionSensitiveEnv, d as describeDockerFailure, g as finchSecretArgvRefusal, h as dockerSpawnEnvWithSensitive, l as describeDockerCapturedOutput, m as redactDockerArgvValues, v as warnFinchArgvExposure, w as runDockerStreaming } from "./diff-calculator-CRkRB1Dg.js";
6
+ import { n as canonicalizeRegion, r as derivePartitionAndUrlSuffix } from "./aws-partition-DA0r2sr-.js";
7
+ import { on as DEFAULT_STATE_PREFIX, sn as injectiveKey } from "./update-removal-D-FspP88.js";
8
+ import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
9
+ import * as path from "node:path";
10
+ import { dirname, isAbsolute, join, resolve } from "node:path";
11
+ import { execFile, execFileSync, spawn } from "node:child_process";
12
+ import { tmpdir } from "node:os";
13
+ import { HOST_GATEWAY_MIN_VERSION, LOOPBACK_FORWARDER_IMAGE, LocalInvokeBuildError, activateWorkloadAwsWiring, applyWorkloadAwsWiringToEnv, architectureToPlatform, attachLoopbackForwarder, awsEmulatorEnvName, buildContainerImage, derivePseudoParametersFromRegion, effectiveLoopbackPorts, ensureForwarderImage, firstUsableRegion, getActiveWorkloadAwsWiring, getActiveWorkloadAwsWiring as getActiveWorkloadAwsWiring$1, getAwsEndpointOverride, isAwsServiceRoutedToEmulator, isRealAwsSentinel, materializeLayerFromArn, noImplicitEcrPullArgs, probeHostGatewaySupport, recordAssumedRole, resolveAwsEmulatorOption, resolveHostDefaultCredentials, resolveHostGatewayExtraHosts, resolveRuntimeCodeMountPath, resolveRuntimeFileExtension, resolveRuntimeImage, substituteImagePlaceholders, takeAwsEmulatorStateSourceHint, tryResolveImageFnJoin } from "cdk-local/internal";
14
+ import { promisify } from "node:util";
15
+ import { Command, InvalidArgumentError, Option } from "commander";
16
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
17
+ import { createServer } from "node:net";
18
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
19
+
20
+ // src/cli/commands/state-file-keys.ts
21
+ const STATE_FILE_SUFFIX = "/state.json";
22
+ const LEGACY_SEGMENTS_UNDER_PREFIX = 1;
23
+ const LOCK_FILE_SUFFIX = "/lock.json";
24
+ const REGION_SEGMENT = /^(?:[a-z]{2}|eusc)(-[a-z]+)+-\d+$/;
25
+ async function listAllStateKeys(stateBackend) {
26
+ return (await stateBackend.listRawKeys("")).filter((k) => k.endsWith(STATE_FILE_SUFFIX));
27
+ }
28
+ async function listAllLockKeys(stateBackend) {
29
+ return (await stateBackend.listRawKeys("")).filter((k) => k.endsWith(LOCK_FILE_SUFFIX));
30
+ }
31
+ function parseStateKey(key, suffix = STATE_FILE_SUFFIX, knownPrefix) {
32
+ const body = key.slice(0, -suffix.length);
33
+ const prefix = knownPrefix?.replace(/\/+$/, "");
34
+ if (prefix !== void 0 && prefix !== "" && key.startsWith(`${prefix}/`)) {
35
+ const rest = body.slice(prefix.length + 1).split("/");
36
+ if (rest.length === LEGACY_SEGMENTS_UNDER_PREFIX && rest[0]) return { stack: rest[0] };
37
+ }
38
+ const segments = body.split("/");
39
+ const last = segments[segments.length - 1] ?? key;
40
+ const secondLast = segments[segments.length - 2];
41
+ if (secondLast !== void 0 && secondLast !== "" && REGION_SEGMENT.test(last)) return {
42
+ stack: secondLast,
43
+ region: last
44
+ };
45
+ return { stack: last };
46
+ }
47
+ function describeStateKey(key, suffix = STATE_FILE_SUFFIX, knownPrefix) {
48
+ const { stack, region } = parseStateKey(key, suffix, knownPrefix);
49
+ const name = displayIdent(stack, { maxCodePoints: STACK_REF_MAX_CODE_POINTS });
50
+ return region === void 0 ? name : `${name} (${displayIdent(region)})`;
51
+ }
52
+ const STATE_KEY_MAX_CODE_POINTS = STACK_REF_MAX_CODE_POINTS + 64;
53
+
54
+ // src/cli/options/resource-timeout.ts
55
+ function parseDuration(value) {
56
+ if (typeof value !== "string" || value.length === 0) throw new Error(`Invalid duration "${value}": expected <number>s, <number>m, or <number>h (e.g. 30s, 5m, 1h)`);
57
+ const match = /^(\d+(?:\.\d+)?)([smh])$/.exec(value.trim());
58
+ if (!match) throw new Error(`Invalid duration "${value}": expected <number>s, <number>m, or <number>h (e.g. 30s, 5m, 1h)`);
59
+ const num = Number(match[1]);
60
+ if (!Number.isFinite(num) || num <= 0) throw new Error(`Invalid duration "${value}": must be greater than zero`);
61
+ const unit = match[2];
62
+ return Math.round(num * (unit === "s" ? 1e3 : unit === "m" ? 6e4 : 36e5));
63
+ }
64
+ const RESOURCE_TYPE_REGEX = TIMEOUT_FLAG_RESOURCE_TYPE;
65
+ function parseResourceTimeoutToken(flagName) {
66
+ return (raw, previous) => {
67
+ const acc = previous ?? { perTypeMs: {} };
68
+ if (!acc.perTypeMs) acc.perTypeMs = {};
69
+ const eqIndex = raw.indexOf("=");
70
+ if (eqIndex === -1) {
71
+ acc.globalMs = parseDuration(raw);
72
+ return acc;
73
+ }
74
+ const typePart = raw.substring(0, eqIndex).trim();
75
+ const durationPart = raw.substring(eqIndex + 1).trim();
76
+ if (!RESOURCE_TYPE_REGEX.test(typePart)) throw new Error(`Invalid ${flagName} value "${raw}": left-hand side must be a CloudFormation resource type like AWS::Service::Resource (got "${typePart}")`);
77
+ if (durationPart.length === 0) throw new Error(`Invalid ${flagName} value "${raw}": missing duration after '=' (e.g. ${typePart}=1h)`);
78
+ let ms;
79
+ try {
80
+ ms = parseDuration(durationPart);
81
+ } catch (err) {
82
+ const inner = describeAwsFailure(err).detail;
83
+ throw new Error(`Invalid ${flagName} value "${raw}": ${inner}`);
84
+ }
85
+ acc.perTypeMs[typePart] = ms;
86
+ return acc;
87
+ };
88
+ }
89
+ const resourceTimeoutOptions = [new Option("--resource-warn-after <duration_or_type=duration>", "Warn when a single resource operation exceeds this wall-clock duration. Repeatable: pass a bare duration (e.g. 5m) to set the global default, or TYPE=DURATION (e.g. AWS::CloudFront::Distribution=10m) for a per-type override.").default(void 0, "5m").argParser(parseResourceTimeoutToken("--resource-warn-after")), new Option("--resource-timeout <duration_or_type=duration>", "Abort a single resource operation that exceeds this wall-clock duration. Repeatable: pass a bare duration (e.g. 30m) to set the global default, or TYPE=DURATION (e.g. AWS::CloudFront::Distribution=1h) for a per-type override. Custom-Resource-heavy stacks may need to raise this above the default 30m (the Custom Resource provider's polling cap is 1h). When this is shorter than the 5m --resource-warn-after default, --resource-warn-after is auto-lowered to min(5m, 0.5*timeout) and a warning is logged so the user can override explicitly.").default(void 0, "30m").argParser(parseResourceTimeoutToken("--resource-timeout"))];
90
+ function formatMs(ms) {
91
+ if (ms % 36e5 === 0) return `${ms / 36e5}h`;
92
+ if (ms % 6e4 === 0) return `${ms / 6e4}m`;
93
+ return `${Math.round(ms / 1e3)}s`;
94
+ }
95
+ function autoLoweredWarnMs(timeoutMs) {
96
+ return Math.max(1, Math.min(DEFAULT_RESOURCE_WARN_AFTER_MS, Math.floor(timeoutMs / 2)));
97
+ }
98
+ function validateResourceTimeouts(opts) {
99
+ const timeout = opts.resourceTimeout;
100
+ const globalWarn = opts.resourceWarnAfter?.globalMs;
101
+ const globalTimeout = timeout?.globalMs;
102
+ if (typeof globalWarn === "number" && typeof globalTimeout === "number") {
103
+ if (globalWarn >= globalTimeout) throw new Error(`--resource-warn-after (${globalWarn}ms) must be less than --resource-timeout (${globalTimeout}ms)`);
104
+ } else if (typeof globalTimeout === "number") {
105
+ if (3e5 >= globalTimeout) {
106
+ const lowered = autoLoweredWarnMs(globalTimeout);
107
+ ensureWarnAfter(opts).globalMs = lowered;
108
+ getLogger().warn(`--resource-warn-after defaulted to ${formatMs(lowered)} because --resource-timeout ${formatMs(globalTimeout)} is shorter than the ${formatMs(DEFAULT_RESOURCE_WARN_AFTER_MS)} default. Pass --resource-warn-after ${commandHole("duration")} explicitly to override.`);
109
+ }
110
+ } else if (typeof globalWarn === "number" && globalWarn >= 18e5) throw new Error(`--resource-warn-after (${formatMs(globalWarn)}) must be less than --resource-timeout (default ${formatMs(DEFAULT_RESOURCE_TIMEOUT_MS)}). Pass --resource-timeout ${commandHole("duration")} alongside it to raise the deadline.`);
111
+ const warnPerType = opts.resourceWarnAfter?.perTypeMs ?? {};
112
+ const timeoutPerType = timeout?.perTypeMs ?? {};
113
+ const types = /* @__PURE__ */ new Set([...Object.keys(warnPerType), ...Object.keys(timeoutPerType)]);
114
+ for (const t of types) {
115
+ const explicitPerTypeWarn = warnPerType[t];
116
+ const explicitPerTypeTimeout = timeoutPerType[t];
117
+ const effectiveGlobalWarn = opts.resourceWarnAfter?.globalMs;
118
+ const effectiveWarn = explicitPerTypeWarn ?? effectiveGlobalWarn ?? 3e5;
119
+ const effectiveTimeout = explicitPerTypeTimeout ?? globalTimeout ?? 18e5;
120
+ if (effectiveWarn < effectiveTimeout) continue;
121
+ if (explicitPerTypeWarn !== void 0 && explicitPerTypeTimeout !== void 0) throw new Error(`--resource-warn-after for ${t} (${formatMs(explicitPerTypeWarn)}) must be less than --resource-timeout for ${t} (${formatMs(explicitPerTypeTimeout)})`);
122
+ if (explicitPerTypeWarn !== void 0) throw new Error(`--resource-warn-after for ${t} (${formatMs(explicitPerTypeWarn)}) must be less than --resource-timeout for ${t} (${formatMs(effectiveTimeout)}). Pass --resource-timeout ${t}=${commandHole("duration")} alongside it to raise the deadline.`);
123
+ const lowered = autoLoweredWarnMs(effectiveTimeout);
124
+ ensureWarnAfter(opts).perTypeMs[t] = lowered;
125
+ getLogger().warn(`--resource-warn-after for ${t} defaulted to ${formatMs(lowered)} because --resource-timeout for ${t} (${formatMs(effectiveTimeout)}) is shorter than the inherited ${formatMs(effectiveWarn)} warn. Pass --resource-warn-after ${t}=${commandHole("duration")} explicitly to override.`);
126
+ }
127
+ }
128
+ function ensureWarnAfter(opts) {
129
+ if (!opts.resourceWarnAfter) opts.resourceWarnAfter = { perTypeMs: {} };
130
+ if (!opts.resourceWarnAfter.perTypeMs) opts.resourceWarnAfter.perTypeMs = {};
131
+ return opts.resourceWarnAfter;
132
+ }
133
+
134
+ // src/cli/options/provisioning-route.ts
135
+ const RESOURCE_TYPE_FORMAT = /^[A-Z][A-Za-z0-9]+(::[A-Z][A-Za-z0-9]+)+$/;
136
+ function parseAllowUnsupportedTypesToken(value, previous) {
137
+ const parsed = value.split(",").map((s) => s.trim()).filter(Boolean);
138
+ for (const token of parsed) if (!RESOURCE_TYPE_FORMAT.test(token)) throw new Error(`Invalid --allow-unsupported-types value "${token}": expected a CloudFormation resource type like AWS::Service::Type or Custom::Foo.`);
139
+ return [...previous ?? [], ...parsed];
140
+ }
141
+ const allowUnsupportedTypesOption = new Option("--allow-unsupported-types <types>", "Comma-separated resource types to attempt via Cloud Control even though cdkd reports them unsupported (AWS NON_PROVISIONABLE). Escape hatch — Cloud Control will likely still fail. Example: --allow-unsupported-types AWS::Foo::Bar,AWS::Baz::Qux").argParser(parseAllowUnsupportedTypesToken);
142
+ const RESOURCE_PROPERTY_FORMAT = /^[A-Z][A-Za-z0-9]+(::[A-Z][A-Za-z0-9]+)+:[A-Z][A-Za-z0-9]*$/;
143
+ function parseRouteEntries(value, previous, flag) {
144
+ const parsed = value.split(",").map((s) => s.trim()).filter(Boolean);
145
+ for (const token of parsed) {
146
+ if (!RESOURCE_PROPERTY_FORMAT.test(token)) throw new Error(`Invalid ${flag} value "${token}": expected <ResourceType>:<PropertyName> with PascalCase on both halves (e.g. AWS::ApiGatewayV2::Api:Body).`);
147
+ if (token.startsWith("Custom::")) throw new Error(`Invalid ${flag} value "${token}": Custom:: resources are routed through cfn-response and have no SDK-unwired properties at cdkd, so the flag would have no effect. Use --allow-unsupported-types for type-level escape hatches instead.`);
148
+ }
149
+ return [...previous ?? [], ...parsed];
150
+ }
151
+ function parsePreferSdkRouteToken(value, previous) {
152
+ return parseRouteEntries(value, previous, "--prefer-sdk-route");
153
+ }
154
+ let deprecatedAliasWarned = false;
155
+ function parseAllowUnsupportedPropertiesToken(value, previous) {
156
+ if (!deprecatedAliasWarned) {
157
+ deprecatedAliasWarned = true;
158
+ process.stderr.write("--allow-unsupported-properties is deprecated and will be removed in the first minor release after 2026-12-01; use --prefer-sdk-route, which takes the same <ResourceType>:<PropertyName> tokens and does the same thing. The old name reads as the opposite of its behaviour: it does not make the property reach AWS, it keeps the resource on the SDK provider and accepts that the value is NOT written.\n");
159
+ }
160
+ return parseRouteEntries(value, previous, "--allow-unsupported-properties");
161
+ }
162
+ const preferSdkRouteOption = new Option("--prefer-sdk-route <entries>", "Comma-separated <ResourceType>:<PropertyName> tokens to keep on the SDK provider instead of auto-routing the resource to Cloud Control. The named values are then NOT written to AWS — the deployed resource is missing the field. Ignored for a resource that routes to Cloud Control for another reason (a sibling unwired property, or a sticky cc-api state record), where the values are written after all. Example: --prefer-sdk-route AWS::ApiGatewayV2::Api:Body").argParser(parsePreferSdkRouteToken);
163
+ const allowUnsupportedPropertiesOption = new Option("--allow-unsupported-properties <entries>", "Deprecated alias for --prefer-sdk-route.").argParser(parseAllowUnsupportedPropertiesToken).hideHelp();
164
+ const LOGICAL_ID_FORMAT = /^[A-Za-z][A-Za-z0-9]{0,254}$/;
165
+ function parseRecreateViaCcApiToken(value, previous) {
166
+ const token = value.trim();
167
+ if (!LOGICAL_ID_FORMAT.test(token)) throw new Error(`Invalid --recreate-via-cc-api value "${value}": expected a CloudFormation logical id (alphanumeric, starts with a letter, max 255 chars). One --recreate-via-cc-api flag per resource — repeat the flag for additional targets.`);
168
+ return [...previous ?? [], token];
169
+ }
170
+ const recreateViaCcApiOption = new Option("--recreate-via-cc-api <logicalId>", "Destroy + recreate the named resource (by CloudFormation logical id) via Cloud Control API in this deploy, so a top-level CFn property the SDK provider does not write reaches AWS via CC. Repeatable — pass the flag once per resource. Per-resource opt-in (no bulk / no per-stack shortcut) so the destroy-and-recreate cost is acknowledged for each target. Stateful resource types (RDS, DynamoDB, S3, EFS, ...) refuse unless --force-stateful-recreation is ALSO passed (two-flag protection). Cannot be combined with --prefer-sdk-route on the same resource type and property. Refused, with no bypass, for a type Cloud Control cannot create (NON_PROVISIONABLE).").argParser(parseRecreateViaCcApiToken);
171
+ function parseRecreateViaSdkProviderToken(value, previous) {
172
+ const token = value.trim();
173
+ if (!LOGICAL_ID_FORMAT.test(token)) throw new Error(`Invalid --recreate-via-sdk-provider value "${value}": expected a CloudFormation logical id (alphanumeric, starts with a letter, max 255 chars). One --recreate-via-sdk-provider flag per resource — repeat the flag for additional targets.`);
174
+ return [...previous ?? [], token];
175
+ }
176
+ function parsePinCcApiToken(value, previous) {
177
+ const token = value.trim();
178
+ if (!LOGICAL_ID_FORMAT.test(token)) throw new Error(`Invalid --pin-cc-api value "${value}": expected a CloudFormation logical id (alphanumeric, starts with a letter, max 255 chars). One --pin-cc-api flag per resource — repeat the flag for additional targets.`);
179
+ return [...previous ?? [], token];
180
+ }
181
+ const pinCcApiOption = new Option("--pin-cc-api <logicalId>", "Keep the named resource (by CloudFormation logical id) on the Cloud Control route in this deploy, declining the automatic return to the SDK Provider that a type-level sdk-coverage exemption would otherwise apply to a resource recorded as provisionedBy: cc-api. Repeatable — pass the flag once per resource. Has no effect on a resource already on the SDK path, and does not override an exemption admitted because Cloud Control cannot manage the type.").argParser(parsePinCcApiToken);
182
+ const recreateViaSdkProviderOption = new Option("--recreate-via-sdk-provider <logicalId>", "Destroy + recreate the named resource (by CloudFormation logical id) via cdkd's SDK Provider in this deploy, so a resource currently sticky on provisionedBy: cc-api flips back to provisionedBy: sdk. Used after a release adds SDK coverage for a type the user originally needed CC for (e.g. Lambda LoggingConfig). Repeatable — pass the flag once per resource. Per-resource opt-in. Stateful resource types refuse unless --force-stateful-recreation is ALSO passed.").argParser(parseRecreateViaSdkProviderToken);
183
+
184
+ // src/cli/options/assume-role.ts
185
+ function parseAssumeRoleToken(raw, previous) {
186
+ const acc = previous ?? { perLambda: nullPrototypeRecord() };
187
+ if (!acc.perLambda) acc.perLambda = nullPrototypeRecord();
188
+ const shownRaw = quotedArgv(raw, 613);
189
+ const eqIndex = raw.trim().startsWith("arn:") ? -1 : raw.indexOf("=");
190
+ if (eqIndex === -1) {
191
+ const bare = raw.trim();
192
+ if (!isIamRoleArn(bare)) throw new Error(`Invalid --assume-role value ${shownRaw}: expected an IAM role ARN like arn:aws:iam::123456789012:role/MyRole, or LogicalId='<arn>'.`);
193
+ acc.globalArn = bare;
194
+ return acc;
195
+ }
196
+ const logicalId = raw.substring(0, eqIndex).trim();
197
+ const arn = raw.substring(eqIndex + 1).trim();
198
+ if (!/^[A-Za-z][A-Za-z0-9]*$/.test(logicalId)) throw new Error(`Invalid --assume-role value ${shownRaw}: left-hand side ${quotedArgv(logicalId)} must be a CloudFormation logical ID (alphanumeric, leading letter).`);
199
+ if (!isIamRoleArn(arn)) throw new Error(`Invalid --assume-role value ${shownRaw}: right-hand side ${quotedArgv(arn, 613)} must be an IAM role ARN like arn:aws:iam::123456789012:role/MyRole.`);
200
+ acc.perLambda[logicalId] = arn;
201
+ return acc;
202
+ }
203
+ function quotedArgv(value, maxCodePoints) {
204
+ const shown = displayIdent(value, maxCodePoints === void 0 ? void 0 : { maxCodePoints });
205
+ return !/\s/.test(value) && shown === value ? `"${value}"` : shellBoundedDisplay(shown);
206
+ }
207
+ function normalizeStartApiAssumeRole(raw, autoResolve) {
208
+ if (raw === void 0) return autoResolve ? {
209
+ perLambda: nullPrototypeRecord(),
210
+ bareAutoResolve: true
211
+ } : void 0;
212
+ if (autoResolve && raw.globalArn) throw new Error(`--assume-role-auto auto-resolves EACH routed Lambda's own execution role, but --assume-role ${quotedArgv(raw.globalArn, 613)} also names a single global default. These are mutually exclusive on the global slot. Either drop the global ARN to keep --assume-role-auto for every Lambda, or drop --assume-role-auto to keep the global default. Per-Lambda overrides (--assume-role '<LogicalId>'='<arn>') are compatible with either side.`);
213
+ if (autoResolve) raw.bareAutoResolve = true;
214
+ return raw;
215
+ }
216
+ function effectiveAssumeRoleArn(logicalId, opt) {
217
+ if (!opt) return void 0;
218
+ const perLambda = opt.perLambda;
219
+ if (perLambda && Object.hasOwn(perLambda, logicalId)) return perLambda[logicalId];
220
+ return opt.globalArn;
221
+ }
222
+
223
+ // src/cli/options.ts
224
+ function parseContextOptions(contextArgs) {
225
+ const context = nullPrototypeRecord();
226
+ if (contextArgs) for (const arg of contextArgs) {
227
+ const eqIndex = arg.indexOf("=");
228
+ if (eqIndex > 0) context[arg.substring(0, eqIndex)] = arg.substring(eqIndex + 1);
229
+ }
230
+ return context;
231
+ }
232
+ const commonOptions = [
233
+ new Option("--verbose", "Enable verbose logging").default(false),
234
+ new Option("--profile <profile>", "AWS profile"),
235
+ new Option("--role-arn <arn>", "IAM role ARN to assume for AWS API calls (env: CDKD_ROLE_ARN); the role needs the actions for the resource types you deploy plus the bookkeeping actions cdkd itself issues, because cdkd makes raw service API calls and does not route through CloudFormation, so CDK CLI deploy-roles will NOT work. Combines with --profile: the profile supplies the base credentials the role is assumed FROM, and the role is what every later AWS call runs as"),
236
+ new Option("-y, --yes", "Automatically answer interactive prompts with the recommended response (e.g. confirm destroy)").default(false)
237
+ ];
238
+ const deprecatedRegionOption = new Option("--region <region>", "[deprecated] Prefer AWS_REGION or your AWS profile; --region is still honored but will be removed in a future release").hideHelp();
239
+ function warnIfDeprecatedRegion(options) {
240
+ if (options.region !== void 0) process.stderr.write("Warning: --region is deprecated and will be removed in a future release. It is still honored for now (it overrides AWS_REGION / your AWS profile), but prefer the AWS_REGION environment variable or your AWS profile to choose the region.\n");
241
+ }
242
+ const appOptions = [new Option("-a, --app <command>", "CDK app command (e.g., \"node app.ts\") or path to a pre-synthesized cloud assembly directory. Falls back to cdk.json or CDKD_APP env"), new Option("--output <path>", "Output directory for synthesis").default("cdk.out")];
243
+ const stateOptions = [new Option("--state-bucket <bucket>", "S3 bucket for state storage. Falls back to CDKD_STATE_BUCKET env or cdk.json"), new Option("--state-prefix <prefix>", "S3 key prefix for state files").default(DEFAULT_STATE_PREFIX).argParser(parseStatePrefix)];
244
+ function parseStatePrefix(value) {
245
+ if (value.includes("<") || value.includes(">")) throw new InvalidArgumentError("a state prefix cannot contain '<' or '>': that is a placeholder cdkd printed in a suggested command for a value it could not show. Replace it with your actual prefix.");
246
+ return value;
247
+ }
248
+ const stackOptions = [new Option("--stack <name>", "Stack name to operate on")];
249
+ function parseStackRegion(value) {
250
+ if (value.trim() === "") throw new InvalidArgumentError(`expected a region name (e.g. us-east-1), got ${value === "" ? "an empty value" : "whitespace only"}. Omit the flag entirely to operate on every region a stack has state in.`);
251
+ return value;
252
+ }
253
+ function guardStackRegionOptions(cmd) {
254
+ for (const option of cmd.options) if (option.long === "--stack-region" && option.parseArg === void 0) option.argParser(parseStackRegion);
255
+ for (const sub of cmd.commands) guardStackRegionOptions(sub);
256
+ }
257
+ const noWaitOption = new Option("--no-wait", "Skip waiting for async resources to stabilize (RDS, ElastiCache, NAT Gateway, EC2 Instance, ELBv2 LoadBalancer, Lambda MicroVM Image, ECS Service steady state)");
258
+ const fullWaitOption = new Option("--full-wait", "Also wait for stabilizations cdkd skips by default, matching CloudFormation (CloudFront Distribution Deployed, RDS Multi-AZ DB cluster storage optimization; raise --resource-timeout AWS::RDS::DBCluster for a long one)");
259
+ function validateWaitFlags(opts) {
260
+ if (opts.wait === false && opts.fullWait === true) throw new Error("--no-wait and --full-wait cannot be combined: --no-wait skips stabilization waits, --full-wait adds them. Pick one.");
261
+ }
262
+ function applyWaitFlagEnv(opts) {
263
+ validateWaitFlags(opts);
264
+ process.env["CDKD_WAIT_FLAGS_AVAILABLE"] = "true";
265
+ if (opts.wait === false) process.env["CDKD_NO_WAIT"] = "true";
266
+ if (opts.fullWait === true) process.env["CDKD_FULL_WAIT"] = "true";
267
+ }
268
+ const aggressiveVpcParallelOption = new Option("--no-aggressive-vpc-parallel", "Disable the default relaxation of CDK-injected VPC route DependsOn (on by default; opt out to keep the strict CDK ordering)");
269
+ const forceStatefulRecreationOption = new Option("--force-stateful-recreation", "Confirm a data-losing destroy + recreate of a stateful resource. Required whenever a replacement target is a stateful type on the --recreate-via-cc-api / --recreate-via-sdk-provider pre-flight, with --replace, AND on the paths a plain deploy reaches with no flag: a template immutable-property change, and an in-place update the provisioning layer rejects. Stateful types are databases, filesystems, KMS keys, table / vector storage, source repositories, and more; https://cdkd.dev/cli-deploy-safety/ carries the full list. S3 buckets and log groups are the conditional cases: at pre-flight, a non-empty bucket, or a log group with retention, with log streams, or whose emptiness the probe could not settle; mid-deploy, ANY bucket or log group, because the emptiness probe cannot run there. The two probes differ on failure — the bucket fails open, the log group closed. Destroy + recreate loses ALL data in the resource — no automatic data migration. Full opt-in for CI use: --recreate-via-cc-api '<id>' --force-stateful-recreation --yes.").default(false);
270
+ const replaceOption = new Option("--replace", "Replace (DELETE + CREATE) a resource whose in-place update is rejected because an immutable property changed and AWS exposes no update API for it (e.g. Lambda LayerVersion content, EFS AccessPoint, ECS TaskDefinition, ApiGatewayV2 immutable fields). Without this flag such a change fails the deploy. Stateful types (RDS / DynamoDB / EFS / any S3 bucket / any Logs log group / etc.) ALSO require --force-stateful-recreation since the replacement is a data-losing DELETE + CREATE — mid-deploy neither emptiness probe can run, so both conditional types count as stateful there.").default(false);
271
+ const useCdkBootstrapAssetsOption = new Option("--use-cdk-bootstrap-assets", "Publish assets to the CDK bootstrap bucket/repo named by the asset manifest verbatim, skipping the cdkd asset-storage redirection even when this region is opted in via 'cdkd bootstrap'. For apps deployed via both CloudFormation and cdkd during a migration window. Per-app pin: cdk.json context.cdkd.useCdkBootstrapAssets. Also suppresses the legacy-mode 'cdk gc' notice.").default(false);
272
+ const strictGetattOption = new Option("--strict-getatt", "Fail the deploy on ANY Fn::GetAtt that falls back to the physical ID because cdkd cannot construct the attribute (default: warn and use the physical ID, hard-failing only when the fallback is knowably wrong — an *Arn attribute with a non-ARN value or a *Url attribute with a non-http(s) value). Also fails the deploy when a stack Output cannot be resolved (default: warn and store no value).").default(false);
273
+ const allowUnaddressedOption = new Option("--allow-unaddressed", "Exit 0 even when the deploy left a resource unaddressed — a DELETE the provider could not issue, or a replacement whose old resource survives untracked (default: exit 2, matching cdkd destroy). The summary rows and warnings are printed either way; only the exit code changes.").default(false);
274
+ const noCfnFallbackOption = new Option("--no-cfn-fallback", "Do not fall back to CloudFormation (ListExports / stack outputs) when an Fn::ImportValue / Fn::GetStackOutput reference is not found in cdkd state (default: fall back, so producers still managed by CloudFormation can be referenced)");
275
+ const annotationMessageOptions = [new Option("--strict", "Do not proceed with stacks carrying warning annotations").default(false), new Option("--ignore-errors", "Ignore error annotations from stack synthesis, which will likely produce an invalid deployment").default(false)];
276
+ function exclusivelyOption(command) {
277
+ return new Option("-e, --exclusively", command === "deploy" ? "Only deploy requested stacks, do not include dependencies" : "Only destroy requested stacks, do not include the stacks that depend on them").default(false);
278
+ }
279
+ const deployOptions = [
280
+ new Option("--concurrency <number>", "Maximum concurrent resource operations").default(20).argParser((value) => parseInt(value, 10)),
281
+ new Option("--stack-concurrency <number>", "Maximum concurrent stack deployments").default(4).argParser((value) => parseInt(value, 10)),
282
+ new Option("--asset-publish-concurrency <number>", "Maximum concurrent asset publish operations (S3 uploads + ECR push)").default(8).argParser((value) => parseInt(value, 10)),
283
+ new Option("--image-build-concurrency <number>", "Maximum concurrent Docker image builds").default(4).argParser((value) => parseInt(value, 10)),
284
+ new Option("--dry-run", "Show changes without applying").default(false),
285
+ new Option("--skip-assets", "Skip asset publishing").default(false),
286
+ new Option("--no-rollback", "Skip rollback on deployment failure"),
287
+ new Option("--no-auto-asset-storage", "Do not auto-create cdkd-owned asset storage (asset bucket + container-asset ECR repo + marker) on the first deploy into a region not yet opted in via 'cdkd bootstrap'. Deploys into such regions stay in legacy mode (CDK bootstrap destinations). Per-app opt-out: cdk.json context.cdkd.autoAssetStorage: false."),
288
+ new Option("--no-capture-observed-state", "Skip capturing AWS-current properties after each create/update (adds a fire-and-forget readCurrentState per resource so cdkd drift can compare against the real deploy-time AWS snapshot instead of the template). On by default. Disable when deploy speed matters more than rich drift detection — falls back to comparing against template properties (the pre-v3 behavior)."),
289
+ new Option("--prefix-user-supplied-names", "Opt in to LEGACY behavior: prepend the stack name to physical names the user explicitly supplied in their CDK code (e.g. `new iam.Role(this, \"X\", { roleName: \"my-role\" })` → AWS resource named `MyStack-my-role` instead of `my-role`). Since v0.94.0 the default is to NOT prefix user-supplied names — this flag restores the pre-v0.94.0 behavior on Pattern B providers (IAM Role / User / Group / InstanceProfile / ManagedPolicy / ELBv2 LoadBalancer / TargetGroup). Enable via this flag, CDKD_PREFIX_USER_SUPPLIED_NAMES=true, or cdk.json context.cdkd.prefixUserSuppliedNames=true. Applies to `cdkd deploy` only.").default(false),
290
+ noWaitOption,
291
+ fullWaitOption,
292
+ aggressiveVpcParallelOption,
293
+ exclusivelyOption("deploy"),
294
+ allowUnsupportedTypesOption,
295
+ preferSdkRouteOption,
296
+ allowUnsupportedPropertiesOption,
297
+ recreateViaCcApiOption,
298
+ recreateViaSdkProviderOption,
299
+ pinCcApiOption,
300
+ forceStatefulRecreationOption,
301
+ replaceOption,
302
+ useCdkBootstrapAssetsOption,
303
+ strictGetattOption,
304
+ noCfnFallbackOption,
305
+ allowUnaddressedOption,
306
+ ...resourceTimeoutOptions
307
+ ];
308
+ const contextOptions = [new Option("-c, --context <key=value...>", "Set context values (can be specified multiple times)")];
309
+ const destroyOptions = [
310
+ new Option("-f, --force", "Do not ask for confirmation before destroying the stacks").default(false),
311
+ new Option("--remove-protection", `Bypass deletion protection on protected resources by flipping the per-resource protection flag off in-place before delete. Covers stack-level terminationProtection (CDK property) and resource-level protection on ${removeProtectionTypeList()}.`).default(false),
312
+ allowUnsupportedTypesOption
313
+ ];
314
+ const skipFinalSnapshotOption = new Option("--skip-final-snapshot", "Delete resources whose DeletionPolicy (or, on replacements, UpdateReplacePolicy) is 'Snapshot' — including an RDS DB cluster or standalone DB instance with no DeletionPolicy, whose CloudFormation default is 'Snapshot' — WITHOUT creating the final snapshot the policy promises (DATA LOSS — explicit opt-out of CloudFormation parity). By default cdkd creates the final snapshot for every CloudFormation-supported type (RDS DBInstance / DBCluster, Neptune / DocDB clusters, ElastiCache CacheCluster / ReplicationGroup, Redshift Cluster, EC2 Volume) and refuses the delete when it cannot — e.g. a resource managed via the Cloud Control API route, whose delete has no final-snapshot parameter. On 'cdkd rollback' the flag governs the rolled-back CREATE's DeletionPolicy; a reverse-replacement delete of the NEW resource keeps its own bounded UpdateReplacePolicy behavior and is unaffected.").default(false);
315
+ const noLocalCustomResourcesOption = new Option("--no-local-custom-resources", "Under --aws-emulator, invoke custom resource functions in AWS Emulator's own Lambda runtime instead of running them locally in the official Lambda runtime image (Docker). A no-op without --aws-emulator.");
316
+
317
+ // src/local/local-role-arn.ts
318
+ async function applyRoleArnForLocal(opts) {
319
+ if (getActiveWorkloadAwsWiring()?.mixed) await runWithRealAws(() => applyRoleArnIfSet(opts));
320
+ else await applyRoleArnIfSet(opts);
321
+ const role = getAssumedRoleCredentials();
322
+ if (role === void 0) return;
323
+ recordAssumedRole(getPreAssumeEnvCredentials(), {
324
+ accessKeyId: role.accessKeyId,
325
+ secretAccessKey: role.secretAccessKey,
326
+ sessionToken: role.sessionToken
327
+ });
328
+ }
329
+
330
+ // src/cli/commands/local-profile-credentials-file.ts
331
+ const CONTAINER_AWS_CREDENTIALS_PATH = "/cdkd-aws/credentials";
332
+ async function writeProfileCredentialsFile(profileName, creds, opts) {
333
+ if (profileName === "") throw new Error("writeProfileCredentialsFile: profile name must not be empty.");
334
+ if (/[\r\n[\]]/.test(profileName)) throw new Error(`writeProfileCredentialsFile: profile name ${displayIdent(profileName)} contains a forbidden character (any of CR, LF, '[', ']' would corrupt the INI file or the docker -e env var).`);
335
+ const dir = await mkdtemp(path.join(tmpdir(), "cdkd-profile-creds-"));
336
+ const hostPath = path.join(dir, "credentials");
337
+ opts?.onDirCreated?.(hostPath);
338
+ const lines = [
339
+ `[${profileName}]`,
340
+ `aws_access_key_id = ${creds.accessKeyId}`,
341
+ `aws_secret_access_key = ${creds.secretAccessKey}`
342
+ ];
343
+ if (creds.sessionToken) lines.push(`aws_session_token = ${creds.sessionToken}`);
344
+ try {
345
+ await writeFile(hostPath, lines.join("\n") + "\n", { mode: 384 });
346
+ } catch (err) {
347
+ let removed = true;
348
+ await rm(dir, {
349
+ recursive: true,
350
+ force: true
351
+ }).catch(() => {
352
+ removed = false;
353
+ });
354
+ if (removed) try {
355
+ opts?.onDirRemoved?.(hostPath);
356
+ } catch {}
357
+ throw err;
358
+ }
359
+ return {
360
+ hostPath,
361
+ containerPath: CONTAINER_AWS_CREDENTIALS_PATH,
362
+ profileName,
363
+ dispose: async () => {
364
+ await rm(dir, {
365
+ recursive: true,
366
+ force: true
367
+ });
368
+ }
369
+ };
370
+ }
371
+ function strandedProfileCredentialsNotice(hostPath) {
372
+ if (hostPath === void 0) return void 0;
373
+ return `The AWS credentials file mounted into the containers is NOT removed: delete ${displayIdent(hostPath)} once you tear them down.`;
374
+ }
375
+
376
+ // src/cli/region-options.ts
377
+ function foldRegionOption(options) {
378
+ if (options.region !== void 0) options.region = canonicalizeRegion(options.region);
379
+ for (const key of ["AWS_REGION", "AWS_DEFAULT_REGION"]) {
380
+ const value = process.env[key];
381
+ if (value) process.env[key] = canonicalizeRegion(value);
382
+ }
383
+ }
384
+ function namedCliRegion(optionRegion) {
385
+ return canonicalizeRegion(optionRegion || process.env["AWS_REGION"]) || void 0;
386
+ }
387
+ function rawCliRegion(optionRegion) {
388
+ return optionRegion || process.env["AWS_REGION"] || void 0;
389
+ }
390
+ async function resolveEffectiveRegion(options) {
391
+ const flag = canonicalizeRegion(options.region);
392
+ if (flag) return {
393
+ region: flag,
394
+ source: "flag"
395
+ };
396
+ const awsRegion = canonicalizeRegion(process.env["AWS_REGION"]);
397
+ if (awsRegion && awsRegion === injectedAwsRegionValue()) return {
398
+ region: awsRegion,
399
+ source: "default-env"
400
+ };
401
+ if (awsRegion) return {
402
+ region: awsRegion,
403
+ source: "env"
404
+ };
405
+ const defaultRegionEnv = canonicalizeRegion(process.env["AWS_DEFAULT_REGION"]);
406
+ if (defaultRegionEnv) return {
407
+ region: defaultRegionEnv,
408
+ source: "default-env"
409
+ };
410
+ const fromProfile = canonicalizeRegion(await resolveSdkDefaultRegion(options.profile));
411
+ if (fromProfile) return {
412
+ region: fromProfile,
413
+ source: "profile"
414
+ };
415
+ return {
416
+ region: LEGACY_DEFAULT_REGION,
417
+ source: "default"
418
+ };
419
+ }
420
+ function exportInferredRegionForSdk(effective) {
421
+ if (effective.source !== "default-env") return;
422
+ injectAwsRegion(effective.region);
423
+ }
424
+ const LEGACY_DEFAULT_REGION = "us-east-1";
425
+ async function resolveSdkDefaultRegion(profile) {
426
+ const { STSClient } = await import("@aws-sdk/client-sts");
427
+ let client;
428
+ try {
429
+ client = new STSClient({
430
+ ...awsClientDefaults({ profile }),
431
+ ...profile && { profile }
432
+ });
433
+ return await client.config.region() || void 0;
434
+ } catch {
435
+ return;
436
+ } finally {
437
+ client?.destroy?.();
438
+ }
439
+ }
440
+ function ownedByLegacyDefault(probe) {
441
+ return { stateExists: (stackName, region) => probe.stateExistsOwnedBy(stackName, region, LEGACY_DEFAULT_REGION) };
442
+ }
443
+ async function placeStack(effective, stackName, probe) {
444
+ const [inResolved, inLegacy] = await Promise.all([probe.stateExists(stackName, effective.region), probe.stateExists(stackName, LEGACY_DEFAULT_REGION)]);
445
+ if (inResolved && inLegacy) return "both";
446
+ if (inResolved) return "resolved";
447
+ return inLegacy ? "legacy" : "none";
448
+ }
449
+ function bothRegionsMessage(effective, stackName) {
450
+ return `Stack ${quoteStackName(stackName)} has state in both ${LEGACY_DEFAULT_REGION} and ${displayIdent(effective.region)} (which ${inferredFrom(effective)} resolves). Continuing to use ${LEGACY_DEFAULT_REGION}, as a command with no region named did before. Set AWS_REGION=${displayIdent(effective.region)} to work on the ${displayIdent(effective.region)} one, or AWS_REGION=${LEGACY_DEFAULT_REGION} to silence this message.`;
451
+ }
452
+ function inferredFrom(effective) {
453
+ return effective.source === "default-env" ? "AWS_DEFAULT_REGION" : "your AWS profile";
454
+ }
455
+ function holdMessage(effective, stackName) {
456
+ return `Stack ${quoteStackName(stackName)} has existing state in ${LEGACY_DEFAULT_REGION}, but ${inferredFrom(effective)} resolves ${displayIdent(effective.region)}. Continuing to use ${LEGACY_DEFAULT_REGION} so the existing stack is not duplicated. Set AWS_REGION=${LEGACY_DEFAULT_REGION} to silence this message, or AWS_REGION=${displayIdent(effective.region)} to work in ${displayIdent(effective.region)} instead (where this stack has no state).`;
457
+ }
458
+ function quoteStackName(stackName) {
459
+ return displayIdent(stackName) === stackName ? `'${stackName}'` : "a stack whose name is not a plain identifier";
460
+ }
461
+ function stackRegionResolver(input) {
462
+ const { effective, logger } = input;
463
+ const probe = ownedByLegacyDefault(input.probe);
464
+ const placements = /* @__PURE__ */ new Map();
465
+ const place = (stackName) => {
466
+ let placement = placements.get(stackName);
467
+ if (placement === void 0) {
468
+ placement = placeStack(effective, stackName, probe);
469
+ placement.catch(() => placements.delete(stackName));
470
+ placements.set(stackName, placement);
471
+ }
472
+ return placement;
473
+ };
474
+ const answers = /* @__PURE__ */ new Map();
475
+ const answer = async (stackName) => {
476
+ const placement = await place(stackName);
477
+ if (placement === "legacy" || placement === "both") {
478
+ logger.info(placement === "both" ? bothRegionsMessage(effective, stackName) : holdMessage(effective, stackName));
479
+ return LEGACY_DEFAULT_REGION;
480
+ }
481
+ if (placement === "resolved") return effective.region;
482
+ const others = (input.siblings ?? []).filter((name) => name !== stackName);
483
+ const siblingPlacements = await Promise.all(others.map(place));
484
+ if (siblingPlacements.some((p) => p === "legacy" || p === "both") && !siblingPlacements.includes("resolved")) {
485
+ logger.info(`Stack ${quoteStackName(stackName)} has no state yet, and the other stacks of this app that have state all stay in ${LEGACY_DEFAULT_REGION}, while ${inferredFrom(effective)} resolves ${displayIdent(effective.region)}. Using ${LEGACY_DEFAULT_REGION} for it too, so the app stays in one region. Set AWS_REGION=${LEGACY_DEFAULT_REGION} to silence this message.`);
486
+ return LEGACY_DEFAULT_REGION;
487
+ }
488
+ return effective.region;
489
+ };
490
+ return (stackName, pinned) => {
491
+ if (pinned) return Promise.resolve(pinned);
492
+ if (!regionNeedsReconciliation(effective)) return Promise.resolve(effective.region);
493
+ let result = answers.get(stackName);
494
+ if (result === void 0) {
495
+ result = answer(stackName);
496
+ result.catch(() => answers.delete(stackName));
497
+ answers.set(stackName, result);
498
+ }
499
+ return result;
500
+ };
501
+ }
502
+ function stateWithRegion(state, region) {
503
+ return state.region ? state : {
504
+ ...state,
505
+ region
506
+ };
507
+ }
508
+ function legacyStateBucketFallbackRegion(effective) {
509
+ return regionNeedsReconciliation(effective) ? LEGACY_DEFAULT_REGION : void 0;
510
+ }
511
+ async function reconcileExportIndexRegion(input) {
512
+ const { effective, probe, statePrefix, logger } = input;
513
+ if (!regionNeedsReconciliation(effective)) return effective.region;
514
+ const indexKey = (region) => `${statePrefix}/_index/${region}/exports.json`;
515
+ try {
516
+ if (!await probe.rawObjectExists(indexKey("us-east-1"))) return effective.region;
517
+ } catch (error) {
518
+ logger.warn(safeMsg`[region] could not probe the exports index (${error.name ?? "error"}); using ${effective.region}.`);
519
+ return effective.region;
520
+ }
521
+ logger.debug(safeMsg`[region] exports index exists in ${LEGACY_DEFAULT_REGION}; using it rather than ${effective.region} (inferred).`);
522
+ return LEGACY_DEFAULT_REGION;
523
+ }
524
+ function withOtherIndexRemoval(runStore, input) {
525
+ const { effective, runIndexRegion, statePrefix, probe, createStore, logger } = input;
526
+ const other = runIndexRegion === "us-east-1" ? effective.region : LEGACY_DEFAULT_REGION;
527
+ if (!regionNeedsReconciliation(effective) || other === runIndexRegion) return runStore;
528
+ let otherStore;
529
+ const removeFromOther = async (stackName, region) => {
530
+ try {
531
+ otherStore ??= probe.rawObjectExists(`${statePrefix}/_index/${other}/exports.json`).then((exists) => exists ? createStore(other) : void 0);
532
+ await (await otherStore)?.removeStackIfPresent(stackName, region);
533
+ } catch (error) {
534
+ otherStore = void 0;
535
+ logger.warn(safeMsg`Could not remove ${stackName}'s entries from the ${other} exports index (${error.name ?? "error"}); a later Fn::ImportValue may read a stale value from it.`);
536
+ }
537
+ };
538
+ return new Proxy(runStore, { get(target, prop, receiver) {
539
+ if (prop === "removeStack") return async (stackName, region) => {
540
+ await target.removeStack(stackName, region);
541
+ await removeFromOther(stackName, region);
542
+ };
543
+ const value = Reflect.get(target, prop, receiver);
544
+ return typeof value === "function" ? value.bind(target) : value;
545
+ } });
546
+ }
547
+ async function reconcileMarkerRegionWithLegacyDefault(input) {
548
+ const { effective, probe, markerKeyFor, logger } = input;
549
+ if (!regionNeedsReconciliation(effective)) return effective.region;
550
+ const markerExists = async (region) => {
551
+ try {
552
+ return await probe.getRawObject(markerKeyFor(region)) !== null;
553
+ } catch (error) {
554
+ if (error.name !== "NoSuchBucket") throw error;
555
+ logger.debug(`[region] no state bucket yet, so no bootstrap marker for ${region} (first bootstrap).`);
556
+ return false;
557
+ }
558
+ };
559
+ if (await markerExists(effective.region)) {
560
+ logger.debug(`[region] asset storage exists in ${effective.region} (from your AWS profile); using it.`);
561
+ return effective.region;
562
+ }
563
+ if (!await markerExists("us-east-1")) return effective.region;
564
+ logger.info(`cdkd asset storage exists in ${LEGACY_DEFAULT_REGION}, but your AWS profile resolves ${effective.region}. Continuing to use ${LEGACY_DEFAULT_REGION} so the existing storage is not orphaned. Pass '--region ${effective.region}' to target your profile's region, or '--region ${LEGACY_DEFAULT_REGION}' to silence this message.`);
565
+ return LEGACY_DEFAULT_REGION;
566
+ }
567
+ function regionNeedsReconciliation(effective) {
568
+ if (effective.source === "flag" || effective.source === "env") return false;
569
+ return effective.region !== LEGACY_DEFAULT_REGION;
570
+ }
571
+ function adoptDeprecatedRegionFlag(cmd) {
572
+ const registered = cmd.options;
573
+ const inherited = registered.findIndex((option) => option.long === "--region");
574
+ if (inherited !== -1) {
575
+ registered.splice(inherited, 1);
576
+ const emitter = cmd;
577
+ emitter.removeAllListeners("option:region");
578
+ emitter.removeAllListeners("optionEnv:region");
579
+ if (cmd.getOptionValueSource("region") === "default") {
580
+ const internals = cmd;
581
+ delete internals._optionValues["region"];
582
+ delete internals._optionValueSources["region"];
583
+ }
584
+ }
585
+ cmd.addOption(deprecatedRegionOption);
586
+ cmd.hook("preAction", (_thisCommand, actionCommand) => {
587
+ const options = actionCommand.opts();
588
+ warnIfDeprecatedRegion(options);
589
+ if (options.stackRegion !== void 0) {
590
+ options.rawStackRegion = options.stackRegion;
591
+ options.stackRegion = canonicalizeRegion(options.stackRegion);
592
+ }
593
+ foldRegionOption(options);
594
+ });
595
+ return cmd;
596
+ }
597
+ function regionShown(region) {
598
+ return displayIdent(region) === region ? plainOrDescribed(region, "region") : "a region that is not a plain identifier";
599
+ }
600
+
601
+ // src/local/local-aws-wiring.ts
602
+ async function activateLocalAwsWiring(options) {
603
+ assertAwsEmulatorValue(options.awsEmulator);
604
+ try {
605
+ await activateWorkloadAwsWiring({
606
+ awsEmulator: options.awsEmulator,
607
+ caBundle: options.caBundle,
608
+ profile: options.profile,
609
+ pull: options.pull,
610
+ envVars: options.envVars
611
+ });
612
+ } catch (err) {
613
+ const cause = err instanceof Error && err.cause instanceof Error ? err.cause : void 0;
614
+ throw new CdkdError(err instanceof Error ? err.message : String(err), "LOCAL_AWS_WIRING_FAILED", cause);
615
+ }
616
+ }
617
+ async function activateLocalAwsAndRoleArn(options) {
618
+ await activateLocalAwsWiring(options);
619
+ await applyRoleArnForLocal({
620
+ roleArn: options.roleArn,
621
+ region: options.region
622
+ });
623
+ }
624
+ function assertAwsEmulatorValue(flag) {
625
+ const value = resolveAwsEmulatorOption(flag);
626
+ if (typeof value !== "string") return;
627
+ const where = `--aws-emulator (or ${awsEmulatorEnvName()})`;
628
+ let u;
629
+ try {
630
+ u = new URL(value);
631
+ } catch {
632
+ u = void 0;
633
+ }
634
+ if (u === void 0 ? /^[a-z][a-z0-9+.-]*:\/\/[^/?#]*@/i.test(value) || /[?#]/.test(value) : u.username !== "" || u.password !== "" || u.search !== "" || u.hash !== "") throw new CdkdError(`${where} must be a bare scheme://host:port URL; the value carries a user name, password, query or fragment, which is not shown here. Remove it.`, "LOCAL_AWS_WIRING_FAILED");
635
+ if (u === void 0 || u.protocol !== "https:" && u.protocol !== "http:") throw new CdkdError(`${where} takes an http(s) URL such as https://127.0.0.1:9297, and the value given is not one. The URL is OPTIONAL, so a value right after the flag is taken as the URL: put --aws-emulator after the target, or write --aws-emulator=<url>.`, "LOCAL_AWS_WIRING_FAILED");
636
+ }
637
+ async function applyLocalAwsWiring(wiring, env, extraMounts, takenContainerPaths) {
638
+ const defaults = wiring.mode === "forward" && !env["AWS_ACCESS_KEY_ID"] ? await resolveHostDefaultCredentials() : void 0;
639
+ const wiredEnv = applyWorkloadAwsWiringToEnv(env, wiring, defaults);
640
+ const emulatorOnly = workloadGetsEmulatorKeysOnly(env, wiring);
641
+ const mounts = extraMounts.filter((m) => !emulatorOnly || m.containerPath !== "/cdkd-aws/credentials");
642
+ const taken = /* @__PURE__ */ new Set([...takenContainerPaths, ...mounts.map((m) => m.containerPath)]);
643
+ for (const m of wiring.mounts) if (!taken.has(m.containerPath)) mounts.push({
644
+ ...m,
645
+ readOnly: true
646
+ });
647
+ return {
648
+ env: wiredEnv,
649
+ extraMounts: mounts
650
+ };
651
+ }
652
+ function loopbackPortsFor(wiring, env, network) {
653
+ if (network !== "host") return effectiveLoopbackPorts(env, wiring);
654
+ const mixed = wiring.mixed;
655
+ if (mixed && effectiveLoopbackPorts(env, wiring).includes(mixed.resignPort)) throw new CdkdError("A run with \"real-aws\" exceptions (AWS Emulator mixed mode) cannot use the host network: its re-signing sidecar listens on the workload's own loopback. Drop the \"real-aws\" exceptions or the host network.", "LOCAL_AWS_EMULATOR_FORWARDER_FAILED");
656
+ return [];
657
+ }
658
+ async function prepareLocalLoopbackForwarder(wiring) {
659
+ try {
660
+ await ensureForwarderImage(wiring.skipPull === true);
661
+ } catch (err) {
662
+ if (wiring.mode === "emulator" || wiring.mixed) throw new CdkdError(`--aws-emulator: the loopback forwarder image could not be pulled: ${err.message}`, "LOCAL_AWS_EMULATOR_FORWARDER_PULL_FAILED");
663
+ }
664
+ }
665
+ async function attachLocalLoopbackForwarder(containerId, ports) {
666
+ const wiring = getActiveWorkloadAwsWiring$1();
667
+ if (!wiring) return;
668
+ try {
669
+ await (ports === void 0 ? attachLoopbackForwarder(containerId, wiring) : attachLoopbackForwarder(containerId, wiring, ports));
670
+ } catch (err) {
671
+ throw new CdkdError(err instanceof Error ? err.message : String(err), "LOCAL_AWS_EMULATOR_FORWARDER_FAILED", err instanceof Error ? err : void 0);
672
+ }
673
+ }
674
+ async function profileCredentialsForWorkload(profile, resolve) {
675
+ if (!profile || localAwsEmulatorActive()) return void 0;
676
+ return resolve(profile);
677
+ }
678
+ function setContainerRegion(env, region) {
679
+ if (!region) return;
680
+ const folded = canonicalizeRegion(region);
681
+ env["AWS_REGION"] = folded;
682
+ env["AWS_DEFAULT_REGION"] = folded;
683
+ }
684
+ async function resolveContainerRegion(sources) {
685
+ const named = firstUsableRegion(sources.region, process.env["AWS_REGION"], process.env["AWS_DEFAULT_REGION"], sources.stackRegion, sources.stateRegion);
686
+ if (named) return canonicalizeRegion(named);
687
+ const fromProfile = firstUsableRegion(await resolveSdkDefaultRegion(sources.profile));
688
+ return fromProfile ? canonicalizeRegion(fromProfile) : void 0;
689
+ }
690
+ function localAwsEmulatorActive() {
691
+ return getActiveWorkloadAwsWiring$1()?.mode === "emulator";
692
+ }
693
+ function localAwsEmulatorCredentials() {
694
+ const wiring = getActiveWorkloadAwsWiring$1();
695
+ return wiring?.mode === "emulator" ? wiring.emulatorCredentials : void 0;
696
+ }
697
+ function workloadGetsEmulatorKeysOnly(env, wiring) {
698
+ if (!wiring) return false;
699
+ if (wiring.mode === "emulator") return true;
700
+ if (!wiring.mixed) return false;
701
+ return !Object.entries(env).some(([k, v]) => k !== "AWS_ENDPOINT_URL" && isRealAwsSentinel(k, v));
702
+ }
703
+ function taskRoleAssumedInRealAws(env, wiring) {
704
+ if (wiring?.mode === "emulator") return false;
705
+ if (!wiring?.mixed) return true;
706
+ return isRealAwsSentinel("AWS_ENDPOINT_URL_STS", env["AWS_ENDPOINT_URL_STS"]);
707
+ }
708
+ function mixedModeActive() {
709
+ return getActiveWorkloadAwsWiring$1()?.mixed !== void 0;
710
+ }
711
+ function realAwsException(service, workload) {
712
+ return mixedModeActive() && !isAwsServiceRoutedToEmulator(service, workload);
713
+ }
714
+ function mixedModeEmulatorOverride() {
715
+ return getAwsEndpointOverride() ?? getActiveWorkloadAwsWiring$1()?.mixed?.emulatorClientOverride;
716
+ }
717
+ function warnAwsEmulatorStateSourceHint(dropped, stateSourceGiven) {
718
+ if (dropped === 0 || stateSourceGiven) return;
719
+ const hint = takeAwsEmulatorStateSourceHint();
720
+ if (hint !== void 0) getLogger().warn(hint);
721
+ }
722
+
723
+ // src/utils/glob-match.ts
724
+ function globMatches(pattern, subject) {
725
+ const segments = pattern.split("*");
726
+ if (segments.length === 1) return pattern === subject;
727
+ const head = segments[0];
728
+ const tail = segments[segments.length - 1];
729
+ if (subject.length < head.length + tail.length) return false;
730
+ if (!subject.startsWith(head) || !subject.endsWith(tail)) return false;
731
+ const end = subject.length - tail.length;
732
+ let cursor = head.length;
733
+ for (let i = 1; i < segments.length - 1; i++) {
734
+ const segment = segments[i];
735
+ if (segment === "") continue;
736
+ const at = subject.indexOf(segment, cursor);
737
+ if (at === -1 || at + segment.length > end) return false;
738
+ cursor = at + segment.length;
739
+ }
740
+ return true;
741
+ }
742
+ function pathGlobMatches(pattern, subject) {
743
+ const p = pattern.split("/");
744
+ const s = subject.split("/");
745
+ let can = s.map(() => false).concat(true);
746
+ for (let i = p.length - 1; i >= 0; i--) {
747
+ const next = new Array(s.length + 1).fill(false);
748
+ if (p[i] === "**") for (let j = s.length; j >= 0; j--) next[j] = can[j] || j < s.length && next[j + 1];
749
+ else for (let j = 0; j < s.length; j++) next[j] = can[j + 1] && globMatches(p[i], s[j]);
750
+ can = next;
751
+ }
752
+ return can[0];
753
+ }
754
+
755
+ // src/cli/cdk-path.ts
756
+ function readCdkPath(resource) {
757
+ const meta = resource.Metadata;
758
+ if (!meta) return "";
759
+ const v = meta["aws:cdk:path"];
760
+ return typeof v === "string" ? v : "";
761
+ }
762
+ function readCdkPathOrUndefined(resource) {
763
+ const path = readCdkPath(resource);
764
+ return path === "" ? void 0 : path;
765
+ }
766
+ function buildCdkPathIndex(template) {
767
+ const index = /* @__PURE__ */ new Map();
768
+ for (const [logicalId, resource] of Object.entries(template.Resources)) {
769
+ if (resource.Type === "AWS::CDK::Metadata") continue;
770
+ const path = readCdkPath(resource);
771
+ if (path) index.set(path, logicalId);
772
+ }
773
+ return index;
774
+ }
775
+ function resolveCdkPathToLogicalIds(input, index) {
776
+ const seen = /* @__PURE__ */ new Map();
777
+ const prefix = `${input}/`;
778
+ for (const [path, logicalId] of index) if (path === input || path.startsWith(prefix)) {
779
+ if (!seen.has(logicalId)) seen.set(logicalId, path);
780
+ }
781
+ return [...seen.entries()].map(([logicalId, cdkPath]) => ({
782
+ logicalId,
783
+ cdkPath
784
+ }));
785
+ }
786
+ function stackForConstructPath(path, stacks) {
787
+ let best;
788
+ let bestRank = -1;
789
+ for (const s of stacks) {
790
+ const names = [[s.displayName, 1], [s.stackName, 0]];
791
+ for (const [name, preference] of names) {
792
+ if (typeof name !== "string" || name.length === 0) continue;
793
+ if (!path.startsWith(`${name}/`)) continue;
794
+ const rank = name.length * 2 + preference;
795
+ if (rank > bestRank) {
796
+ best = s;
797
+ bestRank = rank;
798
+ }
799
+ }
800
+ }
801
+ return best;
802
+ }
803
+ function stackForPathFormTarget(parsed, target, stacks) {
804
+ if (!parsed.isPath || parsed.pathOrId !== target) return void 0;
805
+ return stackForConstructPath(parsed.pathOrId, stacks);
806
+ }
807
+
808
+ // src/cli/stack-matcher.ts
809
+ function matchStacks(stacks, patterns, options = {}) {
810
+ if (patterns.length === 0) return [];
811
+ const selected = /* @__PURE__ */ new Set();
812
+ for (const pattern of patterns) for (const stack of stacksForPattern(stacks, pattern)) selected.add(stack);
813
+ if (options.dedupe === "identity") return stacks.filter((s) => selected.has(s));
814
+ const seen = /* @__PURE__ */ new Set();
815
+ return stacks.filter((s) => selected.has(s) && !seen.has(s.stackName) && seen.add(s.stackName));
816
+ }
817
+ function stackNameRegionCollisions(stacks, regionOf, selected = new Set(stacks)) {
818
+ const byNameRegion = /* @__PURE__ */ new Map();
819
+ for (const stack of stacks) {
820
+ const key = injectiveKey(stack.stackName, regionOf(stack) ?? "");
821
+ const group = byNameRegion.get(key);
822
+ if (group) group.push(stack);
823
+ else byNameRegion.set(key, [stack]);
824
+ }
825
+ const sameAccountPossible = (a, b) => a.account === void 0 || b.account === void 0 || a.account === b.account;
826
+ const groups = [];
827
+ for (const group of byNameRegion.values()) {
828
+ const chosen = group.filter((s) => selected.has(s));
829
+ if (chosen.length === 0) continue;
830
+ const colliding = group.filter((s) => selected.has(s) || chosen.some((c) => sameAccountPossible(c, s)));
831
+ if (colliding.length > 1) groups.push(colliding);
832
+ }
833
+ return groups;
834
+ }
835
+ function stacksForDependency(depName, dependent, pool) {
836
+ if (depName === dependent.stackName) return [];
837
+ const candidates = pool.filter((s) => s.stackName === depName);
838
+ if (candidates.length <= 1) return candidates;
839
+ const sameStage = candidates.filter((s) => s.stagePath === dependent.stagePath);
840
+ const inStage = sameStage.length > 0 ? sameStage : candidates;
841
+ if (inStage.length === 1) return inStage;
842
+ const sameRegion = inStage.filter((s) => s.region === dependent.region);
843
+ return sameRegion.length > 0 ? sameRegion : inStage;
844
+ }
845
+ function renderStackNameRegionCollision(groups, regionOf) {
846
+ const ident = (v) => displayIdent(v, { maxCodePoints: STACK_REF_MAX_CODE_POINTS });
847
+ return `Selected stacks address the same CloudFormation stack: ${groups.map((group) => {
848
+ const region = regionOf(group[0]);
849
+ const where = region === void 0 ? "and neither sets env.region, so they deploy to the same region" : `in region ${ident(region)}`;
850
+ const accounts = [...new Set(group.flatMap((s) => s.account ? [s.account] : []))];
851
+ const accountNote = accounts.length > 1 ? ` (their accounts ${accounts.map(ident).join(", ")} differ, but one run deploys every selected stack under its own account)` : "";
852
+ return `${group.map(describeStack).join(", ")} share the physical stack name ${ident(group[0].stackName)} ${where}${accountNote}`;
853
+ }).join("; ")}. Give each a distinct stackName or env.region, or select only one of them by its CDK path.` + (groups.some((g) => g.some((s) => s.region === void 0 && regionOf(s) !== void 0)) ? " A stack without env.region takes the run's region: pin that Stage's region, or set AWS_REGION to another region for this run." : "");
854
+ }
855
+ function refuseStackNameRegionCollisions(stacks, regionOf, selected) {
856
+ const groups = stackNameRegionCollisions(stacks, regionOf, selected);
857
+ if (groups.length > 0) throw new CdkdError(renderStackNameRegionCollision(groups, (s) => regionOf(s)), "STACK_NAME_REGION_COLLISION");
858
+ }
859
+ function selectTargetStack(parsed, target, stacks) {
860
+ if (parsed.stackPattern === null) return stacks.length === 1 ? {
861
+ kind: "found",
862
+ stack: stacks[0]
863
+ } : { kind: "no-prefix" };
864
+ const byPrefix = stackForPathFormTarget(parsed, target, stacks);
865
+ if (byPrefix) {
866
+ if (stackForPathFormTarget(parsed, target, [...stacks].reverse()) === byPrefix) return {
867
+ kind: "found",
868
+ stack: byPrefix
869
+ };
870
+ return {
871
+ kind: "ambiguous",
872
+ pattern: byPrefix.stackName,
873
+ matched: stacks.filter((s) => s.stackName === byPrefix.stackName)
874
+ };
875
+ }
876
+ const matched = matchStacks([...stacks], [parsed.stackPattern], { dedupe: "identity" });
877
+ if (matched.length === 1) return {
878
+ kind: "found",
879
+ stack: matched[0]
880
+ };
881
+ if (matched.length === 0) return {
882
+ kind: "not-found",
883
+ pattern: parsed.stackPattern
884
+ };
885
+ return {
886
+ kind: "ambiguous",
887
+ pattern: parsed.stackPattern,
888
+ matched
889
+ };
890
+ }
891
+ function renderAmbiguousTargetStack(pattern, matched) {
892
+ const sharedName = matched.length > 1 && matched.every((s) => s.stackName === pattern);
893
+ const example = matched.find((s) => s.displayName && s.displayName !== s.stackName)?.displayName;
894
+ const hint = example !== void 0 && displayIdent(example, { maxCodePoints: 1152 }) === example ? ` (e.g. '${example}/<construct path>')` : "";
895
+ return `Stack pattern ${renderPatternList([pattern])} matched ${matched.length} stacks: ${matched.map(describeStack).join(", ")}` + (sharedName ? ", which share that physical stack name" : "") + (example !== void 0 ? `. Name one stack by its CDK path, shown in parentheses${hint}.` : ". Use a more specific pattern.");
896
+ }
897
+ function stacksForPattern(stacks, pattern) {
898
+ const byId = stacks.filter((s) => pathGlobMatches(pattern, s.displayName ?? s.stackName));
899
+ return byId.length > 0 ? byId : stacks.filter((s) => s.stackName === pattern);
900
+ }
901
+ function describeStack(stack) {
902
+ const name = displayIdent(stack.stackName, { maxCodePoints: STACK_REF_MAX_CODE_POINTS });
903
+ if (stack.displayName && stack.displayName !== stack.stackName) return `${name} (${displayIdent(stack.displayName, { maxCodePoints: STACK_REF_MAX_CODE_POINTS })})`;
904
+ return name;
905
+ }
906
+ function renderNoStackMatch(patterns, available) {
907
+ return patterns.length > 0 ? `No stacks matching ${patterns.join(", ")} found in assembly. ` + (available.length > 0 ? `Available: ${available.map(describeStack).join(", ")}` : "The assembly has no stacks") : "No stacks found in assembly";
908
+ }
909
+ function unmatchedPatterns(stacks, patterns, isPresent = () => true) {
910
+ return [...new Set(patterns)].filter((p) => !stacksForPattern(stacks, p).some(isPresent));
911
+ }
912
+ function renderUnmatchedPatternsWarning(unmatched, where) {
913
+ const verb = unmatched.length === 1 ? "was" : "were";
914
+ return `${renderPatternList(unmatched)} matched no stack ${where} and ${verb} skipped.`;
915
+ }
916
+ function renderNotInAppWarning(names) {
917
+ const one = names.length === 1;
918
+ return `${renderPatternList(names)} ${one ? "is" : "are"} in state but ${one ? "is not a stack" : "are not stacks"} of this app and ${one ? "was" : "were"} skipped. A nested stack is destroyed with its parent; another app's stack, with that app or by name through cdkd state destroy.`;
919
+ }
920
+ function renderPatternList(patterns) {
921
+ return patterns.map((p) => displayIdent(p, {
922
+ maxCodePoints: STACK_REF_MAX_CODE_POINTS,
923
+ listMember: true
924
+ })).join(", ");
925
+ }
926
+ function stackMatchesPattern(stack, pattern) {
927
+ return pathGlobMatches(pattern, stack.displayName ?? stack.stackName) || pattern === stack.stackName;
928
+ }
929
+ function partitionTopLevel(stacks) {
930
+ const topLevel = [];
931
+ const inStages = [];
932
+ for (const stack of stacks) (stack.stagePath === void 0 ? topLevel : inStages).push(stack);
933
+ return {
934
+ topLevel,
935
+ inStages
936
+ };
937
+ }
938
+ function renderAllLeftOutStageStacks(inStages) {
939
+ const n = inStages.length;
940
+ return `--all selects top-level stacks only; ${n} stack${n === 1 ? "" : "s"} inside a CDK Stage ${n === 1 ? "was" : "were"} left out (${inStages.map(describeStack).join(", ")}). ` + renderStagePatternAdvice(inStages);
941
+ }
942
+ function renderStagePatternAdvice(inStages) {
943
+ const stagePatterns = [...new Set(inStages.map((s) => s.stagePath).filter((p) => p !== void 0 && displayIdent(p, { maxCodePoints: 1152 }) === p))].map((p) => `'${p}/*'`);
944
+ return stagePatterns.length > 0 ? `Name them with ${stagePatterns.join(", ")}, or select every stack with '**'.` : `Select them with '**'.`;
945
+ }
946
+ function stacksNoLongerSelected(stacks, patterns, selected) {
947
+ const oldRule = (p, s) => globMatches(p, p.includes("/") ? s.displayName ?? s.stackName : s.stackName);
948
+ const dropped = stacks.filter((s) => !selected.has(s.stackName) && patterns.some((p) => oldRule(p, s)));
949
+ return {
950
+ stacks: dropped,
951
+ patterns: [...new Set(patterns)].filter((p) => dropped.some((s) => oldRule(p, s)))
952
+ };
953
+ }
954
+ function renderStacksNoLongerSelected(patterns, dropped) {
955
+ const n = dropped.length;
956
+ const one = patterns.length === 1;
957
+ const inStages = dropped.filter((s) => s.stagePath !== void 0);
958
+ const direct = (s) => s.stagePath !== void 0 && (s.displayName ?? s.stackName).split("/").length === s.stagePath.split("/").length + 1;
959
+ return `${renderPatternList(patterns)} now ${one ? "matches" : "match"} the CDK path, with * inside one segment, and no longer ${one ? "selects" : "select"} ${n} stack${n === 1 ? "" : "s"} ${one ? "it" : "they"} used to (${dropped.map(describeStack).join(", ")}). ` + (inStages.length === dropped.length && inStages.every(direct) ? renderStagePatternAdvice(inStages) : inStages.length > 0 ? "Name each by the CDK path shown in parentheses, or select every stack with '**'." : "Name each by the CDK path shown in parentheses.");
960
+ }
961
+ function renderAllNoTopLevelStacks(inStages) {
962
+ return `--all selects top-level stacks only, and this app has none: every stack is inside a CDK Stage (${inStages.map(describeStack).join(", ")}). ` + renderStagePatternAdvice(inStages);
963
+ }
964
+
965
+ // src/local/docker-runner.ts
966
+ const execFileAsync = promisify(execFile);
967
+ var DockerRunnerError = class DockerRunnerError extends Error {
968
+ constructor(message) {
969
+ super(message);
970
+ this.name = "DockerRunnerError";
971
+ Object.setPrototypeOf(this, DockerRunnerError.prototype);
972
+ }
973
+ };
974
+ async function pullImage(image, skipPull) {
975
+ const logger = getLogger().child("docker");
976
+ if (skipPull) {
977
+ logger.debug(`Skipping docker pull for ${image} (--no-pull)`);
978
+ return;
979
+ }
980
+ if (getLogger().getLevel() === "debug") {
981
+ logger.info(`Pulling ${image}...`);
982
+ try {
983
+ await runDockerForeground(["pull", image]);
984
+ } catch (err) {
985
+ throw new DockerRunnerError(`docker pull ${image} failed: ${describeDockerFailure(err, ["pull", image])}`);
986
+ }
987
+ return;
988
+ }
989
+ logger.debug(`Pulling ${image} (silent — pass --verbose to stream progress)`);
990
+ try {
991
+ await runDockerStreaming(["pull", image], { streamLive: false });
992
+ } catch (err) {
993
+ const e = err;
994
+ if (e.exitCode === void 0 || e.exitCode === null) throw new DockerRunnerError(`docker pull ${image} failed: ${describeDockerFailure(err, ["pull", image])}`);
995
+ const detail = describeDockerCapturedOutput(err, ["pull", image], "(no output)");
996
+ throw new DockerRunnerError(`docker pull ${image} exited with code ${e.exitCode}: ${detail}`);
997
+ }
998
+ }
999
+ async function runDetached(opts) {
1000
+ const wiring = getActiveWorkloadAwsWiring$1();
1001
+ if (!wiring) return runDetachedContainer(opts.envAfterWiring === void 0 ? opts : {
1002
+ ...opts,
1003
+ env: {
1004
+ ...opts.env,
1005
+ ...opts.envAfterWiring
1006
+ }
1007
+ });
1008
+ const wired = await applyLocalAwsWiring(wiring, opts.env, opts.extraMounts ?? [], opts.mounts.map((m) => m.containerPath));
1009
+ if (opts.network === "host" && wiring.sidecar?.passthrough && wired.env["AWS_ENDPOINT_URL_SQS"] === wiring.sidecar.endpoint) delete wired.env["AWS_ENDPOINT_URL_SQS"];
1010
+ const wiredOpts = {
1011
+ ...opts,
1012
+ env: {
1013
+ ...wired.env,
1014
+ ...opts.envAfterWiring
1015
+ },
1016
+ extraMounts: wired.extraMounts
1017
+ };
1018
+ const ports = [.../* @__PURE__ */ new Set([...loopbackPortsFor(wiring, wired.env, opts.network), ...opts.network === "host" ? [] : opts.extraLoopbackPorts ?? []])];
1019
+ if (ports.length > 0) await prepareLocalLoopbackForwarder(wiring);
1020
+ const id = await runDetachedContainer(wiredOpts);
1021
+ await attachLocalLoopbackForwarder(id, ports);
1022
+ return id;
1023
+ }
1024
+ async function runDetachedContainer(opts) {
1025
+ const args = [
1026
+ "run",
1027
+ "-d",
1028
+ "--rm"
1029
+ ];
1030
+ if (opts.name) args.push("--name", opts.name);
1031
+ if (opts.network) args.push("--network", opts.network);
1032
+ if (opts.platform) args.push("--platform", opts.platform);
1033
+ if (opts.extraHosts) for (const entry of opts.extraHosts) args.push("--add-host", `${entry.host}:${entry.ip}`);
1034
+ const host = opts.host ?? "127.0.0.1";
1035
+ args.push("-p", `${host}:${opts.hostPort}:${opts.containerPort ?? 8080}`);
1036
+ if (opts.debugPort !== void 0) args.push("-p", `${host}:${opts.debugPort}:${opts.debugPort}`);
1037
+ for (const mount of opts.mounts) {
1038
+ const ro = mount.readOnly ? ":ro" : "";
1039
+ args.push("-v", `${mount.hostPath}:${mount.containerPath}${ro}`);
1040
+ }
1041
+ if (opts.extraMounts) for (const mount of opts.extraMounts) {
1042
+ const ro = mount.readOnly ? ":ro" : "";
1043
+ args.push("-v", `${mount.hostPath}:${mount.containerPath}${ro}`);
1044
+ }
1045
+ const sensitiveKeys = opts.sensitiveEnvKeys && opts.sensitiveEnvKeys.size > 0 ? /* @__PURE__ */ new Set([...SENSITIVE_ENV_KEYS, ...opts.sensitiveEnvKeys]) : SENSITIVE_ENV_KEYS;
1046
+ const { flags, sensitiveEnv: passthroughEnv, collisions } = partitionSensitiveEnv(opts.env, sensitiveKeys, { ...opts.name !== void 0 && { subject: `Container '${opts.name}'` } });
1047
+ args.push(...flags);
1048
+ if (opts.tmpfs) args.push("--tmpfs", `${opts.tmpfs.target}:rw,size=${opts.tmpfs.sizeMb}m`);
1049
+ if (opts.workingDir) args.push("--workdir", opts.workingDir);
1050
+ let entryPointTail = [];
1051
+ if (opts.entryPoint && opts.entryPoint.length > 0) {
1052
+ args.push("--entrypoint", opts.entryPoint[0]);
1053
+ entryPointTail = opts.entryPoint.slice(1);
1054
+ }
1055
+ args.push(...noImplicitEcrPullArgs(opts.image), opts.image, ...entryPointTail, ...opts.cmd);
1056
+ const logger = getLogger().child("docker");
1057
+ logger.debug(`${getDockerCmd()} ${redactDockerArgvValues(args).join(" ")}`);
1058
+ if (collisions.length > 0) logger.warn(`Env var(s) ${collisions.map((k) => JSON.stringify(k)).join(", ")} share a name with a variable the container client reads (docker, or the CDK_DOCKER binary) or have a malformed name (empty, or containing '=' / NUL), and were NOT passed to the container at all (a colliding name would hijack that client; a malformed name cannot form a valid environment variable). Rename the env var if the container needs it.`);
1059
+ const forwardedKeys = Object.keys(passthroughEnv);
1060
+ const refusal = finchSecretArgvRefusal(forwardedKeys.filter((k) => opts.sensitiveEnvKeys?.has(k)), `Container for image ${displayIdent(opts.image)}`);
1061
+ if (refusal !== void 0) throw new DockerRunnerError(refusal);
1062
+ warnFinchArgvExposure(forwardedKeys);
1063
+ try {
1064
+ const { stdout } = await execFileAsync(getDockerCmd(), args, {
1065
+ maxBuffer: 10485760,
1066
+ env: dockerSpawnEnvWithSensitive(passthroughEnv)
1067
+ });
1068
+ return stdout.trim();
1069
+ } catch (error) {
1070
+ throw new DockerRunnerError(`docker run failed: ${describeDockerFailure(error, args)}`);
1071
+ }
1072
+ }
1073
+ function streamLogs(containerId) {
1074
+ const stream = followContainerLogs(containerId);
1075
+ return () => stream.stop();
1076
+ }
1077
+ const RESERVATION_ROUTED_SINKS = {
1078
+ stdout: (chunk) => {
1079
+ if (isStdoutReservedForPayload()) process.stderr.write(chunk);
1080
+ else process.stdout.write(chunk);
1081
+ },
1082
+ stderr: (chunk) => {
1083
+ process.stderr.write(chunk);
1084
+ }
1085
+ };
1086
+ function followContainerLogs(containerId, sinks = RESERVATION_ROUTED_SINKS) {
1087
+ const proc = spawn(getDockerCmd(), [
1088
+ "logs",
1089
+ "-f",
1090
+ containerId
1091
+ ], { stdio: [
1092
+ "ignore",
1093
+ "pipe",
1094
+ "pipe"
1095
+ ] });
1096
+ proc.stdout?.on("data", (chunk) => sinks.stdout(chunk));
1097
+ proc.stderr?.on("data", (chunk) => sinks.stderr(chunk));
1098
+ let markClosed = () => void 0;
1099
+ const closed = new Promise((resolveClosed) => {
1100
+ markClosed = resolveClosed;
1101
+ });
1102
+ proc.on("close", () => markClosed());
1103
+ proc.on("error", () => {
1104
+ markClosed();
1105
+ });
1106
+ const stop = () => {
1107
+ if (!proc.killed) proc.kill("SIGTERM");
1108
+ };
1109
+ return {
1110
+ stop,
1111
+ drain: async (timeoutMs) => {
1112
+ let timer;
1113
+ const timedOut = new Promise((resolveTimeout) => {
1114
+ timer = setTimeout(() => resolveTimeout(false), timeoutMs);
1115
+ });
1116
+ try {
1117
+ const drained = await Promise.race([closed.then(() => true), timedOut]);
1118
+ if (!drained) {
1119
+ getLogger().child("docker").debug(safeMsg`docker logs -f ${containerId} did not end within ${timeoutMs}ms; stopping it (later log lines may be missing)`);
1120
+ stop();
1121
+ }
1122
+ return drained;
1123
+ } finally {
1124
+ clearTimeout(timer);
1125
+ }
1126
+ }
1127
+ };
1128
+ }
1129
+ async function killContainer(containerId, timeoutMs = 1e4) {
1130
+ if (!containerId) return;
1131
+ const args = ["kill", containerId];
1132
+ try {
1133
+ await execFileAsync(getDockerCmd(), args, { timeout: timeoutMs });
1134
+ } catch (error) {
1135
+ getLogger().child("docker").debug(safeMsg`docker kill ${containerId} failed: ${describeDockerFailure(error, args)}`);
1136
+ }
1137
+ }
1138
+ const CONTAINER_LOG_DRAIN_TIMEOUT_MS = 5e3;
1139
+ async function killAndDrainContainerLogs(containerId, stream, timeoutMs = CONTAINER_LOG_DRAIN_TIMEOUT_MS) {
1140
+ if (!stream) return;
1141
+ if (containerId) await killContainer(containerId);
1142
+ await stream.drain(timeoutMs);
1143
+ }
1144
+ async function flushStdio(timeoutMs = 2e3) {
1145
+ const flushed = (stream) => new Promise((resolveFlush) => {
1146
+ try {
1147
+ stream.write("", () => resolveFlush());
1148
+ } catch {
1149
+ resolveFlush();
1150
+ }
1151
+ });
1152
+ let timer;
1153
+ await Promise.race([Promise.all([flushed(process.stdout), flushed(process.stderr)]), new Promise((resolveTimeout) => {
1154
+ timer = setTimeout(resolveTimeout, timeoutMs);
1155
+ })]);
1156
+ clearTimeout(timer);
1157
+ }
1158
+ async function removeContainer(containerId) {
1159
+ if (!containerId) return;
1160
+ const logger = getLogger().child("docker");
1161
+ const args = [
1162
+ "rm",
1163
+ "-f",
1164
+ containerId
1165
+ ];
1166
+ try {
1167
+ await execFileAsync(getDockerCmd(), args);
1168
+ logger.debug(`Removed container ${containerId}`);
1169
+ } catch (error) {
1170
+ logger.debug(`docker rm -f ${containerId} failed: ${describeDockerFailure(error, args)}`);
1171
+ }
1172
+ }
1173
+ function removeContainersSync(ids) {
1174
+ if (ids.length === 0) return;
1175
+ const args = [
1176
+ "rm",
1177
+ "-f",
1178
+ ...ids
1179
+ ];
1180
+ try {
1181
+ execFileSync(getDockerCmd(), args, {
1182
+ stdio: "ignore",
1183
+ timeout: 1e4
1184
+ });
1185
+ } catch (error) {
1186
+ getLogger().child("docker").debug(`docker rm -f failed: ${describeDockerFailure(error, args)}`);
1187
+ }
1188
+ }
1189
+ async function imageInLocalCache(image) {
1190
+ const args = [
1191
+ "image",
1192
+ "inspect",
1193
+ "--format",
1194
+ "{{.Id}}",
1195
+ image
1196
+ ];
1197
+ try {
1198
+ await execFileAsync(getDockerCmd(), args);
1199
+ return true;
1200
+ } catch (error) {
1201
+ getLogger().child("docker").debug(`${image} is not in the local cache: ${describeDockerFailure(error, args)}`);
1202
+ return false;
1203
+ }
1204
+ }
1205
+ const NAMESPACE_PORT_FORWARDER_SCRIPT = "const net=require('net');const [l,t]=process.argv.slice(1).map(Number);const h=(c)=>{const u=net.connect(t,c.localAddress);c.pipe(u);u.pipe(c);u.on('error',()=>c.destroy());c.on('error',()=>u.destroy());};const s6=net.createServer(h);s6.on('error',()=>{});s6.listen(l,'::1');net.createServer(h).listen(l,'127.0.0.1',()=>console.log('ready'));";
1206
+ async function startNamespacePortForwarder(containerId, listenPort, targetPort, readyTimeoutMs = 15e3, name) {
1207
+ const args = [
1208
+ "run",
1209
+ "-d",
1210
+ "--rm",
1211
+ ...name !== void 0 ? ["--name", name] : [],
1212
+ "--network",
1213
+ `container:${containerId}`,
1214
+ "--entrypoint",
1215
+ "node",
1216
+ LOOPBACK_FORWARDER_IMAGE,
1217
+ "-e",
1218
+ NAMESPACE_PORT_FORWARDER_SCRIPT,
1219
+ String(listenPort),
1220
+ String(targetPort)
1221
+ ];
1222
+ let sidecarId;
1223
+ try {
1224
+ sidecarId = (await execFileAsync(getDockerCmd(), args)).stdout.trim();
1225
+ } catch (error) {
1226
+ throw new Error(`Port forwarder failed to start: ${describeDockerFailure(error, args)}`);
1227
+ }
1228
+ const deadline = Date.now() + readyTimeoutMs;
1229
+ const logArgs = ["logs", sidecarId];
1230
+ for (;;) {
1231
+ try {
1232
+ if ((await execFileAsync(getDockerCmd(), logArgs)).stdout.includes("ready")) return sidecarId;
1233
+ } catch (error) {
1234
+ getLogger().child("docker").debug(`docker logs ${sidecarId} failed: ${describeDockerFailure(error, logArgs)}`);
1235
+ }
1236
+ if (Date.now() > deadline) {
1237
+ await removeContainer(sidecarId);
1238
+ throw new Error(`Port forwarder ${listenPort} -> ${targetPort} did not listen within ${readyTimeoutMs}ms`);
1239
+ }
1240
+ await new Promise((resolveSleep) => setTimeout(resolveSleep, 200));
1241
+ }
1242
+ }
1243
+ async function dockerBridgeGateway() {
1244
+ const args = [
1245
+ "network",
1246
+ "inspect",
1247
+ "bridge",
1248
+ "--format",
1249
+ "{{range .IPAM.Config}}{{.Gateway}} {{end}}"
1250
+ ];
1251
+ try {
1252
+ const { stdout } = await execFileAsync(getDockerCmd(), args);
1253
+ return stdout.trim().split(/\s+/).find((a) => /^(\d{1,3}\.){3}\d{1,3}$/.test(a));
1254
+ } catch (error) {
1255
+ getLogger().child("docker").debug(`docker network inspect failed: ${describeDockerFailure(error, args)}`);
1256
+ return;
1257
+ }
1258
+ }
1259
+ async function ensureDockerAvailable() {
1260
+ const cmd = getDockerCmd();
1261
+ const args = [
1262
+ "version",
1263
+ "--format",
1264
+ "{{.Server.Version}}"
1265
+ ];
1266
+ try {
1267
+ await execFileAsync(cmd, args);
1268
+ } catch (error) {
1269
+ if (error.code === "ENOENT") throw new DockerRunnerError(`${cmd} is not installed or not on PATH. cdkd local invoke needs Docker (or a compatible CLI specified via CDK_DOCKER) — install it and retry.`);
1270
+ throw new DockerRunnerError(`${cmd} daemon is not reachable: ${describeDockerFailure(error, args)}. Start Docker Desktop / the docker daemon and retry.`);
1271
+ }
1272
+ }
1273
+ function pickFreePort() {
1274
+ return new Promise((resolvePort, rejectPort) => {
1275
+ const server = createServer();
1276
+ server.unref();
1277
+ server.on("error", rejectPort);
1278
+ server.listen(0, "127.0.0.1", () => {
1279
+ const address = server.address();
1280
+ if (!address || typeof address === "string") {
1281
+ server.close();
1282
+ rejectPort(/* @__PURE__ */ new Error("Could not allocate a host port"));
1283
+ return;
1284
+ }
1285
+ const port = address.port;
1286
+ server.close(() => resolvePort(port));
1287
+ });
1288
+ });
1289
+ }
1290
+ const SENSITIVE_ENV_KEYS = /* @__PURE__ */ new Set([
1291
+ "AWS_ACCESS_KEY_ID",
1292
+ "AWS_SECRET_ACCESS_KEY",
1293
+ "AWS_SESSION_TOKEN"
1294
+ ]);
1295
+
1296
+ // src/local/rie-client.ts
1297
+ const INVOKE_PATH = "/2015-03-31/functions/function/invocations";
1298
+ const NOT_AN_RIE_STATUS = /* @__PURE__ */ new Set([404, 405]);
1299
+ async function waitForRieReady(host, port, timeoutMs = 5e3) {
1300
+ const deadline = Date.now() + timeoutMs;
1301
+ let lastError;
1302
+ while (Date.now() < deadline) {
1303
+ try {
1304
+ if (await httpProbe(host, port, 500)) {
1305
+ await setTimeout$1(250);
1306
+ return;
1307
+ }
1308
+ } catch (err) {
1309
+ lastError = err;
1310
+ }
1311
+ await setTimeout$1(100);
1312
+ }
1313
+ const tail = lastError instanceof Error ? `: ${lastError.message}` : "";
1314
+ throw new Error(`RIE did not become ready on ${host} port ${port} within ${timeoutMs}ms${tail}. The container may have exited early — check 'docker logs' output.`);
1315
+ }
1316
+ async function httpProbe(host, port, timeoutMs) {
1317
+ const controller = new AbortController();
1318
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1319
+ try {
1320
+ await (await fetch(`http://${formatAuthority(host, port)}/`, {
1321
+ method: "POST",
1322
+ headers: { "Content-Type": "application/json" },
1323
+ body: "{}",
1324
+ signal: controller.signal
1325
+ })).text().catch(() => void 0);
1326
+ return true;
1327
+ } catch (err) {
1328
+ if (isTransientNetworkError(err)) return false;
1329
+ throw err;
1330
+ } finally {
1331
+ clearTimeout(timer);
1332
+ }
1333
+ }
1334
+ function isTransientNetworkError(err) {
1335
+ if (!(err instanceof Error)) return false;
1336
+ if (err.name === "AbortError") return true;
1337
+ if (err.name === "TypeError" && err.message === "fetch failed") return true;
1338
+ const cause = err.cause;
1339
+ if (cause?.code === "ECONNRESET") return true;
1340
+ if (cause?.code === "ECONNREFUSED") return true;
1341
+ if (cause?.code === "UND_ERR_SOCKET") return true;
1342
+ return false;
1343
+ }
1344
+ async function invokeRie(host, port, event, timeoutMs) {
1345
+ const url = `http://${formatAuthority(host, port)}${INVOKE_PATH}`;
1346
+ const body = JSON.stringify(event ?? {});
1347
+ const controller = new AbortController();
1348
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1349
+ let response;
1350
+ try {
1351
+ response = await fetchWithStartupRetry(url, body, controller.signal);
1352
+ } catch (err) {
1353
+ if (err.name === "AbortError") throw new Error(`RIE invoke at ${url} timed out after ${timeoutMs}ms. The handler may be hung; check container logs.`);
1354
+ throw err;
1355
+ } finally {
1356
+ clearTimeout(timer);
1357
+ }
1358
+ const raw = await response.text();
1359
+ if (NOT_AN_RIE_STATUS.has(response.status)) throw new Error(`The container answered the invoke at ${url} with HTTP ${response.status}, which the Lambda Runtime Interface Emulator never sends for that path: something else is listening on the container's port 8080 (the function's own server?). Check the container logs.`);
1360
+ let payload = raw;
1361
+ try {
1362
+ payload = JSON.parse(raw);
1363
+ } catch {}
1364
+ return {
1365
+ payload,
1366
+ raw
1367
+ };
1368
+ }
1369
+ async function fetchWithStartupRetry(url, body, signal) {
1370
+ const maxAttempts = 3;
1371
+ let lastError;
1372
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) try {
1373
+ return await fetch(url, {
1374
+ method: "POST",
1375
+ headers: { "Content-Type": "application/json" },
1376
+ body,
1377
+ signal
1378
+ });
1379
+ } catch (err) {
1380
+ if (err.name === "AbortError") throw err;
1381
+ lastError = err;
1382
+ if (attempt === maxAttempts) break;
1383
+ await setTimeout$1(200);
1384
+ }
1385
+ throw lastError;
1386
+ }
1387
+
1388
+ // src/local/layer-tree-copy.ts
1389
+ function copyLayerTreeLastWins(src, dest) {
1390
+ mkdirSync(dest, { recursive: true });
1391
+ copyDirLastWins(realpathSync.native(src), dest);
1392
+ }
1393
+ function copyDirLastWins(fromDir, toDir) {
1394
+ for (const entry of readdirSync(fromDir, { withFileTypes: true })) {
1395
+ const from = join(fromDir, entry.name);
1396
+ const to = join(toDir, entry.name);
1397
+ if (entry.isSymbolicLink()) {
1398
+ removeUnless(to, "symlink");
1399
+ symlinkSync(readlinkSync(from), to);
1400
+ } else if (entry.isDirectory()) {
1401
+ removeUnless(to, "directory");
1402
+ mkdirSync(to, { recursive: true });
1403
+ copyDirLastWins(from, to);
1404
+ } else {
1405
+ removeUnless(to, "file");
1406
+ cpSync(from, to, { force: true });
1407
+ }
1408
+ }
1409
+ }
1410
+ function removeUnless(to, kind) {
1411
+ let st;
1412
+ try {
1413
+ st = lstatSync(to);
1414
+ } catch {
1415
+ return;
1416
+ }
1417
+ if (kind === "directory" && st.isDirectory()) return;
1418
+ if (kind === "file" && st.isFile()) return;
1419
+ rmSync(to, {
1420
+ recursive: true,
1421
+ force: true
1422
+ });
1423
+ }
1424
+ async function layerAssetDirectory(assetPath) {
1425
+ if (!assetPath.toLowerCase().endsWith(".zip") || !lstatSync(assetPath).isFile()) return { dir: assetPath };
1426
+ const tmpDir = mkdtempSync(join(tmpdir(), "cdkd-layer-zip-"));
1427
+ try {
1428
+ const { default: AdmZip } = await import("adm-zip");
1429
+ new AdmZip(assetPath).extractAllTo(tmpDir, true, true);
1430
+ } catch (error) {
1431
+ rmSync(tmpDir, {
1432
+ recursive: true,
1433
+ force: true
1434
+ });
1435
+ throw error;
1436
+ }
1437
+ return {
1438
+ dir: tmpDir,
1439
+ tmpDir
1440
+ };
1441
+ }
1442
+
1443
+ // src/local/docker-image-builder.ts
1444
+ async function buildContainerImage$1(asset, cdkOutDir, options) {
1445
+ try {
1446
+ return await buildContainerImage(asset, cdkOutDir, options);
1447
+ } catch (e) {
1448
+ if (e instanceof LocalInvokeBuildError) throw new LocalInvokeBuildError$1(e.message);
1449
+ throw e;
1450
+ }
1451
+ }
1452
+
1453
+ // src/local/lambda-resolver/types.ts
1454
+ var LocalInvokeResolutionError = class LocalInvokeResolutionError extends Error {
1455
+ constructor(message) {
1456
+ super(message);
1457
+ this.name = "LocalInvokeResolutionError";
1458
+ Object.setPrototypeOf(this, LocalInvokeResolutionError.prototype);
1459
+ }
1460
+ };
1461
+
1462
+ // src/local/intrinsic-image.ts
1463
+ function derivePseudoParametersFromRegion$1(region, accountId) {
1464
+ return derivePseudoParametersFromRegion(canonicalizeRegion(region), accountId);
1465
+ }
1466
+
1467
+ // src/local/lambda-resolver/asset-code.ts
1468
+ function resolveAssetCodeDirectory(opts) {
1469
+ const { manifestDir, assetPath, wrapError, assetOutdir, logicalId } = opts;
1470
+ if (isAbsolute(assetPath)) {
1471
+ const absolute = resolve(assetPath);
1472
+ const escape = absoluteAssemblyPathEscape(assetOutdir, absolute);
1473
+ if (escape !== void 0) getLogger().warn(`Lambda ${displayIdent(logicalId)} has an absolute Metadata['aws:asset:path'] pointing outside the assembly: ${displayAssemblyPath(absolute)}` + (escape.escape === "symlink" ? ` (through a symbolic link to ${displayAssemblyPath(escape.realPath)})` : "") + ". cdkd will bind-mount that directory into the container read-only, where the code in this assembly can read it. This is what cdk synth --no-staging emits, and is expected for it; if you did not synthesize with that flag, treat this assembly as untrusted.");
1474
+ return absolute;
1475
+ }
1476
+ const resolved = resolveAssemblyPath(manifestDir, assetPath, { containWithin: assetOutdir });
1477
+ if (!resolved.contained && resolved.escape === "lexical" && resolved.path === resolve(assetOutdir)) return resolved.path;
1478
+ if (!resolved.contained) throw wrapError(`Lambda ${displayIdent(logicalId)} has Metadata['aws:asset:path']=${displayAssemblyPath(assetPath)} which ${renderAssemblyPathEscape(resolved, assetOutdir, "mount it")}`);
1479
+ return resolved.path;
1480
+ }
1481
+ function assetPathDirs(stack) {
1482
+ const manifestDir = stack.assetManifestPath ? dirname(stack.assetManifestPath) : stack.assetOutdir ?? process.cwd();
1483
+ return {
1484
+ manifestDir,
1485
+ assetOutdir: stack.assetOutdir ?? manifestDir
1486
+ };
1487
+ }
1488
+ function resolveAssetCodePath(stack, logicalId, resource, options = {}) {
1489
+ const assetPath = resource.Metadata?.["aws:asset:path"];
1490
+ if (typeof assetPath !== "string" || assetPath.length === 0) throw new LocalInvokeResolutionError(`Lambda ${plainOrDescribed(logicalId, "logical id")} has no Metadata['aws:asset:path']. cdkd local invoke needs this hint to find the local asset directory. Re-synthesize the app (without \`--output '<stale-dir>'\`) and retry.`);
1491
+ const { manifestDir, assetOutdir } = assetPathDirs(stack);
1492
+ const abs = resolveAssetCodeDirectory({
1493
+ manifestDir,
1494
+ assetPath,
1495
+ wrapError: (message) => new LocalInvokeResolutionError(message),
1496
+ assetOutdir,
1497
+ logicalId
1498
+ });
1499
+ if (options.acceptZipFile === true && abs.toLowerCase().endsWith(".zip") && existsSync(abs) && statSync(abs).isFile()) return abs;
1500
+ if (!existsSync(abs) || !statSync(abs).isDirectory()) throw new LocalInvokeResolutionError(`Lambda ${displayIdent(logicalId)} asset directory ${displayAssemblyPath(abs)} does not exist or is not a directory. Re-synthesize the app and retry.`);
1501
+ return abs;
1502
+ }
1503
+
1504
+ // src/local/lambda-resolver/layers.ts
1505
+ function resolveLambdaLayers(stack, logicalId, props) {
1506
+ const layers = props["Layers"];
1507
+ if (layers === void 0) return [];
1508
+ if (!Array.isArray(layers)) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has a non-array Layers property. Expected an array of LayerVersion references.`);
1509
+ if (layers.length === 0) return [];
1510
+ const resources = stack.template.Resources ?? {};
1511
+ const out = [];
1512
+ for (let i = 0; i < layers.length; i++) {
1513
+ const entry = layers[i];
1514
+ if (typeof entry === "string") {
1515
+ const parsed = classifyLayerVersionArn(entry);
1516
+ if (!parsed.ok) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has a Layers entry [${i}] cdkd cannot resolve locally: literal string '${entry}'. Expected a same-stack Ref / Fn::GetAtt to an AWS::Lambda::LayerVersion OR a literal layer-version ARN of the form arn:aws:lambda:<region>:<account>:layer:<name>:<version>.` + describeLayerArnRejection(parsed.rejection));
1517
+ out.push({
1518
+ kind: "arn",
1519
+ logicalId: parsed.value.arn,
1520
+ ...parsed.value
1521
+ });
1522
+ continue;
1523
+ }
1524
+ const layerLogicalId = pickLayerLogicalId(entry);
1525
+ if (!layerLogicalId) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has a Layers entry [${i}] cdkd cannot resolve locally: ${describeLayerEntry(entry)}. Expected a same-stack Ref / Fn::GetAtt to an AWS::Lambda::LayerVersion OR a literal layer-version ARN of the form arn:aws:lambda:<region>:<account>:layer:<name>:<version>.`);
1526
+ const layerResource = resources[layerLogicalId];
1527
+ if (!layerResource) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' Layers entry [${i}] references '${layerLogicalId}', but no resource with that logical ID exists in stack '${stack.stackName}'.`);
1528
+ if (layerResource.Type !== "AWS::Lambda::LayerVersion") throw new LocalInvokeResolutionError(`Lambda '${logicalId}' Layers entry [${i}] references '${layerLogicalId}' (${layerResource.Type}), which is not an AWS::Lambda::LayerVersion.`);
1529
+ const assetPath = resolveAssetCodePath(stack, layerLogicalId, layerResource, { acceptZipFile: true });
1530
+ out.push({
1531
+ kind: "asset",
1532
+ logicalId: layerLogicalId,
1533
+ assetPath
1534
+ });
1535
+ }
1536
+ return out;
1537
+ }
1538
+ const LAYER_ARN_PATTERN = new RegExp(`^arn:([a-z][a-z0-9-]*):lambda:([a-z]{2,}(?:-[a-z]+)+-\\d+):(\\d{12}):layer:([A-Za-z0-9_-]+):(\\d+)$`);
1539
+ function classifyLayerVersionArn(input) {
1540
+ const m = LAYER_ARN_PATTERN.exec(input);
1541
+ if (!m) return {
1542
+ ok: false,
1543
+ rejection: { kind: "shape" }
1544
+ };
1545
+ const partition = m[1];
1546
+ const region = m[2];
1547
+ const derived = derivePartitionAndUrlSuffix(region).partition;
1548
+ if (derived !== partition) return {
1549
+ ok: false,
1550
+ rejection: {
1551
+ kind: "partition",
1552
+ partition,
1553
+ region,
1554
+ derived,
1555
+ derivedFromTable: derived !== "aws"
1556
+ }
1557
+ };
1558
+ return {
1559
+ ok: true,
1560
+ value: {
1561
+ arn: input,
1562
+ region,
1563
+ accountId: m[3],
1564
+ name: m[4],
1565
+ version: m[5]
1566
+ }
1567
+ };
1568
+ }
1569
+ function describeLayerArnRejection(rejection) {
1570
+ if (rejection.kind === "shape") return "";
1571
+ const { partition, region, derived, derivedFromTable } = rejection;
1572
+ const head = ` The partition '${partition}' does not match region '${region}'`;
1573
+ return derivedFromTable ? `${head}, which is in partition '${derived}'.` : `${head}: no partition prefix matches that region, so cdkd resolves it to the commercial partition '${derived}'.`;
1574
+ }
1575
+ function pickLayerLogicalId(entry) {
1576
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return void 0;
1577
+ const obj = entry;
1578
+ if (typeof obj["Ref"] === "string") return obj["Ref"];
1579
+ if ("Fn::GetAtt" in obj) {
1580
+ const arg = obj["Fn::GetAtt"];
1581
+ if (Array.isArray(arg) && typeof arg[0] === "string") return arg[0];
1582
+ }
1583
+ }
1584
+ function describeLayerEntry(entry) {
1585
+ if (typeof entry === "string") return `literal ARN '${entry}'`;
1586
+ if (entry === null) return "null";
1587
+ if (typeof entry !== "object") return stringifyValue(entry);
1588
+ try {
1589
+ const json = JSON.stringify(entry);
1590
+ return json.length > 120 ? json.substring(0, 117) + "..." : json;
1591
+ } catch {
1592
+ return Object.prototype.toString.call(entry);
1593
+ }
1594
+ }
1595
+
1596
+ // src/local/lambda-resolver/properties.ts
1597
+ function extractLambdaProperties(stack, logicalId, resource, resources) {
1598
+ const props = resource.Properties ?? {};
1599
+ const memoryMb = typeof props["MemorySize"] === "number" ? props["MemorySize"] : 128;
1600
+ const timeoutSec = typeof props["Timeout"] === "number" ? props["Timeout"] : 3;
1601
+ const ephemeralStorageMb = extractEphemeralStorageMb(props, logicalId);
1602
+ const code = props["Code"] ?? {};
1603
+ const imageUri = extractImageUri(code["ImageUri"], logicalId, stack.stackName, resources, stack.region);
1604
+ if (imageUri !== void 0) return extractImageLambdaProperties({
1605
+ stack,
1606
+ logicalId,
1607
+ resource,
1608
+ memoryMb,
1609
+ timeoutSec,
1610
+ props,
1611
+ imageUri,
1612
+ ...ephemeralStorageMb !== void 0 && { ephemeralStorageMb }
1613
+ });
1614
+ const runtime = typeof props["Runtime"] === "string" ? props["Runtime"] : "";
1615
+ const handler = typeof props["Handler"] === "string" ? props["Handler"] : "";
1616
+ if (!runtime) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has no Runtime property and no Code.ImageUri. cdkd cannot tell if this is a ZIP or a container Lambda.`);
1617
+ if (!handler) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has no Handler property.`);
1618
+ const inlineCode = typeof code["ZipFile"] === "string" ? code["ZipFile"] : void 0;
1619
+ let codePath = null;
1620
+ if (!inlineCode) codePath = resolveAssetCodePath(stack, logicalId, resource);
1621
+ const layers = resolveLambdaLayers(stack, logicalId, props);
1622
+ return {
1623
+ kind: "zip",
1624
+ stack,
1625
+ logicalId,
1626
+ resource,
1627
+ runtime,
1628
+ handler,
1629
+ memoryMb,
1630
+ timeoutSec,
1631
+ architecture: extractArchitecture(props, logicalId),
1632
+ codePath,
1633
+ layers,
1634
+ ...ephemeralStorageMb !== void 0 && { ephemeralStorageMb },
1635
+ ...inlineCode !== void 0 && { inlineCode }
1636
+ };
1637
+ }
1638
+ function extractEphemeralStorageMb(props, logicalId) {
1639
+ const raw = props["EphemeralStorage"];
1640
+ if (raw === void 0 || raw === null) return void 0;
1641
+ if (typeof raw !== "object" || Array.isArray(raw)) return void 0;
1642
+ const size = raw["Size"];
1643
+ if (typeof size !== "number") return;
1644
+ if (!Number.isFinite(size) || size < 1) return void 0;
1645
+ if (size > 10240) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has Properties.EphemeralStorage.Size = ${size} MiB, which exceeds the AWS limit of 10240 MiB. AWS would reject the function at deploy time; cap the value to <= 10240 (10 GiB) and retry.`);
1646
+ return Math.floor(size);
1647
+ }
1648
+ function extractImageUri(value, logicalId, stackName, resources, region) {
1649
+ if (typeof value === "string" && value.length > 0) return value;
1650
+ if (value && typeof value === "object" && !Array.isArray(value)) {
1651
+ const obj = value;
1652
+ const sub = obj["Fn::Sub"];
1653
+ if (typeof sub === "string" && sub.length > 0) return sub;
1654
+ if (Array.isArray(sub) && typeof sub[0] === "string") return sub[0];
1655
+ if ("Fn::Join" in obj) {
1656
+ const pseudoParameters = derivePseudoParametersFromRegion$1(region);
1657
+ const joinResolved = tryResolveImageFnJoin(value, resources, pseudoParameters ? { pseudoParameters } : void 0);
1658
+ if (joinResolved.kind === "resolved") return joinResolved.uri;
1659
+ if (joinResolved.kind === "needs-state") throw new LocalInvokeResolutionError(`Lambda '${logicalId}' in ${stackName} references same-stack ECR repository '${joinResolved.repoLogicalId}' via Fn::Join. cdkd local invoke cannot resolve the repository URI without state — deploy the stack first (so cdkd records the repository physical id), rebuild via lambda.DockerImageCode.fromImageAsset, or pin a public image.`);
1660
+ if (joinResolved.kind === "unsupported-join") throw new LocalInvokeResolutionError(`Lambda '${logicalId}' in ${stackName} has an unsupported Fn::Join Code.ImageUri shape: ${joinResolved.reason}. cdkd local invoke recognizes the canonical CDK 2.x lambda.DockerImageCode.fromEcr Fn::Join shape (delimiter "" with nested Fn::Select/Fn::Split over an ECR Repository Arn GetAtt + Ref to the repo).`);
1661
+ throw new LocalInvokeResolutionError(`Lambda '${logicalId}' in ${stackName} has an Fn::Join Code.ImageUri that cdkd local invoke cannot resolve${pseudoParameters ? " (likely ${AWS::AccountId}, which cdkd cannot derive without --from-state or STS)" : ` (cdkd could not derive AWS pseudo parameters because stack.region was undefined)`}. Workarounds: deploy first and run with --from-state, or pin a fully-literal public image URI.`);
1662
+ }
1663
+ }
1664
+ }
1665
+ function extractArchitecture(props, logicalId) {
1666
+ const arches = props["Architectures"];
1667
+ if (Array.isArray(arches) && arches.length > 0) {
1668
+ const first = arches[0];
1669
+ if (first === "arm64") return "arm64";
1670
+ if (first === "x86_64") return "x86_64";
1671
+ throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has unsupported Architectures value '${String(first)}'. cdkd local invoke supports x86_64 and arm64.`);
1672
+ }
1673
+ return "x86_64";
1674
+ }
1675
+ function extractImageLambdaProperties(args) {
1676
+ const { stack, logicalId, resource, memoryMb, timeoutSec, ephemeralStorageMb, props, imageUri } = args;
1677
+ const rawImageConfig = props["ImageConfig"] ?? {};
1678
+ const imageConfig = {};
1679
+ if (Array.isArray(rawImageConfig["Command"])) imageConfig.command = rawImageConfig["Command"].filter((s) => typeof s === "string");
1680
+ if (Array.isArray(rawImageConfig["EntryPoint"])) imageConfig.entryPoint = rawImageConfig["EntryPoint"].filter((s) => typeof s === "string");
1681
+ if (typeof rawImageConfig["WorkingDirectory"] === "string") imageConfig.workingDirectory = rawImageConfig["WorkingDirectory"];
1682
+ return {
1683
+ kind: "image",
1684
+ stack,
1685
+ logicalId,
1686
+ resource,
1687
+ memoryMb,
1688
+ timeoutSec,
1689
+ imageUri,
1690
+ imageConfig,
1691
+ architecture: extractArchitecture(props, logicalId),
1692
+ layers: [],
1693
+ ...ephemeralStorageMb !== void 0 && { ephemeralStorageMb }
1694
+ };
1695
+ }
1696
+
1697
+ // src/local/lambda-resolver/target.ts
1698
+ function parseTarget(target) {
1699
+ if (typeof target !== "string" || target.length === 0) throw new LocalInvokeResolutionError("Empty target. Pass a CDK display path (e.g. 'MyStack/MyApi/Handler') or stack-qualified logical ID (e.g. 'MyStack:MyApiHandler1234ABCD').");
1700
+ const colonIdx = target.indexOf(":");
1701
+ const slashIdx = target.indexOf("/");
1702
+ if (colonIdx > 0 && (slashIdx === -1 || colonIdx < slashIdx)) {
1703
+ const stackPattern = target.substring(0, colonIdx);
1704
+ const pathOrId = target.substring(colonIdx + 1);
1705
+ if (pathOrId.length === 0) throw new LocalInvokeResolutionError(`Target '${target}' has no logical ID after ':'.`);
1706
+ return {
1707
+ stackPattern,
1708
+ pathOrId,
1709
+ isPath: pathOrId.includes("/")
1710
+ };
1711
+ }
1712
+ if (slashIdx > 0) return {
1713
+ stackPattern: target.substring(0, slashIdx),
1714
+ pathOrId: target,
1715
+ isPath: true
1716
+ };
1717
+ return {
1718
+ stackPattern: null,
1719
+ pathOrId: target,
1720
+ isPath: false
1721
+ };
1722
+ }
1723
+ function resolveLambdaTarget(target, stacks) {
1724
+ if (stacks.length === 0) throw new LocalInvokeResolutionError("No stacks found in the synthesized assembly.");
1725
+ const parsed = parseTarget(target);
1726
+ const stack = pickStack(parsed, stacks, target);
1727
+ const template = stack.template;
1728
+ const resources = template.Resources ?? {};
1729
+ let match;
1730
+ if (parsed.isPath) {
1731
+ const index = buildCdkPathIndex(template);
1732
+ const lambdaMatches = resolveCdkPathToLogicalIds(parsed.pathOrId, index).filter(({ logicalId }) => resources[logicalId]?.Type === "AWS::Lambda::Function");
1733
+ if (lambdaMatches.length === 0) throw notFoundError(target, stack, resources);
1734
+ if (lambdaMatches.length > 1) throw new LocalInvokeResolutionError(`Target '${target}' matches ${lambdaMatches.length} Lambda functions in ${stack.stackName}: ` + lambdaMatches.map((m) => m.logicalId).join(", ") + ". Refine the path or use the stack:LogicalId form.");
1735
+ const m = lambdaMatches[0];
1736
+ match = {
1737
+ logicalId: m.logicalId,
1738
+ resource: resources[m.logicalId]
1739
+ };
1740
+ } else {
1741
+ const resource = resources[parsed.pathOrId];
1742
+ if (!resource) throw notFoundError(target, stack, resources);
1743
+ match = {
1744
+ logicalId: parsed.pathOrId,
1745
+ resource
1746
+ };
1747
+ }
1748
+ const { logicalId, resource } = match;
1749
+ if (resource.Type !== "AWS::Lambda::Function") {
1750
+ if (resource.Type.startsWith("Custom::")) throw new LocalInvokeResolutionError(`Resource '${logicalId}' in ${stack.stackName} is a Custom Resource (${resource.Type}), not a Lambda function. Custom Resources are invoked by the deploy framework, not by users. If you want to test the underlying handler, target the ServiceToken Lambda directly.`);
1751
+ throw new LocalInvokeResolutionError(`Resource '${logicalId}' in ${stack.stackName} is ${resource.Type}, not a Lambda function. cdkd local invoke only works on AWS::Lambda::Function resources in v1.`);
1752
+ }
1753
+ return extractLambdaProperties(stack, logicalId, resource, resources);
1754
+ }
1755
+ function pickStack(parsed, stacks, target) {
1756
+ const selection = selectTargetStack(parsed, target, stacks);
1757
+ switch (selection.kind) {
1758
+ case "found": return selection.stack;
1759
+ case "no-prefix": throw new LocalInvokeResolutionError(`Multiple stacks in app, target '${parsed.pathOrId}' is missing a stack prefix. Use 'StackName:${parsed.pathOrId}' or 'StackName/...' (path form). Available stacks: ${stacks.map(describeStack).join(", ")}.`);
1760
+ case "not-found": throw new LocalInvokeResolutionError(`Stack '${selection.pattern}' not found. Available stacks: ${stacks.map(describeStack).join(", ")}.`);
1761
+ case "ambiguous": throw new LocalInvokeResolutionError(renderAmbiguousTargetStack(selection.pattern, selection.matched));
1762
+ }
1763
+ }
1764
+ function notFoundError(target, stack, resources) {
1765
+ const lambdas = [];
1766
+ for (const [logicalId, resource] of Object.entries(resources)) {
1767
+ if (resource.Type !== "AWS::Lambda::Function") continue;
1768
+ const meta = resource.Metadata;
1769
+ const cdkPath = typeof meta?.["aws:cdk:path"] === "string" ? meta["aws:cdk:path"] : "";
1770
+ lambdas.push({
1771
+ displayPath: cdkPath || logicalId,
1772
+ logicalId
1773
+ });
1774
+ }
1775
+ let msg = `target '${target}' did not match any Lambda function in ${stack.stackName}.\n\n`;
1776
+ if (lambdas.length === 0) msg += `Stack ${stack.stackName} has no Lambda functions.`;
1777
+ else {
1778
+ const width = Math.max(...lambdas.map((l) => l.displayPath.length));
1779
+ msg += `Available Lambda functions in ${stack.stackName}:\n`;
1780
+ for (const l of lambdas) msg += ` ${l.displayPath.padEnd(width)} (${l.logicalId})\n`;
1781
+ }
1782
+ return new LocalInvokeResolutionError(msg.trimEnd());
1783
+ }
1784
+
1785
+ // src/cli/commands/local-invoke/inline-code.ts
1786
+ function resolveInlineCodeFilePath(dir, modulePath, fileExtension, handler) {
1787
+ const resolved = resolveAssemblyPath(dir, `${modulePath}${fileExtension}`);
1788
+ if (!resolved.contained) throw new Error(`Handler ${displayAssemblyPath(handler)} names a module path that ${renderAssemblyPathEscape(resolved, dir, "materialize it", "A Handler's module path names a file inside the function's own code directory; one that leaves it would write the inline Code.ZipFile body to an arbitrary path on this machine. Refusing to materialize it.")}`);
1789
+ return resolved.path;
1790
+ }
1791
+ function materializeInlineCode(handler, source, fileExtension) {
1792
+ const lastDot = handler.lastIndexOf(".");
1793
+ if (lastDot <= 0) throw new Error(`Handler '${handler}' is malformed: expected '<modulePath>.<exportName>'.`);
1794
+ const modulePath = handler.substring(0, lastDot);
1795
+ const dir = mkdtempSync(path.join(tmpdir(), "cdkd-local-invoke-"));
1796
+ try {
1797
+ const filePath = resolveInlineCodeFilePath(dir, modulePath, fileExtension, handler);
1798
+ mkdirSync(path.dirname(filePath), { recursive: true });
1799
+ writeFileSync(filePath, source, "utf-8");
1800
+ } catch (e) {
1801
+ try {
1802
+ rmSync(dir, {
1803
+ recursive: true,
1804
+ force: true
1805
+ });
1806
+ } catch {}
1807
+ throw e;
1808
+ }
1809
+ return dir;
1810
+ }
1811
+
1812
+ // src/cli/commands/local-invoke/image-plan.ts
1813
+ async function resolveZipImagePlan(lambda, options) {
1814
+ let inlineTmpDir;
1815
+ let codeDir = lambda.codePath;
1816
+ if (codeDir === null) {
1817
+ inlineTmpDir = materializeInlineCode(lambda.handler, lambda.inlineCode ?? "", resolveRuntimeFileExtension(lambda.runtime));
1818
+ codeDir = inlineTmpDir;
1819
+ }
1820
+ const image = resolveRuntimeImage(lambda.runtime);
1821
+ let layerPlan;
1822
+ try {
1823
+ await pullImage(image, options.pull === false);
1824
+ layerPlan = await materializeLambdaLayersIncludingArns(lambda.layers, options, {
1825
+ logicalId: lambda.logicalId,
1826
+ cdkPath: readCdkPathOrUndefined(lambda.resource)
1827
+ });
1828
+ } catch (error) {
1829
+ if (inlineTmpDir !== void 0) rmSync(inlineTmpDir, {
1830
+ recursive: true,
1831
+ force: true
1832
+ });
1833
+ throw error;
1834
+ }
1835
+ const containerCodePath = resolveRuntimeCodeMountPath(lambda.runtime);
1836
+ const tmpfs = resolveTmpfsForLambda(lambda);
1837
+ return {
1838
+ image,
1839
+ mounts: [{
1840
+ hostPath: codeDir,
1841
+ containerPath: containerCodePath,
1842
+ readOnly: true
1843
+ }],
1844
+ extraMounts: layerPlan.mount ? [layerPlan.mount] : [],
1845
+ cmd: [lambda.handler],
1846
+ platform: architectureToPlatform(lambda.architecture),
1847
+ ...inlineTmpDir !== void 0 && { inlineTmpDir },
1848
+ ...layerPlan.tmpDir !== void 0 && { layersTmpDir: layerPlan.tmpDir },
1849
+ ...layerPlan.extraTmpDirs.length > 0 && { layerArnTmpDirs: layerPlan.extraTmpDirs },
1850
+ ...tmpfs !== void 0 && { tmpfs }
1851
+ };
1852
+ }
1853
+ async function materializeLambdaLayersIncludingArns(layers, options, workload) {
1854
+ const extraTmpDirs = [];
1855
+ const flat = [];
1856
+ try {
1857
+ for (const layer of layers) {
1858
+ if (layer.kind === "asset") {
1859
+ const asset = await layerAssetDirectory(layer.assetPath);
1860
+ if (asset.tmpDir !== void 0) extraTmpDirs.push(asset.tmpDir);
1861
+ flat.push({
1862
+ logicalId: layer.logicalId,
1863
+ assetPath: asset.dir
1864
+ });
1865
+ continue;
1866
+ }
1867
+ const dir = await materializeLayerFromArn(layer, {
1868
+ ...workload && { workload },
1869
+ ...options.layerRoleArn !== void 0 && { roleArn: explicitRoleArnOrThrow("--layer-role-arn", options.layerRoleArn) }
1870
+ });
1871
+ extraTmpDirs.push(dir);
1872
+ flat.push({
1873
+ logicalId: layer.arn,
1874
+ assetPath: dir
1875
+ });
1876
+ }
1877
+ return {
1878
+ ...materializeLambdaLayers(flat),
1879
+ extraTmpDirs
1880
+ };
1881
+ } catch (error) {
1882
+ for (const dir of extraTmpDirs) rmSync(dir, {
1883
+ recursive: true,
1884
+ force: true
1885
+ });
1886
+ throw error;
1887
+ }
1888
+ }
1889
+ function resolveTmpfsForLambda(lambda) {
1890
+ if (lambda.ephemeralStorageMb === void 0) return void 0;
1891
+ const logger = getLogger();
1892
+ if (lambda.kind === "image") logger.info(`Lambda ${lambda.logicalId}: capping /tmp at ${lambda.ephemeralStorageMb} MiB via --tmpfs (overlays any base-image /tmp content)`);
1893
+ else logger.debug(`Lambda ${lambda.logicalId}: applying EphemeralStorage cap via --tmpfs /tmp:size=${lambda.ephemeralStorageMb}m`);
1894
+ return {
1895
+ target: "/tmp",
1896
+ sizeMb: lambda.ephemeralStorageMb
1897
+ };
1898
+ }
1899
+ function materializeLambdaLayers(layers) {
1900
+ if (layers.length === 0) return {};
1901
+ if (layers.length === 1) return { mount: {
1902
+ hostPath: layers[0].assetPath,
1903
+ containerPath: "/opt",
1904
+ readOnly: true
1905
+ } };
1906
+ const tmpDir = mkdtempSync(path.join(tmpdir(), "cdkd-local-invoke-layers-"));
1907
+ try {
1908
+ for (const layer of layers) copyLayerTreeLastWins(layer.assetPath, tmpDir);
1909
+ } catch (error) {
1910
+ rmSync(tmpDir, {
1911
+ recursive: true,
1912
+ force: true
1913
+ });
1914
+ throw error;
1915
+ }
1916
+ return {
1917
+ mount: {
1918
+ hostPath: tmpDir,
1919
+ containerPath: "/opt",
1920
+ readOnly: true
1921
+ },
1922
+ tmpDir
1923
+ };
1924
+ }
1925
+ async function resolveLocalBuildPlan(lambda) {
1926
+ if (!lambda.stack.assetManifestPath) return void 0;
1927
+ const { manifestDir: cdkOutDir, assetOutdir } = assetPathDirs(lambda.stack);
1928
+ const manifest = await new AssetManifestLoader().loadStackManifest(lambda.stack, cdkOutDir);
1929
+ if (!manifest) return void 0;
1930
+ const entry = getDockerImageBySourceHash(manifest, lambda.imageUri);
1931
+ if (!entry) return void 0;
1932
+ return {
1933
+ asset: entry.asset,
1934
+ cdkOutDir,
1935
+ assetOutdir
1936
+ };
1937
+ }
1938
+
1939
+ export { renderUnmatchedPatternsWarning as $, parseContextOptions as $t, followContainerLogs as A, rawCliRegion as At, resolveRuntimeCodeMountPath as B, writeProfileCredentialsFile as Bt, waitForRieReady as C, warnAwsEmulatorStateSourceHint as Ct, dockerBridgeGateway as D, foldRegionOption as Dt, SENSITIVE_ENV_KEYS as E, exportInferredRegionForSdk as Et, removeContainer as F, resolveEffectiveRegion as Ft, partitionTopLevel as G, contextOptions as Gt, resolveRuntimeImage as H, appOptions as Ht, removeContainersSync as I, stackRegionResolver as It, renderAllNoTopLevelStacks as J, destroyOptions as Jt, refuseStackNameRegionCollisions as K, deployOptions as Kt, runDetached as L, stateWithRegion as Lt, killAndDrainContainerLogs as M, reconcileMarkerRegionWithLegacyDefault as Mt, pickFreePort as N, regionNeedsReconciliation as Nt, ensureDockerAvailable as O, legacyStateBucketFallbackRegion as Ot, pullImage as P, regionShown as Pt, renderStacksNoLongerSelected as Q, noLocalCustomResourcesOption as Qt, startNamespacePortForwarder as R, withOtherIndexRemoval as Rt, invokeRie as S, taskRoleAssumedInRealAws as St, DockerRunnerError as T, adoptDeprecatedRegionFlag as Tt, describeStack as U, applyWaitFlagEnv as Ut, resolveRuntimeFileExtension as V, annotationMessageOptions as Vt, matchStacks as W, commonOptions as Wt, renderNoStackMatch as X, guardStackRegionOptions as Xt, renderAmbiguousTargetStack as Y, exclusivelyOption as Yt, renderNotInAppWarning as Z, noCfnFallbackOption as Zt, copyLayerTreeLastWins as _, listAllLockKeys as _n, prepareLocalLoopbackForwarder as _t, materializeLayerFromArn as a, warnIfDeprecatedRegion as an, buildCdkPathIndex as at, probeHostGatewaySupport as b, resolveContainerRegion as bt, extractLambdaProperties as c, parseAssumeRoleToken as cn, stackForConstructPath as ct, resolveAssetCodeDirectory as d, resourceTimeoutOptions as dn, assertAwsEmulatorValue as dt, parseStackRegion as en, selectTargetStack as et, derivePseudoParametersFromRegion$1 as f, validateResourceTimeouts as fn, attachLocalLoopbackForwarder as ft, buildContainerImage$1 as g, describeStateKey as gn, mixedModeEmulatorOverride as gt, architectureToPlatform as h, STATE_KEY_MAX_CODE_POINTS as hn, mixedModeActive as ht, resolveInlineCodeFilePath as i, useCdkBootstrapAssetsOption as in, unmatchedPatterns as it, imageInLocalCache as j, reconcileExportIndexRegion as jt, flushStdio as k, namedCliRegion as kt, resolveLambdaLayers as l, allowUnsupportedTypesOption as ln, stackForPathFormTarget as lt, tryResolveImageFnJoin as m, STATE_FILE_SUFFIX as mn, localAwsEmulatorCredentials as mt, resolveTmpfsForLambda as n, stackOptions as nn, stacksForDependency as nt, resolveLambdaTarget as o, effectiveAssumeRoleArn as on, readCdkPathOrUndefined as ot, substituteImagePlaceholders as p, LOCK_FILE_SUFFIX as pn, getActiveWorkloadAwsWiring$1 as pt, renderAllLeftOutStageStacks as q, deprecatedRegionOption as qt, resolveZipImagePlan as r, stateOptions as rn, stacksNoLongerSelected as rt, extractEphemeralStorageMb as s, normalizeStartApiAssumeRole as sn, resolveCdkPathToLogicalIds as st, resolveLocalBuildPlan as t, skipFinalSnapshotOption as tn, stackMatchesPattern as tt, assetPathDirs as u, parseDuration as un, activateLocalAwsAndRoleArn as ut, layerAssetDirectory as v, listAllStateKeys as vn, profileCredentialsForWorkload as vt, CONTAINER_LOG_DRAIN_TIMEOUT_MS as w, workloadGetsEmulatorKeysOnly as wt, resolveHostGatewayExtraHosts as x, setContainerRegion as xt, HOST_GATEWAY_MIN_VERSION as y, parseStateKey as yn, realAwsException as yt, streamLogs as z, strandedProfileCredentialsNotice as zt };
1940
+ //# sourceMappingURL=image-plan-D4I8-FhR.js.map