Skip to content

Commit 6ea71e5

Browse files
fix: CDK paths
1 parent fa99088 commit 6ea71e5

File tree

1 file changed

+57
-2
lines changed

1 file changed

+57
-2
lines changed

src/frameworks/cdkFrameworkWorker.mjs

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
import { createRequire as topLevelCreateRequire } from "module";
22
const require = topLevelCreateRequire(import.meta.url);
3+
import path from "path";
4+
import { fileURLToPath } from "node:url";
5+
const __filename = fileURLToPath(import.meta.url);
6+
const __dirname = path.dirname(__filename);
37

48
import { workerData, parentPort } from "node:worker_threads";
59
import fs from "fs/promises";
6-
import path from "path";
710

811
import { Logger } from "../logger.mjs";
912

@@ -18,7 +21,9 @@ parentPort.on("message", async (data) => {
1821

1922
// execute code to get the data into global.lambdas
2023
const codeFile = await fs.readFile(data.compileOutput, "utf8");
21-
const __dirname = path.resolve("./x"); // CDK needs this, pure magic
24+
25+
fixCdkPaths();
26+
2227
eval(codeFile);
2328

2429
if (!global.lambdas || global.lambdas?.length === 0) {
@@ -45,3 +50,53 @@ parentPort.on("message", async (data) => {
4550
);
4651
parentPort.postMessage(lambdas);
4752
});
53+
54+
/**
55+
* Some paths are not resolved correctly in the CDK code, so we need to fix them
56+
*/
57+
function fixCdkPaths() {
58+
//const path = require("path"); // leave this line for manual debugging
59+
60+
// Get the path to the aws-cdk-lib module
61+
let awsCdkLibPath = require.resolve("aws-cdk-lib");
62+
awsCdkLibPath = awsCdkLibPath.replace("/index.js", "");
63+
Logger.verbose(`[CDK] [Worker] aws-cdk-lib PATH ${awsCdkLibPath}`);
64+
65+
const pathsFix = {
66+
"custom-resource-handlers/": `${awsCdkLibPath}/custom-resource-handlers/`,
67+
};
68+
69+
// Create a proxy to intercept calls to the path module so we can fix paths
70+
const pathProxy = new Proxy(path, {
71+
get(target, prop) {
72+
if (typeof target[prop] === "function") {
73+
return function (...args) {
74+
if (prop === "resolve") {
75+
let resolvedPath = target[prop].apply(target, args);
76+
77+
for (const [key, value] of Object.entries(pathsFix)) {
78+
if (resolvedPath.includes(key)) {
79+
// replace the beginning of the path with the value
80+
const i = resolvedPath.indexOf(key);
81+
const newResolvedPath = `${value}${resolvedPath.substring(i + key.length)}`;
82+
Logger.verbose(
83+
`[CDK] [Worker] Fixing path ${resolvedPath} -> ${newResolvedPath}`
84+
);
85+
resolvedPath = newResolvedPath;
86+
}
87+
}
88+
89+
return resolvedPath;
90+
}
91+
return target[prop].apply(target, args);
92+
};
93+
}
94+
return target[prop];
95+
},
96+
});
97+
98+
// Override the path module in the require cache
99+
require.cache[require.resolve("path")] = {
100+
exports: pathProxy,
101+
};
102+
}

0 commit comments

Comments
 (0)