Skip to content

Commit

Permalink
fix(astro): handle builtin modules without node prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
anonrig committed Dec 29, 2023
1 parent 66ea1e6 commit dd338b4
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 4 deletions.
16 changes: 13 additions & 3 deletions packages/astro/src/integration/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@ import * as path from 'path';
import { sentryVitePlugin } from '@sentry/vite-plugin';
import type { AstroConfig, AstroIntegration } from 'astro';

import { namespaceBuiltinPlugin } from './namespace';
import { buildClientSnippet, buildSdkInitFileImportSnippet, buildServerSnippet } from './snippets';
import type { SentryOptions } from './types';

const PKG_NAME = '@sentry/astro';

export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => {
return {
name: PKG_NAME,
name: '@sentry/astro',
hooks: {
// eslint-disable-next-line complexity
'astro:config:setup': async ({ updateConfig, injectScript, addMiddleware, config, command }) => {
Expand Down Expand Up @@ -51,6 +50,17 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => {
});
}

// Update Node.js builtin imports for Cloudflare.
// Node.js APIs are available under `node:` prefix.
// Ref: https://developers.cloudflare.com/workers/runtime-apis/nodejs/
if (config?.adapter?.name.startsWith('@astrojs/cloudflare')) {
updateConfig({
vite: {
plugins: [namespaceBuiltinPlugin()],
},
});
}

const pathToClientInit = options.clientInitPath
? path.resolve(options.clientInitPath)
: findDefaultSdkInitFile('client');
Expand Down
26 changes: 26 additions & 0 deletions packages/astro/src/integration/namespace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import module from 'module';
import type { Plugin } from 'vite';

/**
* Cloudflare like environments doesn't support requiring builtin modules
* to be loaded without `node:` prefix. This vite plugin ensures that,
* all built-in modules are loaded with `node:` prefix.
*
* TODO: Remove this when we support Node 18 and above.
*/
export function namespaceBuiltinPlugin(): Plugin {
return {
name: '@sentry/astro',
enforce: 'pre',
resolveId(id) {
if (module.builtinModules.includes(id)) {
return {
id: `node:${id}`,
external: true,
};
}

return undefined;
},
};
}
3 changes: 2 additions & 1 deletion packages/astro/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"include": ["src/**/*"],

"compilerOptions": {
// package-specific options
// Required for importing 'module' for access to builtin modules.
"allowSyntheticDefaultImports": true
}
}

0 comments on commit dd338b4

Please sign in to comment.