@cdkd/cli 0.347.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 (58) hide show
  1. package/dist/{ambient-client-defaults-BV_xDm4m.js → ambient-client-defaults-7acjxfyN.js} +3 -3
  2. package/dist/{ambient-client-defaults-BV_xDm4m.js.map → ambient-client-defaults-7acjxfyN.js.map} +1 -1
  3. package/dist/{asg-provider-fpr4ZEfp.js → asg-provider-Dvy_jqxt.js} +5 -5
  4. package/dist/{asg-provider-fpr4ZEfp.js.map → asg-provider-Dvy_jqxt.js.map} +1 -1
  5. package/dist/aws-partition-DA0r2sr-.js +58 -0
  6. package/dist/aws-partition-DA0r2sr-.js.map +1 -0
  7. package/dist/cli.js +2 -2
  8. package/dist/custom-resource-runtime-Dwnnj7bg.js +1104 -0
  9. package/dist/custom-resource-runtime-Dwnnj7bg.js.map +1 -0
  10. package/dist/{db-instance-modify-retry-BbBT68Qa.js → db-instance-modify-retry-pFWx2ED5.js} +4 -4
  11. package/dist/{db-instance-modify-retry-BbBT68Qa.js.map → db-instance-modify-retry-pFWx2ED5.js.map} +1 -1
  12. package/dist/delete-started-Co5Gt1jH.js +169 -0
  13. package/dist/delete-started-Co5Gt1jH.js.map +1 -0
  14. package/dist/{deploy-engine-DMWjQ_C2.js → deploy-engine-DeYSJno7.js} +720 -11916
  15. package/dist/deploy-engine-DeYSJno7.js.map +1 -0
  16. package/dist/diff-calculator-CRkRB1Dg.js +4959 -0
  17. package/dist/diff-calculator-CRkRB1Dg.js.map +1 -0
  18. package/dist/ec2-termination-protection-BM1Zt3Fn.js +1277 -0
  19. package/dist/ec2-termination-protection-BM1Zt3Fn.js.map +1 -0
  20. package/dist/{ecr-uri-C2FWGsrX.js → ecr-uri-C3_6QVgR.js} +3 -3
  21. package/dist/{ecr-uri-C2FWGsrX.js.map → ecr-uri-C3_6QVgR.js.map} +1 -1
  22. package/dist/expected-bucket-owner-CGoY_YS8.js +88 -0
  23. package/dist/expected-bucket-owner-CGoY_YS8.js.map +1 -0
  24. package/dist/{iam-role-provider-70-NzlFV.js → iam-role-provider-BaN9MMWs.js} +6 -5
  25. package/dist/iam-role-provider-BaN9MMWs.js.map +1 -0
  26. package/dist/image-plan-D4I8-FhR.js +1940 -0
  27. package/dist/image-plan-D4I8-FhR.js.map +1 -0
  28. package/dist/index.d.ts +3 -1
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +5 -4
  31. package/dist/{aws-failure-text-jomzO3aT.js → logger-DmQRya0S.js} +148 -59
  32. package/dist/logger-DmQRya0S.js.map +1 -0
  33. package/dist/{neptune-provider-CX4BHKjZ.js → neptune-provider-BYgFNrtZ.js} +6 -6
  34. package/dist/{neptune-provider-CX4BHKjZ.js.map → neptune-provider-BYgFNrtZ.js.map} +1 -1
  35. package/dist/{program-BU5T28eB.js → program-BBGm88gl.js} +1031 -2003
  36. package/dist/program-BBGm88gl.js.map +1 -0
  37. package/dist/{provider-classes-cw32hLq9.js → provider-classes-CRCHL04N.js} +44 -28
  38. package/dist/provider-classes-CRCHL04N.js.map +1 -0
  39. package/dist/{rds-provider-CxSVX1d7.js → rds-provider-DKZjtd50.js} +110 -70
  40. package/dist/rds-provider-DKZjtd50.js.map +1 -0
  41. package/dist/{read-replica-DtD9IDko.js → read-replica-C5e4xpYi.js} +78 -24
  42. package/dist/read-replica-C5e4xpYi.js.map +1 -0
  43. package/dist/replacement-rules-01_01yDU.js +4937 -0
  44. package/dist/replacement-rules-01_01yDU.js.map +1 -0
  45. package/dist/resource-deadline-TfDpwRQ_.js +423 -0
  46. package/dist/resource-deadline-TfDpwRQ_.js.map +1 -0
  47. package/dist/{update-removal-CpGaCv-d.js → update-removal-D-FspP88.js} +3 -3
  48. package/dist/{update-removal-CpGaCv-d.js.map → update-removal-D-FspP88.js.map} +1 -1
  49. package/dist/{version-Bx-Ox9xU.js → version-DamSnfI_.js} +2 -2
  50. package/dist/{version-Bx-Ox9xU.js.map → version-DamSnfI_.js.map} +1 -1
  51. package/package.json +4 -2
  52. package/dist/aws-failure-text-jomzO3aT.js.map +0 -1
  53. package/dist/deploy-engine-DMWjQ_C2.js.map +0 -1
  54. package/dist/iam-role-provider-70-NzlFV.js.map +0 -1
  55. package/dist/program-BU5T28eB.js.map +0 -1
  56. package/dist/provider-classes-cw32hLq9.js.map +0 -1
  57. package/dist/rds-provider-CxSVX1d7.js.map +0 -1
  58. package/dist/read-replica-DtD9IDko.js.map +0 -1
