Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v8 Node + ESM + esbuild error #12009

Open
3 tasks done
jd-carroll opened this issue May 13, 2024 · 9 comments
Open
3 tasks done

v8 Node + ESM + esbuild error #12009

jd-carroll opened this issue May 13, 2024 · 9 comments

Comments

@jd-carroll
Copy link

Is there an existing issue for this?

How do you use Sentry?

Sentry Saas (sentry.io)

Which SDK are you using?

@sentry/aws-serverless

SDK Version

8.0.0

Framework Version

No response

Link to Sentry event

No response

SDK Setup

No response

Steps to Reproduce

For completeness I thought I would link this here too: open-telemetry/opentelemetry-js#4691

When bundling @sentry/...@^8 in a "full ESM" mode, you will get (potentially) hundreds of errors along the lines of:

WARN  ▲ [WARNING] Constructing "ImportInTheMiddle" will crash at run-time because it's an import namespace object, not a constructor [call-import-namespace]
   ../../node_modules/@prisma/instrumentation/node_modules/@opentelemetry/instrumentation/build/esm/platform/node/instrumentation.js:273:30:
     273 │             var esmHook = new ImportInTheMiddle([
         ╵                               ~~~~~~~~~~~~~~~~~
 Consider changing "ImportInTheMiddle" to a default import instead:
   ../../node_modules/@prisma/instrumentation/node_modules/@opentelemetry/instrumentation/build/esm/platform/node/instrumentation.js:55:7:
     55 │ import * as ImportInTheMiddle from 'import-in-the-middle';
        │        ~~~~~~~~~~~~~~~~~~~~~~
        ╵        ImportInTheMiddle

I have not taken the time to identify how / when this error could be encountered, but can confirm that doing the following in a module environment will throw an error:

import * as ImportInTheMiddle from 'import-in-the-middle';
var esmHook = new ImportInTheMiddle( ... );

The instantiation would need to look like:

var esmHook = new ImportInTheMiddle.default.default( ... );

Would be nice to add some support for either of the following issues:

If for no other reason than eliminating unnecessary warnings during build.

Expected Result

NA

Actual Result

NA

@mydea
Copy link
Member

mydea commented May 14, 2024

Hello,

this is hopefully fixed by #12017!

@lforst
Copy link
Member

lforst commented May 14, 2024

I think this will be an issue for all situations where esbuild is involved. @jd-carroll already you already did the right thing reporting this upstream! As soon as that fix lands in the opentelemetry packages we will bump the dep asap.

@jd-carroll
Copy link
Author

@mydea @lforst This is 100% causing my lambdas to crash and makes using Sentry@v8 not possible for ESM.

Again, at runtime, the lambdas fail with:
image

That stacktrace corresponds to this code:
image

Could someone from @sentry help identify what the path forward for ESM would be?

There seem to be a number of pertinent issues:

@jd-carroll jd-carroll changed the title Possible Instrumentation Crash v8 Unusable for Node + ESM May 23, 2024
@mydea
Copy link
Member

mydea commented May 23, 2024

Hey,

this is most likely fixed by open-telemetry/opentelemetry-js#4546 - we'll try to get this merged & released!

Lms24 added a commit that referenced this issue May 27, 2024
…ddle` (#12233)

Our lambda layer relies on one bundled Sentry SDK, which caused problems
raised in #12089 and
#12009 (comment).
Specifically, by bundling `import-in-the-middle` code into one file, it
seems like the library's way of declaring its exports conflict, causing
the "ImportInTheMiddle is not a constructor" error to be thrown. While
this should ideally be fixed soon in `import-in-the-middle`, for now
this patch adds a small Rollup plugin to transform `new
ImportInTheMiddle(...)` calls to `new ImportInTheMiddle.default(...)` to
our AWS Lambda Layer bundle config.
@AbhiPrasad
Copy link
Member

@jd-carroll could you share the esbuild config you use?

@timfish timfish changed the title v8 Unusable for Node + ESM v8 Node + ESM + esbuild error May 27, 2024
@jd-carroll
Copy link
Author

jd-carroll commented May 28, 2024 via email

@jd-carroll
Copy link
Author

jd-carroll commented May 29, 2024

Here is the raw config:

    // LambdaBundlerConfig
    const LambdaBundlerConfig: BuildOptions = {
      entryPoints: [LambdaEntryFile], // some/file.ts
      outfile: LambdaFile, // options.format === 'cjs' ? 'dist/lambdas/lambda.js' : 'dist/lambdas/lambda.mjs'
      bundle: true,
      sourcemap: 'linked',
      splitting: false,
      platform: 'node',
      mainFields: options.format === 'cjs' ? ['main'] : ['module', 'main'], // almost always ['module', 'main']
      external: options.external || [],
      target: options.target ?? (options.format === 'cjs' ? 'es5' : 'esnext'), // almost always esnext
      format: options.format, // almost always 'esm'
      banner: options.banner, // only used in dev
      minify: options.minify ?? true, // only false in dev
      metafile: true,

      plugins: [
        SentryBuildPlugin(definition, LambdaVersion, SentryEnabled),
        NotifyResultPlugin(),
        WriteEsbuildMetaPlugin(MetaFile),
        ValidateLambdaHandler(definition, LambdaFile, options.format),
        ...(options.plugins ?? [])
      ],
      inject: [SentryEnabled ? SentryInit : undefined, ...inject].filter(Boolean) as string[],
      define: {
        ...definedFlags
      }
    };

I'll also add that the SentryInit which is injected when SentryEnabled, is where the initial Sentry.init() call happens.

Otherwise, the lambda code already includes the Sentry wrapper for AWS lambda.

@jd-carroll
Copy link
Author

NOTE: For all the esbuild'ers out there, here's a simple plugin to get things working that follows #12233

import fs from 'node:fs';
import path from 'node:path';
import type { Plugin } from 'esbuild';

export function FixImportInTheMiddlePlugin(enabled: boolean): Plugin {
  if (!enabled) {
    return {
      name: 'skip-fix-import-in-the-middle',
      setup() {}
    };
  }

  return {
    name: 'fix-import-in-the-middle',
    setup(build) {
      build.onLoad({ filter: /@opentelemetry\/instrumentation/ }, async (args) => {
        const extension = path.extname(args.path).slice(1);

        let text = await fs.promises.readFile(args.path, 'utf-8');
        if (text.includes('* as ImportInTheMiddle')) {
          text = text.replaceAll(/new\s+(ImportInTheMiddle)\(/gm, 'new $1.default(');
        }

        return {
          contents: text,
          loader: (extension === 'mjs' ? 'js' : extension) as 'ts' | 'js'
        };
      });
    }
  };
}

@AbhiPrasad
Copy link
Member

DataDog/import-in-the-middle#88 should fix this with import-in-the-middle, we also have to update OTEL but we'll take care of that too. Appreciate the patience in the meantime @jd-carroll!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: No status
Development

No branches or pull requests

4 participants