@@ -212,26 +212,83 @@ export class CdkFramework implements IFramework {
212212 config : LldConfigBase ,
213213 ) {
214214 const entryFile = await this . getCdkEntryFile ( cdkConfigPath ) ;
215- // Define a plugin to prepend custom code to .ts or .tsx files
215+ let isESM = false ;
216+ const packageJsonPath = await findPackageJson ( entryFile ) ;
217+
218+ if ( packageJsonPath ) {
219+ try {
220+ const packageJson = JSON . parse (
221+ await fs . readFile ( packageJsonPath , { encoding : 'utf-8' } ) ,
222+ ) ;
223+ if ( packageJson . type === 'module' ) {
224+ isESM = true ;
225+ Logger . verbose ( `[CDK] Using ESM format` ) ;
226+ }
227+ } catch ( err : any ) {
228+ Logger . error (
229+ `Error reading CDK package.json (${ packageJsonPath } ): ${ err . message } ` ,
230+ err ,
231+ ) ;
232+ }
233+ }
234+
235+ const rootDir = process . cwd ( ) ;
236+
237+ // Plugin that:
238+ // - Fixes __dirname issues
239+ // - Injects code to get the file path of the Lambda function and CDK hierarchy
216240 const injectCodePlugin : esbuild . Plugin = {
217241 name : 'injectCode' ,
218242 setup ( build : esbuild . PluginBuild ) {
219243 build . onLoad ( { filter : / .* / } , async ( args : esbuild . OnLoadArgs ) => {
220- const absolutePath = path . resolve ( args . path ) ;
244+ // fix __dirname issues
245+ const isWindows = / ^ w i n / . test ( process . platform ) ;
246+ const esc = ( p : string ) => ( isWindows ? p . replace ( / \\ / g, '/' ) : p ) ;
247+
248+ const variables = `
249+ const __fileloc = {
250+ filename: "${ esc ( args . path ) } ",
251+ dirname: "${ esc ( path . dirname ( args . path ) ) } ",
252+ relativefilename: "${ esc ( path . relative ( rootDir , args . path ) ) } ",
253+ relativedirname: "${ esc (
254+ path . relative ( rootDir , path . dirname ( args . path ) ) ,
255+ ) } ",
256+ import: { meta: { url: "file://${ esc ( args . path ) } " } }
257+ };
258+ ` ;
259+
260+ let fileContent = new TextDecoder ( ) . decode (
261+ await fs . readFile ( args . path ) ,
262+ ) ;
221263
222- let source = await fs . readFile ( absolutePath , 'utf8' ) ;
264+ // remove shebang
265+ if ( fileContent . startsWith ( '#!' ) ) {
266+ const firstNewLine = fileContent . indexOf ( '\n' ) ;
267+ fileContent = fileContent . slice ( firstNewLine + 1 ) ;
268+ }
269+
270+ let contents : string ;
271+ if ( args . path . endsWith ( '.ts' ) || args . path . endsWith ( '.js' ) ) {
272+ // add the variables at the top of the file, that contains the file location
273+ contents = `${ variables } \n${ fileContent } ` ;
274+ } else {
275+ contents = fileContent ;
276+ }
223277
278+ const loader = args . path . split ( '.' ) . pop ( ) as esbuild . Loader ;
279+
280+ // Inject code to get the file path of the Lambda function and CDK hierarchy
224281 if ( args . path . includes ( 'aws-cdk-lib/aws-lambda/lib/function.' ) ) {
225282 const codeToFind =
226283 'try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_FunctionProps(props)}' ;
227284
228- if ( ! source . includes ( codeToFind ) ) {
285+ if ( ! contents . includes ( codeToFind ) ) {
229286 throw new Error ( `Can not find code to inject in ${ args . path } ` ) ;
230287 }
231288
232289 // Inject code to get the file path of the Lambda function and CDK hierarchy
233290 // path to match it with the Lambda function. Store data in the global variable.
234- source = source . replace (
291+ contents = contents . replace (
235292 codeToFind ,
236293 `;
237294 global.lambdas = global.lambdas ?? [];
@@ -264,55 +321,28 @@ export class CdkFramework implements IFramework {
264321 ) {
265322 const codeToFind = 'super(scope,id),this.requestDestinationArn=!1;' ;
266323
267- if ( ! source . includes ( codeToFind ) ) {
324+ if ( ! contents . includes ( codeToFind ) ) {
268325 throw new Error ( `Can not find code to inject in ${ args . path } ` ) ;
269326 }
270327
271328 // Inject code to prevent deploying the assets
272- source = source . replace ( codeToFind , codeToFind + `return;` ) ;
329+ contents = contents . replace ( codeToFind , codeToFind + `return;` ) ;
273330 }
274331
275332 return {
276- contents : source ,
277- loader : 'default' ,
333+ contents,
334+ loader,
278335 } ;
279336 } ) ;
280337 } ,
281338 } ;
282339
283- let isESM = false ;
284- // get packgage.json
285- const packageJsonPath = await findPackageJson ( entryFile ) ;
286-
287- if ( packageJsonPath ) {
288- try {
289- const packageJson = JSON . parse (
290- await fs . readFile ( packageJsonPath , { encoding : 'utf-8' } ) ,
291- ) ;
292- if ( packageJson . type === 'module' ) {
293- isESM = true ;
294- Logger . verbose ( `[CDK] Using ESM format` ) ;
295- }
296- } catch ( err : any ) {
297- Logger . error (
298- `Error reading CDK package.json (${ packageJsonPath } ): ${ err . message } ` ,
299- err ,
300- ) ;
301- }
302- }
303-
304340 const compileOutput = path . join (
305341 getProjectDirname ( ) ,
306342 outputFolder ,
307343 `compiledCdk.${ isESM ? 'mjs' : 'cjs' } ` ,
308344 ) ;
309345
310- const dirname = path . join (
311- ...( [ getProjectDirname ( ) , config . subfolder , 'x' ] . filter (
312- ( p ) => p ,
313- ) as string [ ] ) ,
314- ) ;
315-
316346 try {
317347 // Build CDK code
318348 await esbuild . build ( {
@@ -331,7 +361,6 @@ export class CdkFramework implements IFramework {
331361 banner : {
332362 js : [
333363 `import { createRequire as topLevelCreateRequire } from 'module';` ,
334- `import.meta.url = 'file:///${ dirname } /cdkFrameworkWorker.mjs';` ,
335364 `global.require = global.require ?? topLevelCreateRequire(import.meta.url);` ,
336365 `import { fileURLToPath as topLevelFileUrlToPath, URL as topLevelURL } from "url"` ,
337366 `global.__dirname = global.__dirname ?? topLevelFileUrlToPath(new topLevelURL(".", import.meta.url))` ,
@@ -341,10 +370,15 @@ export class CdkFramework implements IFramework {
341370 : {
342371 format : 'cjs' ,
343372 target : 'node18' ,
344- banner : {
345- js : [ `__dirname = '${ dirname } ';` ] . join ( '\n' ) ,
346- } ,
347373 } ) ,
374+ define : {
375+ // replace __dirname,... with the a variable that contains the file location
376+ __filename : '__fileloc.filename' ,
377+ __dirname : '__fileloc.dirname' ,
378+ __relativefilename : '__fileloc.relativefilename' ,
379+ __relativedirname : '__fileloc.relativedirname' ,
380+ 'import.meta.url' : '__fileloc.import.meta.url' ,
381+ } ,
348382 } ) ;
349383 } catch ( error : any ) {
350384 throw new Error ( `Error building CDK code: ${ error . message } ` , {
0 commit comments