@@ -0,0 +1,1104 @@
1
+ import { t as ambientClientDefaults } from "./ambient-client-defaults-7acjxfyN.js";
2
+ import { J as getCurrentStackName, mt as safeMsg, n as getLogger, u as describeAwsFailure } from "./logger-DmQRya0S.js";
3
+ import { q as synthesizedStacks } from "./diff-calculator-CRkRB1Dg.js";
4
+ import { A as followContainerLogs, C as waitForRieReady, D as dockerBridgeGateway, F as removeContainer, H as resolveRuntimeImage, I as removeContainersSync, L as runDetached, M as killAndDrainContainerLogs, N as pickFreePort, O as ensureDockerAvailable, P as pullImage, R as startNamespacePortForwarder, S as invokeRie, c as extractLambdaProperties, j as imageInLocalCache, pt as getActiveWorkloadAwsWiring$1, r as resolveZipImagePlan, x as resolveHostGatewayExtraHosts, xt as setContainerRegion } from "./image-plan-D4I8-FhR.js";
5
+ import { da as localCustomResourceCommand, fa as localCustomResourceRuntimeActive, la as NO_LOCAL_CUSTOM_RESOURCES_FLAG, ua as customResourceStackName, va as responsePresignClient } from "./deploy-engine-DeYSJno7.js";
6
+ import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
7
+ import { PutObjectCommand } from "@aws-sdk/client-s3";
8
+ import { GetFunctionConfigurationCommand, LambdaClient } from "@aws-sdk/client-lambda";
9
+ import { request } from "node:https";
10
+ import { createServer, request as request$1 } from "node:http";
11
+ import { readFileSync, rmSync } from "node:fs";
12
+ import { getActiveWorkloadAwsWiring } from "cdk-local/internal";
13
+ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
14
+ import { SignatureV4 } from "@smithy/signature-v4";
15
+
16
+ // src/local/custom-resource-waiter.ts
17
+ const TARGET_PREFIX = "cdkd-local-target:";
18
+ const TOP_LEVEL_KEYS = /* @__PURE__ */ new Set([
19
+ "StartAt",
20
+ "States",
21
+ "Comment"
22
+ ]);
23
+ const STATE_KEYS = /* @__PURE__ */ new Set([
24
+ "Type",
25
+ "Resource",
26
+ "End",
27
+ "Next",
28
+ "Retry",
29
+ "Catch",
30
+ "Comment"
31
+ ]);
32
+ const RETRY_KEYS = /* @__PURE__ */ new Set([
33
+ "ErrorEquals",
34
+ "IntervalSeconds",
35
+ "MaxAttempts",
36
+ "BackoffRate"
37
+ ]);
38
+ const CATCH_KEYS = /* @__PURE__ */ new Set(["ErrorEquals", "Next"]);
39
+ function getAttArnLogicalId(value) {
40
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
41
+ const entries = Object.entries(value);
42
+ if (entries.length !== 1 || entries[0][0] !== "Fn::GetAtt") return void 0;
43
+ const getAtt = entries[0][1];
44
+ if (Array.isArray(getAtt) && getAtt.length === 2 && getAtt[1] === "Arn") return typeof getAtt[0] === "string" ? getAtt[0] : void 0;
45
+ if (typeof getAtt === "string" && getAtt.endsWith(".Arn")) return getAtt.slice(0, -4);
46
+ }
47
+ function templateDefinitionWithTargets(stateMachine) {
48
+ const props = stateMachine.Properties ?? {};
49
+ if (props["DefinitionSubstitutions"] !== void 0) return void 0;
50
+ const def = props["DefinitionString"];
51
+ if (typeof def === "string") return def;
52
+ if (def === null || typeof def !== "object" || Array.isArray(def)) return void 0;
53
+ const join = def["Fn::Join"];
54
+ if (Object.keys(def).length !== 1 || !Array.isArray(join) || join.length !== 2) return void 0;
55
+ const [sep, parts] = join;
56
+ if (typeof sep !== "string" || !Array.isArray(parts)) return void 0;
57
+ const out = [];
58
+ for (const part of parts) {
59
+ if (typeof part === "string") {
60
+ out.push(part);
61
+ continue;
62
+ }
63
+ const target = getAttArnLogicalId(part);
64
+ if (target === void 0 || !/^[A-Za-z0-9]+$/.test(target)) return void 0;
65
+ out.push(`${TARGET_PREFIX}${target}`);
66
+ }
67
+ return out.join(sep);
68
+ }
69
+ function isRecord(v) {
70
+ return v !== null && typeof v === "object" && !Array.isArray(v);
71
+ }
72
+ function onlyKeys(v, allowed) {
73
+ return Object.keys(v).every((k) => allowed.has(k));
74
+ }
75
+ function isStringArray(v) {
76
+ return Array.isArray(v) && v.length > 0 && v.every((e) => typeof e === "string");
77
+ }
78
+ function optionalNumber(v) {
79
+ return v === void 0 || typeof v === "number" && Number.isFinite(v) && v >= 0;
80
+ }
81
+ function matchWaiterDefinition(templateDefinition, deployedDefinition) {
82
+ let tpl;
83
+ let dep;
84
+ try {
85
+ tpl = JSON.parse(templateDefinition);
86
+ dep = JSON.parse(deployedDefinition);
87
+ } catch {
88
+ return { reason: "its definition is not JSON" };
89
+ }
90
+ if (!isRecord(tpl) || !isRecord(dep)) return { reason: "its definition is not an object" };
91
+ if (!onlyKeys(tpl, TOP_LEVEL_KEYS) || !onlyKeys(dep, TOP_LEVEL_KEYS)) return { reason: "its definition uses a field cdkd does not run locally" };
92
+ if (typeof tpl["StartAt"] !== "string" || tpl["StartAt"] !== dep["StartAt"]) return { reason: "its StartAt does not match the deployed one" };
93
+ const tplStates = tpl["States"];
94
+ const depStates = dep["States"];
95
+ if (!isRecord(tplStates) || !isRecord(depStates)) return { reason: "it has no States" };
96
+ const names = Object.keys(tplStates);
97
+ if (names.length !== Object.keys(depStates).length) return { reason: "its states do not match the deployed ones" };
98
+ const states = /* @__PURE__ */ new Map();
99
+ for (const name of names) {
100
+ const t = tplStates[name];
101
+ const d = Object.hasOwn(depStates, name) ? depStates[name] : void 0;
102
+ if (!isRecord(t) || !isRecord(d)) return { reason: "its states do not match the deployed ones" };
103
+ if (!onlyKeys(t, STATE_KEYS) || t["Type"] !== "Task") return { reason: `state ${name} is not a plain Lambda Task` };
104
+ const resource = t["Resource"];
105
+ if (typeof resource !== "string" || !resource.startsWith(TARGET_PREFIX)) return { reason: `state ${name} does not name a function of the template` };
106
+ const arn = d["Resource"];
107
+ if (typeof arn !== "string" || !/^arn:[^:]+:lambda:[^:]*:[^:]*:function:[^:]+$/.test(arn)) return { reason: `state ${name} does not run a function` };
108
+ const { Resource: _t, ...tRest } = t;
109
+ const { Resource: _d, ...dRest } = d;
110
+ if (JSON.stringify(tRest) !== JSON.stringify(dRest)) return { reason: `state ${name} does not match the deployed one` };
111
+ const retry = t["Retry"] ?? [];
112
+ const catchers = t["Catch"] ?? [];
113
+ if (!Array.isArray(retry) || !Array.isArray(catchers)) return { reason: `state ${name} has a malformed Retry or Catch` };
114
+ for (const r of retry) if (!isRecord(r) || !onlyKeys(r, RETRY_KEYS) || !isStringArray(r["ErrorEquals"]) || !optionalNumber(r["IntervalSeconds"]) || !optionalNumber(r["MaxAttempts"]) || !optionalNumber(r["BackoffRate"])) return { reason: `state ${name} has a Retry cdkd does not run locally` };
115
+ for (const c of catchers) if (!isRecord(c) || !onlyKeys(c, CATCH_KEYS) || !isStringArray(c["ErrorEquals"]) || typeof c["Next"] !== "string") return { reason: `state ${name} has a Catch cdkd does not run locally` };
116
+ const end = t["End"] === true;
117
+ const next = t["Next"];
118
+ if (end === (typeof next === "string")) return { reason: `state ${name} must have exactly one of End and Next` };
119
+ states.set(name, {
120
+ targetLogicalId: resource.slice(18),
121
+ functionArn: arn,
122
+ end,
123
+ ...typeof next === "string" && { next },
124
+ retry,
125
+ catch: catchers
126
+ });
127
+ }
128
+ for (const [name, task] of states) if ([task.next, ...task.catch.map((c) => c.Next)].filter((n) => n !== void 0).some((n) => !states.has(n))) return { reason: `state ${name} moves to a state that does not exist` };
129
+ if (!states.has(tpl["StartAt"])) return { reason: "its StartAt names no state" };
130
+ return {
131
+ startAt: tpl["StartAt"],
132
+ states
133
+ };
134
+ }
135
+ function errorMatches(errorEquals, error) {
136
+ return errorEquals.some((e) => e === "States.ALL" || e === error || e === "States.TaskFailed" && error !== "States.Timeout");
137
+ }
138
+ const MAX_TRANSITIONS = 1e5;
139
+ async function runWaiterPlan(plan, input, runTask, sleep) {
140
+ let stateName = plan.startAt;
141
+ let stateInput = input;
142
+ let attempts = /* @__PURE__ */ new Map();
143
+ for (let transitions = 0; transitions < MAX_TRANSITIONS; transitions++) {
144
+ const task = plan.states.get(stateName);
145
+ const result = await runTask(stateName, task, stateInput);
146
+ if (result.ok) {
147
+ if (task.end) return {
148
+ status: "SUCCEEDED",
149
+ output: result.output
150
+ };
151
+ stateName = task.next;
152
+ stateInput = result.output;
153
+ attempts = /* @__PURE__ */ new Map();
154
+ continue;
155
+ }
156
+ const retrier = task.retry.find((r) => errorMatches(r.ErrorEquals, result.error));
157
+ if (retrier !== void 0) {
158
+ const done = attempts.get(retrier) ?? 0;
159
+ if (done < (retrier.MaxAttempts ?? 3)) {
160
+ attempts.set(retrier, done + 1);
161
+ const interval = retrier.IntervalSeconds ?? 1;
162
+ const backoff = retrier.BackoffRate ?? 2;
163
+ await sleep(interval * Math.pow(backoff, done) * 1e3);
164
+ continue;
165
+ }
166
+ }
167
+ const catcher = task.catch.find((c) => errorMatches(c.ErrorEquals, result.error));
168
+ if (catcher === void 0) return {
169
+ status: "FAILED",
170
+ error: result.error,
171
+ cause: result.cause
172
+ };
173
+ stateName = catcher.Next;
174
+ stateInput = {
175
+ Error: result.error,
176
+ Cause: result.cause
177
+ };
178
+ attempts = /* @__PURE__ */ new Map();
179
+ }
180
+ return {
181
+ status: "FAILED",
182
+ error: "States.Runtime",
183
+ cause: "too many state transitions"
184
+ };
185
+ }
186
+
187
+ // src/local/custom-resource-second-hop.ts
188
+ const MAX_CLOCK_SKEW_MS = 9e5;
189
+ const MAX_BODY_BYTES = 7340032;
190
+ const INVOKE_PATH = /^\/2015-03-31\/functions\/([^/]+)\/invocations$/;
191
+ const UNSIGNED_REQUEST_HEADERS = /* @__PURE__ */ new Set([
192
+ "host",
193
+ "authorization",
194
+ "x-amz-date",
195
+ "x-amz-security-token",
196
+ "x-amz-content-sha256",
197
+ "connection",
198
+ "content-length",
199
+ "transfer-encoding",
200
+ "keep-alive",
201
+ "expect"
202
+ ]);
203
+ const HOP_BY_HOP_RESPONSE_HEADERS = /* @__PURE__ */ new Set([
204
+ "connection",
205
+ "content-length",
206
+ "transfer-encoding",
207
+ "keep-alive"
208
+ ]);
209
+ function referencedLogicalId(value) {
210
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
211
+ const entries = Object.entries(value);
212
+ if (entries.length !== 1) return void 0;
213
+ const [key, arg] = entries[0];
214
+ if (key === "Ref") return typeof arg === "string" ? arg : void 0;
215
+ if (key !== "Fn::GetAtt") return void 0;
216
+ if (Array.isArray(arg) && arg.length === 2 && arg[1] === "Arn") return typeof arg[0] === "string" ? arg[0] : void 0;
217
+ if (typeof arg === "string" && arg.endsWith(".Arn")) return arg.slice(0, -4);
218
+ }
219
+ function callerReferencedLogicalId(caller, requested, type) {
220
+ const deployedEnv = caller.deployed.Environment?.Variables ?? {};
221
+ const envProp = caller.lambda.resource.Properties?.["Environment"];
222
+ const templateEnv = envProp !== null && typeof envProp === "object" ? envProp["Variables"] : void 0;
223
+ if (templateEnv === null || typeof templateEnv !== "object") return void 0;
224
+ const resources = caller.lambda.stack.template.Resources ?? {};
225
+ const unqualified = requested.endsWith(":$LATEST") ? requested.slice(0, -8) : requested;
226
+ for (const [key, value] of Object.entries(deployedEnv)) {
227
+ if (value !== unqualified) continue;
228
+ if (!Object.hasOwn(templateEnv, key)) continue;
229
+ const logicalId = referencedLogicalId(templateEnv[key]);
230
+ if (logicalId === void 0 || !Object.hasOwn(resources, logicalId)) continue;
231
+ if (resources[logicalId].Type === type) return logicalId;
232
+ }
233
+ }
234
+ function credentialScope(authorization) {
235
+ const m = /Credential=[^/,\s]+\/\d{8}\/([^/,\s]+)\/([^/,\s]+)\/aws4_request/.exec(authorization ?? "");
236
+ return m ? {
237
+ region: m[1],
238
+ service: m[2]
239
+ } : void 0;
240
+ }
241
+ function serviceError(status, type, message) {
242
+ return {
243
+ status,
244
+ headers: {
245
+ "content-type": "application/json",
246
+ "x-amzn-errortype": type
247
+ },
248
+ body: Buffer.from(JSON.stringify({
249
+ Type: "Service",
250
+ __type: type,
251
+ message
252
+ }))
253
+ };
254
+ }
255
+ async function startSecondHopEndpoint(deps) {
256
+ const registrations = /* @__PURE__ */ new Map();
257
+ const logger = getLogger();
258
+ const warned = /* @__PURE__ */ new Set();
259
+ const warnOnce = (key, message) => {
260
+ if (warned.has(key)) return;
261
+ warned.add(key);
262
+ logger.warn(message);
263
+ };
264
+ const handle = async (req, res) => {
265
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
266
+ const m = /^\/([0-9a-f]{64})(\/.*)?$/.exec(url.pathname);
267
+ const registration = m ? registrations.get(m[1]) : void 0;
268
+ if (m === null || registration === void 0) {
269
+ res.writeHead(403).end();
270
+ req.resume();
271
+ return;
272
+ }
273
+ const path = m[2] ?? "/";
274
+ const body = await readBody(req);
275
+ if (body === void 0) {
276
+ send(res, serviceError(413, "RequestTooLargeException", "Request body is too large"));
277
+ return;
278
+ }
279
+ const headers = {};
280
+ for (const [k, v] of Object.entries(req.headers)) if (typeof v === "string") headers[k.toLowerCase()] = v;
281
+ else if (Array.isArray(v)) headers[k.toLowerCase()] = v.join(",");
282
+ const scope = credentialScope(headers["authorization"]);
283
+ const query = {};
284
+ for (const key of new Set(url.searchParams.keys())) {
285
+ const all = url.searchParams.getAll(key);
286
+ query[key] = all.length === 1 ? all[0] : all;
287
+ }
288
+ const rawPath = (req.url ?? "/").split("?")[0];
289
+ if (!await verifySignature({
290
+ method: req.method ?? "GET",
291
+ path: rawPath,
292
+ query,
293
+ headers,
294
+ body
295
+ }, deps.emulatorCredentials).catch(() => false)) {
296
+ logger.debug("cr.Provider endpoint: a request not signed with the emulator key was refused");
297
+ send(res, {
298
+ status: 403,
299
+ headers: {},
300
+ body: Buffer.alloc(0)
301
+ });
302
+ return;
303
+ }
304
+ const forwardRequest = {
305
+ service: scope?.service ?? "lambda",
306
+ region: scope?.region ?? regionOf(registration.caller),
307
+ method: req.method ?? "GET",
308
+ path,
309
+ query,
310
+ headers,
311
+ body
312
+ };
313
+ logger.debug(safeMsg`cr.Provider endpoint: ${forwardRequest.service} ${forwardRequest.method} ${path} ${headers["x-amz-target"] ?? ""}`);
314
+ const local = await answerLocally(registration.caller, forwardRequest).catch((err) => {
315
+ logger.warn(safeMsg`A cr.Provider call could not run locally: ${err instanceof Error ? err.message : String(err)}`);
316
+ return serviceError(500, "ServiceException", "cdkd could not run the function in the Lambda runtime image locally; see the cdkd output");
317
+ });
318
+ if (local !== void 0) {
319
+ send(res, local);
320
+ return;
321
+ }
322
+ send(res, await deps.forward(forwardRequest).catch((err) => {
323
+ logger.debug(safeMsg`Forwarding to AWS Emulator failed: ${String(err)}`);
324
+ return serviceError(502, "ServiceException", "cdkd could not reach AWS Emulator");
325
+ }));
326
+ };
327
+ const answerLocally = async (caller, req) => {
328
+ if (req.service === "lambda" && req.method === "POST") {
329
+ const invoke = INVOKE_PATH.exec(req.path);
330
+ if (invoke) return invokeLocally(caller, decodeURIComponent(invoke[1]), req);
331
+ }
332
+ if (req.service === "states" && req.method === "POST" && req.headers["x-amz-target"] === "AWSStepFunctions.StartExecution") return startExecutionLocally(caller, req);
333
+ };
334
+ const resolveTarget = async (caller, functionName) => {
335
+ const logicalId = callerReferencedLogicalId(caller, functionName, "AWS::Lambda::Function");
336
+ if (logicalId === void 0) return {
337
+ reason: "the caller does not reference it",
338
+ referenced: false
339
+ };
340
+ const deployed = await deps.getFunctionConfiguration(functionName);
341
+ if (deployed === void 0) return {
342
+ reason: "AWS Emulator does not describe it",
343
+ referenced: true
344
+ };
345
+ const choice = deps.chooseFunction(caller, logicalId, deployed);
346
+ if ("reason" in choice) return {
347
+ reason: choice.reason,
348
+ referenced: true
349
+ };
350
+ if (!await deps.imageAvailable(choice.lambda)) return {
351
+ reason: "its Lambda runtime image is not available",
352
+ referenced: true
353
+ };
354
+ return {
355
+ lambda: choice.lambda,
356
+ deployed,
357
+ forwardPort: caller.forwardPort
358
+ };
359
+ };
360
+ const invokeLocally = async (caller, functionName, req) => {
361
+ const invocationType = req.headers["x-amz-invocation-type"] ?? "RequestResponse";
362
+ const qualifier = req.query["Qualifier"];
363
+ if (invocationType !== "RequestResponse") return void 0;
364
+ if (qualifier !== void 0 && qualifier !== "$LATEST") return void 0;
365
+ let event;
366
+ try {
367
+ event = req.body.length === 0 ? {} : JSON.parse(req.body.toString("utf8"));
368
+ } catch {
369
+ return;
370
+ }
371
+ const target = await resolveTarget(caller, functionName);
372
+ if ("reason" in target) {
373
+ if (target.referenced) warnOnce(`invoke:${functionName}`, safeMsg`Function ${functionName} runs in AWS Emulator's own Lambda runtime, not locally: ${target.reason}.`);
374
+ else logger.debug(safeMsg`Invoke of ${functionName} goes to AWS Emulator: ${target.reason}`);
375
+ return;
376
+ }
377
+ logger.info(safeMsg`Running function ${target.lambda.logicalId} (${target.lambda.runtime}), invoked by ${caller.lambda.logicalId}, in the Lambda runtime image locally`);
378
+ let result;
379
+ try {
380
+ result = await deps.runLocally(target, event);
381
+ } catch (err) {
382
+ const message = err instanceof Error ? err.message : String(err);
383
+ logger.warn(safeMsg`Function ${target.lambda.logicalId} could not run in the Lambda runtime image locally: ${message}`);
384
+ result = {
385
+ StatusCode: 200,
386
+ FunctionError: "Unhandled",
387
+ Payload: Buffer.from(JSON.stringify({
388
+ errorType: "LocalRuntimeError",
389
+ errorMessage: `cdkd could not run the function in the Lambda runtime image locally: ${message}`
390
+ }))
391
+ };
392
+ }
393
+ const headers = {
394
+ "content-type": "application/json",
395
+ "x-amz-executed-version": "$LATEST"
396
+ };
397
+ if (result.FunctionError !== void 0) headers["x-amz-function-error"] = result.FunctionError;
398
+ if (req.headers["x-amz-log-type"] === "Tail" && result.LogResult !== void 0) headers["x-amz-log-result"] = result.LogResult;
399
+ return {
400
+ status: 200,
401
+ headers,
402
+ body: Buffer.from(result.Payload ?? /* @__PURE__ */ new Uint8Array())
403
+ };
404
+ };
405
+ const startExecutionLocally = async (caller, req) => {
406
+ let body;
407
+ try {
408
+ body = JSON.parse(req.body.toString("utf8"));
409
+ } catch {
410
+ return;
411
+ }
412
+ const stateMachineArn = body["stateMachineArn"];
413
+ if (typeof stateMachineArn !== "string") return void 0;
414
+ const declined = (reason) => {
415
+ warnOnce(`sfn:${stateMachineArn}`, safeMsg`The state machine ${stateMachineArn} runs on AWS Emulator, not locally: ${reason}.`);
416
+ };
417
+ const smLogicalId = callerReferencedLogicalId(caller, stateMachineArn, "AWS::StepFunctions::StateMachine");
418
+ if (smLogicalId === void 0) {
419
+ logger.debug(safeMsg`StartExecution of ${stateMachineArn} goes to AWS Emulator: the caller does not reference it`);
420
+ return;
421
+ }
422
+ const sm = caller.lambda.stack.template.Resources[smLogicalId];
423
+ const templateDefinition = templateDefinitionWithTargets(sm);
424
+ if (templateDefinition === void 0) return declined("its definition is not a plain JSON text");
425
+ const described = await deps.forward({
426
+ service: "states",
427
+ region: req.region,
428
+ method: "POST",
429
+ path: "/",
430
+ query: {},
431
+ headers: {
432
+ "content-type": "application/x-amz-json-1.0",
433
+ "x-amz-target": "AWSStepFunctions.DescribeStateMachine"
434
+ },
435
+ body: Buffer.from(JSON.stringify({ stateMachineArn }))
436
+ });
437
+ let deployedDefinition;
438
+ try {
439
+ deployedDefinition = JSON.parse(described.body.toString("utf8"))["definition"];
440
+ } catch {
441
+ deployedDefinition = void 0;
442
+ }
443
+ if (described.status !== 200 || typeof deployedDefinition !== "string") return declined("AWS Emulator does not describe it");
444
+ const plan = matchWaiterDefinition(templateDefinition, deployedDefinition);
445
+ if ("reason" in plan) return declined(plan.reason);
446
+ const targets = /* @__PURE__ */ new Map();
447
+ for (const [name, task] of plan.states) {
448
+ const logicalId = task.targetLogicalId;
449
+ const resources = caller.lambda.stack.template.Resources ?? {};
450
+ if (!Object.hasOwn(resources, logicalId) || resources[logicalId].Type !== "AWS::Lambda::Function") return declined(`state ${name} does not run a function of the stack`);
451
+ const deployed = await deps.getFunctionConfiguration(task.functionArn);
452
+ if (deployed === void 0) return declined(`AWS Emulator does not describe state ${name}'s function`);
453
+ const choice = deps.chooseFunction(caller, logicalId, deployed);
454
+ if ("reason" in choice) return declined(`state ${name}: ${choice.reason}`);
455
+ if (!await deps.imageAvailable(choice.lambda)) return declined(`state ${name}'s Lambda runtime image is not available`);
456
+ targets.set(name, {
457
+ lambda: choice.lambda,
458
+ deployed,
459
+ forwardPort: caller.forwardPort
460
+ });
461
+ }
462
+ let input = {};
463
+ if (typeof body["input"] === "string") try {
464
+ input = JSON.parse(body["input"]);
465
+ } catch {
466
+ return;
467
+ }
468
+ const execName = typeof body["name"] === "string" ? body["name"] : randomUUID();
469
+ const executionArn = `${stateMachineArn.replace(":stateMachine:", ":execution:")}:${execName}`;
470
+ logger.info(safeMsg`Running state machine ${smLogicalId} (the cr.Provider waiter) locally`);
471
+ runExecution(smLogicalId, plan, targets, input);
472
+ return {
473
+ status: 200,
474
+ headers: { "content-type": "application/x-amz-json-1.0" },
475
+ body: Buffer.from(JSON.stringify({
476
+ executionArn,
477
+ startDate: Date.now() / 1e3
478
+ }))
479
+ };
480
+ };
481
+ const runExecution = async (smLogicalId, plan, targets, input) => {
482
+ const runTask = async (stateName, _task, taskInput) => {
483
+ const target = targets.get(stateName);
484
+ let result;
485
+ try {
486
+ result = await deps.runLocally(target, taskInput);
487
+ } catch (err) {
488
+ return {
489
+ ok: false,
490
+ error: "Lambda.ServiceException",
491
+ cause: err instanceof Error ? err.message : String(err)
492
+ };
493
+ }
494
+ const raw = Buffer.from(result.Payload ?? /* @__PURE__ */ new Uint8Array()).toString("utf8");
495
+ if (result.FunctionError !== void 0) {
496
+ let errorType = "Lambda.Unknown";
497
+ try {
498
+ const parsed = JSON.parse(raw);
499
+ if (typeof parsed["errorType"] === "string") errorType = parsed["errorType"];
500
+ } catch {}
501
+ return {
502
+ ok: false,
503
+ error: errorType,
504
+ cause: raw
505
+ };
506
+ }
507
+ try {
508
+ return {
509
+ ok: true,
510
+ output: raw === "" ? null : JSON.parse(raw)
511
+ };
512
+ } catch {
513
+ return {
514
+ ok: true,
515
+ output: raw
516
+ };
517
+ }
518
+ };
519
+ try {
520
+ const outcome = await runWaiterPlan(plan, input, runTask, (ms) => deps.sleep(ms));
521
+ if (outcome.status === "FAILED") logger.warn(safeMsg`The cr.Provider waiter ${smLogicalId} failed locally: ${outcome.error}: ${outcome.cause}`);
522
+ } catch (err) {
523
+ logger.warn(safeMsg`The cr.Provider waiter ${smLogicalId} stopped: ${err instanceof Error ? err.message : String(err)}`);
524
+ }
525
+ };
526
+ const onRequest = (req, res) => {
527
+ handle(req, res).catch((err) => {
528
+ logger.debug(safeMsg`cr.Provider endpoint error: ${String(err)}`);
529
+ if (!res.headersSent) res.writeHead(500);
530
+ res.end();
531
+ });
532
+ };
533
+ const server = createServer(onRequest);
534
+ server.unref();
535
+ await listen(server, 0, "127.0.0.1");
536
+ const port = server.address().port;
537
+ let gatewayServer;
538
+ const gateway = deps.containerGateway === void 0 ? void 0 : await deps.containerGateway();
539
+ if (gateway !== void 0) {
540
+ const s = createServer(onRequest);
541
+ s.unref();
542
+ try {
543
+ await listen(s, port, gateway);
544
+ gatewayServer = s;
545
+ } catch (err) {
546
+ logger.debug(safeMsg`The cr.Provider endpoint cannot listen on ${gateway}:${String(port)}: ${String(err)}`);
547
+ server.close();
548
+ throw err;
549
+ }
550
+ }
551
+ return {
552
+ register(caller) {
553
+ const token = randomBytes(32).toString("hex");
554
+ registrations.set(token, { caller });
555
+ return {
556
+ url: `http://127.0.0.1:${port}/${token}`,
557
+ port,
558
+ release: () => {
559
+ registrations.delete(token);
560
+ }
561
+ };
562
+ },
563
+ close: async () => {
564
+ await Promise.all([server, gatewayServer].filter((s) => s !== void 0).map((s) => new Promise((resolveClose) => {
565
+ s.close(() => resolveClose());
566
+ s.closeAllConnections();
567
+ })));
568
+ }
569
+ };
570
+ }
571
+ function listen(server, port, host) {
572
+ return new Promise((resolveListen, rejectListen) => {
573
+ server.once("error", rejectListen);
574
+ server.listen(port, host, () => {
575
+ server.off("error", rejectListen);
576
+ resolveListen();
577
+ });
578
+ });
579
+ }
580
+ async function verifySignature(req, credentials) {
581
+ const auth = req.headers["authorization"] ?? "";
582
+ const m = /^AWS4-HMAC-SHA256 Credential=([^/,\s]+)\/(\d{8})\/([^/,\s]+)\/([^/,\s]+)\/aws4_request,\s*SignedHeaders=([a-z0-9;_.-]+),\s*Signature=([0-9a-f]{64})$/.exec(auth);
583
+ if (m === null || m[1] !== credentials.accessKeyId) return false;
584
+ const [, , , region, service, signedHeaderList, signature] = m;
585
+ const amzDate = req.headers["x-amz-date"];
586
+ if (amzDate === void 0 || !/^\d{8}T\d{6}Z$/.test(amzDate)) return false;
587
+ const signingDate = /* @__PURE__ */ new Date(`${amzDate.slice(0, 4)}-${amzDate.slice(4, 6)}-${amzDate.slice(6, 8)}T${amzDate.slice(9, 11)}:${amzDate.slice(11, 13)}:${amzDate.slice(13, 15)}Z`);
588
+ if (Math.abs(Date.now() - signingDate.getTime()) > MAX_CLOCK_SKEW_MS) return false;
589
+ const signedHeaders = signedHeaderList.split(";");
590
+ if (!signedHeaders.includes("host")) return false;
591
+ const payloadHash = createHash("sha256").update(req.body).digest("hex");
592
+ const claimedHash = req.headers["x-amz-content-sha256"];
593
+ if (claimedHash !== void 0 && claimedHash !== payloadHash) return false;
594
+ const headers = {};
595
+ for (const name of signedHeaders) {
596
+ const value = req.headers[name];
597
+ if (value === void 0) return false;
598
+ headers[name] = value;
599
+ }
600
+ const resigned = await new SignatureV4({
601
+ credentials: {
602
+ accessKeyId: credentials.accessKeyId,
603
+ secretAccessKey: credentials.secretAccessKey,
604
+ ...credentials.sessionToken !== void 0 && { sessionToken: credentials.sessionToken }
605
+ },
606
+ region,
607
+ service,
608
+ sha256: NodeSha256,
609
+ applyChecksum: false
610
+ }).sign({
611
+ method: req.method,
612
+ protocol: "http:",
613
+ hostname: "127.0.0.1",
614
+ path: req.path,
615
+ query: req.query,
616
+ headers,
617
+ body: req.body
618
+ }, {
619
+ signingDate,
620
+ signableHeaders: new Set(signedHeaders)
621
+ });
622
+ const expected = /Signature=([0-9a-f]{64})/.exec(resigned.headers["authorization"] ?? "")?.[1];
623
+ if (expected === void 0) return false;
624
+ return timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
625
+ }
626
+ function regionOf(caller) {
627
+ const parts = (caller.deployed.FunctionArn ?? "").split(":");
628
+ return parts.length >= 7 && parts[3] ? parts[3] : caller.lambda.stack.region ?? "us-east-1";
629
+ }
630
+ function readBody(req) {
631
+ return new Promise((resolveBody, rejectBody) => {
632
+ const chunks = [];
633
+ let size = 0;
634
+ let tooLarge = false;
635
+ req.on("data", (chunk) => {
636
+ size += chunk.length;
637
+ if (size > MAX_BODY_BYTES) tooLarge = true;
638
+ else chunks.push(chunk);
639
+ });
640
+ req.on("end", () => resolveBody(tooLarge ? void 0 : Buffer.concat(chunks)));
641
+ req.on("error", rejectBody);
642
+ });
643
+ }
644
+ function send(res, answer) {
645
+ res.writeHead(answer.status, {
646
+ ...answer.headers,
647
+ "content-length": String(answer.body.length)
648
+ });
649
+ res.end(answer.body);
650
+ }
651
+ var NodeSha256 = class {
652
+ hash;
653
+ secret;
654
+ constructor(secret) {
655
+ this.secret = secret;
656
+ this.hash = this.fresh();
657
+ }
658
+ fresh() {
659
+ return this.secret === void 0 ? createHash("sha256") : createHmac("sha256", toBuffer(this.secret));
660
+ }
661
+ update(data) {
662
+ this.hash.update(toBuffer(data));
663
+ }
664
+ digest() {
665
+ return Promise.resolve(new Uint8Array(this.hash.digest()));
666
+ }
667
+ reset() {
668
+ this.hash = this.fresh();
669
+ }
670
+ };
671
+ function toBuffer(data) {
672
+ if (typeof data === "string") return Buffer.from(data, "utf8");
673
+ if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
674
+ return Buffer.from(data);
675
+ }
676
+ let caCache;
677
+ async function forwardToEmulator(req) {
678
+ const wiring = getActiveWorkloadAwsWiring();
679
+ const endpoint = wiring?.emulatorEndpoint;
680
+ const credentials = wiring?.emulatorCredentials;
681
+ if (wiring?.mode !== "emulator" || endpoint === void 0 || credentials === void 0) throw new Error("no AWS Emulator wiring is active");
682
+ const target = new URL(endpoint.url);
683
+ const headers = {};
684
+ for (const [k, v] of Object.entries(req.headers)) if (!UNSIGNED_REQUEST_HEADERS.has(k.toLowerCase())) headers[k.toLowerCase()] = v;
685
+ headers["host"] = target.host;
686
+ const signed = await new SignatureV4({
687
+ credentials: {
688
+ accessKeyId: credentials.accessKeyId,
689
+ secretAccessKey: credentials.secretAccessKey,
690
+ ...credentials.sessionToken !== void 0 && { sessionToken: credentials.sessionToken }
691
+ },
692
+ region: req.region,
693
+ service: req.service,
694
+ sha256: NodeSha256
695
+ }).sign({
696
+ method: req.method,
697
+ protocol: target.protocol,
698
+ hostname: target.hostname,
699
+ ...target.port !== "" && { port: Number(target.port) },
700
+ path: req.path,
701
+ query: req.query,
702
+ headers,
703
+ body: req.body
704
+ });
705
+ let ca;
706
+ if (wiring.caHostPath !== void 0) {
707
+ if (caCache?.path !== wiring.caHostPath) caCache = {
708
+ path: wiring.caHostPath,
709
+ pem: readFileSync(wiring.caHostPath, "utf8")
710
+ };
711
+ ca = caCache.pem;
712
+ }
713
+ const enc = (s) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
714
+ const qs = Object.entries(req.query).flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map((value) => `${enc(k)}=${enc(value)}`)).join("&");
715
+ const send = target.protocol === "https:" ? request : request$1;
716
+ return new Promise((resolveResponse, rejectResponse) => {
717
+ const r = send({
718
+ protocol: target.protocol,
719
+ hostname: target.hostname,
720
+ ...target.port !== "" && { port: Number(target.port) },
721
+ method: req.method,
722
+ path: `${req.path}${qs === "" ? "" : `?${qs}`}`,
723
+ headers: {
724
+ ...signed.headers,
725
+ "content-length": String(req.body.length)
726
+ },
727
+ ...ca !== void 0 && { ca }
728
+ }, (res) => {
729
+ const chunks = [];
730
+ res.on("data", (c) => chunks.push(c));
731
+ res.on("end", () => {
732
+ const out = {};
733
+ for (const [k, v] of Object.entries(res.headers)) {
734
+ if (HOP_BY_HOP_RESPONSE_HEADERS.has(k) || v === void 0) continue;
735
+ out[k] = Array.isArray(v) ? v.join(", ") : v;
736
+ }
737
+ resolveResponse({
738
+ status: res.statusCode ?? 502,
739
+ headers: out,
740
+ body: Buffer.concat(chunks)
741
+ });
742
+ });
743
+ res.on("error", rejectResponse);
744
+ });
745
+ r.on("error", rejectResponse);
746
+ r.end(req.body);
747
+ });
748
+ }
749
+
750
+ // src/local/custom-resource-runtime.ts
751
+ const RESPONSE_URL_EXPIRES_IN_SECONDS = 7200;
752
+ const CONTAINER_HOST = "127.0.0.1";
753
+ let dockerAvailable;
754
+ const runtimeImages = /* @__PURE__ */ new Map();
755
+ const warnedOnce = /* @__PURE__ */ new Set();
756
+ const exitCleanups = /* @__PURE__ */ new Set();
757
+ let exitHookInstalled = false;
758
+ let secondHop;
759
+ let secondHopDisabled = false;
760
+ function warnOnce(key, message) {
761
+ if (warnedOnce.has(key)) return;
762
+ warnedOnce.add(key);
763
+ getLogger().warn(message);
764
+ }
765
+ function serviceTokenTargetLogicalId(serviceToken) {
766
+ if (serviceToken === null || typeof serviceToken !== "object") return void 0;
767
+ const getAtt = serviceToken["Fn::GetAtt"];
768
+ if (Array.isArray(getAtt) && getAtt.length === 2 && getAtt[1] === "Arn") return typeof getAtt[0] === "string" ? getAtt[0] : void 0;
769
+ if (typeof getAtt === "string" && getAtt.endsWith(".Arn")) return getAtt.slice(0, -4);
770
+ }
771
+ function findServiceTokenFunctions(stacks, customResourceLogicalId) {
772
+ const found = [];
773
+ for (const stack of stacks) {
774
+ const resources = stack.template.Resources ?? {};
775
+ const custom = Object.hasOwn(resources, customResourceLogicalId) ? resources[customResourceLogicalId] : void 0;
776
+ if (custom === void 0) continue;
777
+ if (!custom.Type.startsWith("Custom::") && custom.Type !== "AWS::CloudFormation::CustomResource") continue;
778
+ const target = serviceTokenTargetLogicalId(custom.Properties?.["ServiceToken"]);
779
+ if (target === void 0 || !Object.hasOwn(resources, target)) continue;
780
+ const resource = resources[target];
781
+ if (resource.Type !== "AWS::Lambda::Function") continue;
782
+ found.push({
783
+ stack,
784
+ logicalId: target,
785
+ resource
786
+ });
787
+ }
788
+ return found;
789
+ }
790
+ function codeIdentity(lambda) {
791
+ return JSON.stringify([
792
+ lambda.codePath,
793
+ lambda.inlineCode ?? null,
794
+ lambda.handler,
795
+ lambda.runtime,
796
+ lambda.architecture,
797
+ lambda.layers.map((l) => l.kind === "asset" ? l.assetPath : l.arn)
798
+ ]);
799
+ }
800
+ function chooseServiceTokenFunction(candidates, deployed, currentStackName) {
801
+ const resolved = [];
802
+ for (const c of candidates) {
803
+ let lambda;
804
+ try {
805
+ lambda = extractLambdaProperties(c.stack, c.logicalId, c.resource, c.stack.template.Resources ?? {});
806
+ } catch (err) {
807
+ getLogger().debug(safeMsg`${c.stack.stackName}/${c.logicalId} cannot run locally: ${err instanceof Error ? err.message : String(err)}`);
808
+ continue;
809
+ }
810
+ if (lambda.kind !== "zip") continue;
811
+ if (lambda.handler !== deployed.Handler || lambda.runtime !== deployed.Runtime) {
812
+ getLogger().debug(safeMsg`${c.stack.stackName}/${c.logicalId} is ${lambda.handler} (${lambda.runtime}) in the assembly, the deployed function ${String(deployed.Handler)} (${String(deployed.Runtime)})`);
813
+ continue;
814
+ }
815
+ resolved.push(lambda);
816
+ }
817
+ if (resolved.length === 0) return { reason: "its function was not found in the local cloud assembly" };
818
+ const pool = currentStackName === void 0 ? resolved : resolved.filter((l) => l.stack.stackName === currentStackName);
819
+ if (pool.length === 0) return { reason: "its function was not found in the stack being deployed" };
820
+ if (new Set(pool.map(codeIdentity)).size > 1) return { reason: "several functions in the local cloud assembly match it" };
821
+ return { lambda: pool[0] };
822
+ }
823
+ function runtimeImageAvailable(image) {
824
+ let ready = runtimeImages.get(image);
825
+ if (ready === void 0) {
826
+ ready = (async () => {
827
+ if (await imageInLocalCache(image)) return true;
828
+ try {
829
+ await pullImage(image, false);
830
+ return true;
831
+ } catch (err) {
832
+ getLogger().debug(safeMsg`Pulling ${image} failed: ${describeAwsFailure(err).detail}`);
833
+ return false;
834
+ }
835
+ })();
836
+ runtimeImages.set(image, ready);
837
+ }
838
+ return ready;
839
+ }
840
+ async function dockerIsAvailable() {
841
+ dockerAvailable ??= ensureDockerAvailable().then(() => true, (err) => {
842
+ getLogger().debug(safeMsg`Docker probe failed: ${describeAwsFailure(err).detail}`);
843
+ return false;
844
+ });
845
+ return dockerAvailable;
846
+ }
847
+ function noAssemblyWarning(command) {
848
+ const head = "This command did not synthesize the CDK app, so custom resource functions run in AWS Emulator's own Lambda runtime, which can fail.";
849
+ if (command === "destroy" || command === "state destroy") return `${head} Run \`cdkd destroy --aws-emulator\` from the app's directory to run them locally.`;
850
+ return `${head} Pass ${NO_LOCAL_CUSTOM_RESOURCES_FLAG} to silence this.`;
851
+ }
852
+ function regionOfFunctionArn(arn) {
853
+ const parts = arn.split(":");
854
+ return parts.length >= 7 && parts[2] === "lambda" && parts[3] ? parts[3] : void 0;
855
+ }
856
+ async function invokeCustomResourceFunctionLocally(clients, serviceToken, request) {
857
+ if (!localCustomResourceRuntimeActive()) return void 0;
858
+ const logger = getLogger();
859
+ const customResourceLogicalId = typeof request["LogicalResourceId"] === "string" ? request["LogicalResourceId"] : "";
860
+ const fallback = `it runs in AWS Emulator's own Lambda runtime instead`;
861
+ if (!await dockerIsAvailable()) {
862
+ warnOnce("docker", `Docker is not available, so custom resource functions run in AWS Emulator's own Lambda runtime, which can fail (pass ${NO_LOCAL_CUSTOM_RESOURCES_FLAG} to silence this).`);
863
+ return;
864
+ }
865
+ let deployed;
866
+ try {
867
+ deployed = await clients.lambda.send(new GetFunctionConfigurationCommand({ FunctionName: serviceToken }));
868
+ } catch (err) {
869
+ logger.debug(safeMsg`GetFunctionConfiguration failed: ${describeAwsFailure(err).detail}`);
870
+ return;
871
+ }
872
+ const stacks = synthesizedStacks();
873
+ if (stacks.length === 0) {
874
+ warnOnce("no-assembly", noAssemblyWarning(localCustomResourceCommand()));
875
+ return;
876
+ }
877
+ const choice = chooseServiceTokenFunction(findServiceTokenFunctions(stacks, customResourceLogicalId), deployed, getCurrentStackName() ?? customResourceStackName());
878
+ if ("reason" in choice) {
879
+ warnOnce(`resolve:${customResourceLogicalId}`, safeMsg`Custom resource ${customResourceLogicalId}: ${choice.reason}, so ${fallback}.`);
880
+ return;
881
+ }
882
+ const lambda = choice.lambda;
883
+ const image = resolveRuntimeImage(lambda.runtime);
884
+ if (!await runtimeImageAvailable(image)) {
885
+ warnOnce(`image:${image}`, safeMsg`The Lambda runtime image ${image} is not available locally and could not be pulled, so ` + `${lambda.runtime} custom resource functions run in AWS Emulator's own Lambda runtime instead.`);
886
+ return;
887
+ }
888
+ logger.info(safeMsg`Running custom resource ${customResourceLogicalId}'s function ${lambda.logicalId} (${lambda.runtime}) in the Lambda runtime image locally`);
889
+ const response = await responseUrlForContainer(clients.s3, request["ResponseURL"]);
890
+ return runInContainer({
891
+ lambda,
892
+ deployed,
893
+ forwardPort: response.forwardPort
894
+ }, serviceToken, response.url === void 0 ? request : {
895
+ ...request,
896
+ ResponseURL: response.url
897
+ }, await secondHopEndpoint(clients.lambda));
898
+ }
899
+ function lambdaClientForRegion(base) {
900
+ const byRegion = /* @__PURE__ */ new Map();
901
+ return async (functionName) => {
902
+ const region = regionOfFunctionArn(functionName);
903
+ if (region === void 0 || region === await base.config.region()) return base;
904
+ let client = byRegion.get(region);
905
+ if (client === void 0) {
906
+ client = new LambdaClient({
907
+ ...ambientClientDefaults(),
908
+ region
909
+ });
910
+ byRegion.set(region, client);
911
+ }
912
+ return client;
913
+ };
914
+ }
915
+ function secondHopEndpoint(lambdaClient) {
916
+ if (secondHopDisabled) return Promise.resolve(void 0);
917
+ secondHop ??= (async () => {
918
+ const wiring = getActiveWorkloadAwsWiring$1();
919
+ if (wiring === void 0 || wiring.emulatorEndpoint === void 0 || wiring.emulatorCredentials === void 0 || !wiring.emulatorEndpoint.loopback) return;
920
+ const clientFor = lambdaClientForRegion(lambdaClient);
921
+ try {
922
+ return await startSecondHopEndpoint({
923
+ getFunctionConfiguration: async (functionName) => {
924
+ try {
925
+ return await (await clientFor(functionName)).send(new GetFunctionConfigurationCommand({ FunctionName: functionName }));
926
+ } catch (err) {
927
+ getLogger().debug(safeMsg`GetFunctionConfiguration(${functionName}) failed: ${describeAwsFailure(err).detail}`);
928
+ return;
929
+ }
930
+ },
931
+ chooseFunction: (caller, logicalId, deployed) => chooseServiceTokenFunction([{
932
+ stack: caller.lambda.stack,
933
+ logicalId,
934
+ resource: caller.lambda.stack.template.Resources[logicalId]
935
+ }], deployed, caller.lambda.stack.stackName),
936
+ imageAvailable: (lambda) => runtimeImageAvailable(resolveRuntimeImage(lambda.runtime)),
937
+ runLocally: async (target, event) => runInContainer(target, target.deployed.FunctionArn ?? "", event, await secondHopEndpoint(lambdaClient)),
938
+ forward: forwardToEmulator,
939
+ emulatorCredentials: wiring.emulatorCredentials,
940
+ ...process.platform === "linux" && { containerGateway: dockerBridgeGateway },
941
+ sleep: (ms) => new Promise((resolveSleep) => {
942
+ setTimeout(resolveSleep, ms).unref();
943
+ })
944
+ });
945
+ } catch (err) {
946
+ getLogger().debug(safeMsg`The cr.Provider endpoint did not start: ${err instanceof Error ? err.message : String(err)}`);
947
+ return;
948
+ }
949
+ })();
950
+ return secondHop;
951
+ }
952
+ async function responseUrlForContainer(s3Client, responseUrl) {
953
+ const endpoint = getActiveWorkloadAwsWiring$1()?.emulatorEndpoint;
954
+ if (typeof responseUrl !== "string" || endpoint === void 0 || !endpoint.loopback) return {};
955
+ const emulatorUrl = endpoint.url;
956
+ let url;
957
+ let emulator;
958
+ try {
959
+ url = new URL(responseUrl);
960
+ emulator = new URL(emulatorUrl);
961
+ } catch {
962
+ return {};
963
+ }
964
+ if (url.origin !== emulator.origin || url.protocol !== "https:" || url.port === "") return {};
965
+ const [, bucket, ...keyParts] = url.pathname.split("/");
966
+ if (!bucket || keyParts.length === 0) return {};
967
+ const origin = `https://${url.hostname}`;
968
+ const signer = await responsePresignClient(s3Client, {
969
+ url: origin,
970
+ origin,
971
+ httpsOnDefaultPort: true
972
+ });
973
+ return {
974
+ url: await getSignedUrl(signer, new PutObjectCommand({
975
+ Bucket: decodeURIComponent(bucket),
976
+ Key: keyParts.map((p) => decodeURIComponent(p)).join("/")
977
+ }), { expiresIn: RESPONSE_URL_EXPIRES_IN_SECONDS }),
978
+ forwardPort: Number(url.port)
979
+ };
980
+ }
981
+ const SECOND_HOP_ENDPOINT_ENV_KEYS = ["AWS_ENDPOINT_URL_LAMBDA", "AWS_ENDPOINT_URL_SFN"];
982
+ async function runInContainer(fn, functionArn, request, endpoint) {
983
+ const { lambda, deployed, forwardPort } = fn;
984
+ const logger = getLogger();
985
+ const hop = endpoint?.register(fn);
986
+ let imagePlan;
987
+ let containerId;
988
+ let forwarderId;
989
+ let logStream;
990
+ const logChunks = [];
991
+ const tmpDirs = () => [
992
+ imagePlan?.inlineTmpDir,
993
+ imagePlan?.layersTmpDir,
994
+ ...imagePlan?.layerArnTmpDirs ?? []
995
+ ].filter((d) => d !== void 0);
996
+ const containerName = `cdkd-cr-${randomBytes(6).toString("hex")}`;
997
+ const forwarderName = `${containerName}-443`;
998
+ const starting = [];
999
+ const onExit = () => {
1000
+ removeContainersSync([...starting].reverse());
1001
+ for (const dir of tmpDirs()) rmSync(dir, {
1002
+ recursive: true,
1003
+ force: true
1004
+ });
1005
+ };
1006
+ exitCleanups.add(onExit);
1007
+ if (!exitHookInstalled) {
1008
+ exitHookInstalled = true;
1009
+ process.on("exit", () => {
1010
+ for (const cleanup of exitCleanups) cleanup();
1011
+ });
1012
+ }
1013
+ try {
1014
+ imagePlan = await resolveZipImagePlan(lambda, { pull: false });
1015
+ const functionEnv = deployed.Environment?.Variables ?? {};
1016
+ const timeoutSec = deployed.Timeout ?? lambda.timeoutSec;
1017
+ const env = {
1018
+ AWS_LAMBDA_FUNCTION_NAME: deployed.FunctionName ?? lambda.logicalId,
1019
+ AWS_LAMBDA_FUNCTION_MEMORY_SIZE: String(deployed.MemorySize ?? lambda.memoryMb),
1020
+ AWS_LAMBDA_FUNCTION_TIMEOUT: String(timeoutSec),
1021
+ AWS_LAMBDA_FUNCTION_VERSION: "$LATEST",
1022
+ AWS_LAMBDA_LOG_GROUP_NAME: `/aws/lambda/${deployed.FunctionName ?? lambda.logicalId}`,
1023
+ AWS_LAMBDA_LOG_STREAM_NAME: "local",
1024
+ ...functionEnv
1025
+ };
1026
+ setContainerRegion(env, regionOfFunctionArn(functionArn) ?? lambda.stack.region);
1027
+ const hopEnv = {};
1028
+ if (hop !== void 0) for (const key of SECOND_HOP_ENDPOINT_ENV_KEYS) hopEnv[key] = hop.url;
1029
+ const hostPort = await pickFreePort();
1030
+ const extraHosts = await resolveHostGatewayExtraHosts();
1031
+ starting.push(containerName);
1032
+ const plan = imagePlan;
1033
+ const runOptions = (name, withHop) => ({
1034
+ name,
1035
+ image: plan.image,
1036
+ mounts: plan.mounts,
1037
+ ...plan.extraMounts !== void 0 && { extraMounts: plan.extraMounts },
1038
+ env,
1039
+ sensitiveEnvKeys: new Set(Object.keys(functionEnv)),
1040
+ ...withHop && hop !== void 0 && {
1041
+ envAfterWiring: hopEnv,
1042
+ extraLoopbackPorts: [hop.port]
1043
+ },
1044
+ ...extraHosts.length > 0 && { extraHosts },
1045
+ cmd: plan.cmd,
1046
+ hostPort,
1047
+ host: CONTAINER_HOST,
1048
+ ...plan.platform !== void 0 && { platform: plan.platform },
1049
+ ...plan.tmpfs !== void 0 && { tmpfs: plan.tmpfs }
1050
+ });
1051
+ try {
1052
+ containerId = await runDetached(runOptions(containerName, true));
1053
+ } catch (err) {
1054
+ if (hop === void 0 || err?.code !== "LOCAL_AWS_EMULATOR_FORWARDER_FAILED") throw err;
1055
+ const retryName = `${containerName}-nohop`;
1056
+ starting.push(retryName);
1057
+ containerId = await runDetached(runOptions(retryName, false));
1058
+ secondHopDisabled = true;
1059
+ warnOnce("second-hop", safeMsg`The cr.Provider endpoint is not reachable from containers (${err instanceof Error ? err.message : String(err)}), so a cr.Provider's handlers run in AWS Emulator's own Lambda runtime.`);
1060
+ }
1061
+ logStream = followContainerLogs(containerId, {
1062
+ stdout: (chunk) => logChunks.push(chunk),
1063
+ stderr: (chunk) => logChunks.push(chunk)
1064
+ });
1065
+ if (forwardPort !== void 0) {
1066
+ starting.push(forwarderName);
1067
+ forwarderId = await startNamespacePortForwarder(containerId, 443, forwardPort, void 0, forwarderName);
1068
+ }
1069
+ await waitForRieReady(CONTAINER_HOST, hostPort, 5e3);
1070
+ const invokeTimeoutMs = Math.max(3e4, timeoutSec * 2 * 1e3);
1071
+ const result = await invokeRie(CONTAINER_HOST, hostPort, request, invokeTimeoutMs);
1072
+ await killAndDrainContainerLogs(containerId, logStream);
1073
+ logStream = void 0;
1074
+ const logTail = Buffer.concat(logChunks).subarray(-4096);
1075
+ return {
1076
+ StatusCode: 200,
1077
+ ExecutedVersion: "$LATEST",
1078
+ Payload: Buffer.from(result.raw),
1079
+ ...isRuntimeError(result.payload) && { FunctionError: "Unhandled" },
1080
+ ...logTail.length > 0 && { LogResult: logTail.toString("base64") }
1081
+ };
1082
+ } finally {
1083
+ await killAndDrainContainerLogs(containerId, logStream).catch(() => void 0);
1084
+ if (forwarderId !== void 0) await removeContainer(forwarderId).catch(() => void 0);
1085
+ const toRemove = containerId ?? (starting.includes(containerName) ? containerName : void 0);
1086
+ if (toRemove !== void 0) await removeContainer(toRemove).catch((err) => {
1087
+ logger.debug(safeMsg`removeContainer(${toRemove}) failed: ${String(err)}`);
1088
+ });
1089
+ for (const dir of tmpDirs()) rmSync(dir, {
1090
+ recursive: true,
1091
+ force: true
1092
+ });
1093
+ exitCleanups.delete(onExit);
1094
+ hop?.release();
1095
+ }
1096
+ }
1097
+ function isRuntimeError(payload) {
1098
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) return false;
1099
+ const p = payload;
1100
+ return typeof p["errorMessage"] === "string" && typeof p["errorType"] === "string";
1101
+ }
1102
+
1103
+ export { invokeCustomResourceFunctionLocally };
1104
+ //# sourceMappingURL=custom-resource-runtime-Dwnnj7bg.js.map