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

feat(nuxt): Configure sentry in external config #12681

Merged
merged 10 commits into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 14 additions & 10 deletions packages/nuxt/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,24 @@ If the setup through the wizard doesn't work for you, you can also set up the SD

The Sentry Nuxt SDK is based on [Nuxt Modules](https://nuxt.com/docs/api/kit/modules).

1. Add `@sentry/nuxt` to the modules section of `nuxt.config.ts`:
1. Add `@sentry/nuxt/module` to the modules section of `nuxt.config.ts`:
s1gr1d marked this conversation as resolved.
Show resolved Hide resolved

```javascript
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@sentry/nuxt'],
runtimeConfig: {
public: {
sentry: {
dsn: env.DSN,
// Additional config
},
},
},
modules: ['@sentry/nuxt/module'],
});
```

2. Add a `sentry.client.config.(js|ts)` file to the root of your project:

```javascript
import * as Sentry from '@sentry/nuxt';

Sentry.init({
dsn: env.DSN,
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});
```

Expand Down
36 changes: 25 additions & 11 deletions packages/nuxt/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,25 @@
"files": [
"/build"
],
"main": "build/module.cjs",
"module": "build/module.mjs",
"types": "build/types.d.ts",
"main": "build/cjs/index.server.js",
"module": "build/esm/index.server.js",
"browser": "build/esm/index.client.js",
"types": "build/types/index.types.d.ts",
"exports": {
"./package.json": "./package.json",
".": {
"types": "./build/types.d.ts",
"import": "./build/module.mjs",
"require": "./build/module.cjs"
"types": "./build/types/index.types.d.ts",
"browser": {
"import": "./build/esm/index.client.js",
"require": "./build/cjs/index.client.js"
},
"node": "./build/cjs/index.server.js"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m: this should be both esm and cjs

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually I'd double check this too to see if ESM works well on the server 😅

},
"./package.json": "./package.json"
"./module": {
"types": "./build/module/types.d.ts",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: Will we have to do the same as for solid here, where types for a submodule export have to be in the root? 😬 no need to adjust this in this PR, but have a look at it in a follow up, and maybe sync with @andreiborza on this :)

"import": "./build/module/module.mjs",
"require": "./build/module/module.cjs"
}
},
"publishConfig": {
"access": "public"
Expand All @@ -31,6 +40,7 @@
},
"dependencies": {
"@nuxt/kit": "^3.12.2",
"@sentry/browser": "8.13.0",
"@sentry/core": "8.13.0",
"@sentry/node": "8.13.0",
"@sentry/opentelemetry": "8.13.0",
Expand All @@ -41,15 +51,18 @@
},
"devDependencies": {
"@nuxt/module-builder": "0.8.0",
"nitropack": "2.9.6",
"nuxt": "^3.12.2"
},
"scripts": {
"build": "run-p build:transpile",
"build": "run-p build:transpile build:types build:nuxt-module",
"build:dev": "yarn build",
"build:transpile": "nuxt-module-build build --outDir build",
"build:nuxt-module": "nuxt-module-build build --outDir build/module",
"build:transpile": "rollup -c rollup.npm.config.mjs",
"build:types": "tsc -p tsconfig.types.json",
"build:watch": "run-p build:transpile:watch build:types:watch",
"build:dev:watch": "yarn build:watch",
"build:transpile:watch": "nuxt-module-build build --outDir build --watch",
"build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch",
"build:types:watch": "tsc -p tsconfig.types.json --watch",
"build:tarball": "npm pack",
"circularDepCheck": "madge --circular src/index.client.ts && madge --circular src/index.server.ts && madge --circular src/index.types.ts",
Expand All @@ -72,7 +85,8 @@
"^build:types"
],
"outputs": [
"{projectRoot}/build"
"{projectRoot}/build",
"{projectRoot}/build/module"
]
}
}
Expand Down
7 changes: 7 additions & 0 deletions packages/nuxt/rollup.npm.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollup-utils';

export default makeNPMConfigVariants(
makeBaseNPMConfig({
entrypoints: ['src/index.server.ts', 'src/index.client.ts', 'src/client/index.ts', 'src/server/index.ts'],
}),
);
4 changes: 2 additions & 2 deletions packages/nuxt/src/client/sdk.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { applySdkMetadata } from '@sentry/core';
import type { Client } from '@sentry/types';
import { init as initVue } from '@sentry/vue';
import { init as initBrowser } from '@sentry/browser';
import type { SentryVueOptions } from '../common/types';

/**
Expand All @@ -15,5 +15,5 @@ export function init(options: SentryVueOptions): Client | undefined {

applySdkMetadata(sentryOptions, 'nuxt', ['nuxt', 'vue']);

return initVue(sentryOptions);
return initBrowser(sentryOptions);
}
8 changes: 8 additions & 0 deletions packages/nuxt/src/common/debug-build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
declare const __DEBUG_BUILD__: boolean;

/**
* This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
*
* ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
*/
export const DEBUG_BUILD = __DEBUG_BUILD__;
39 changes: 39 additions & 0 deletions packages/nuxt/src/common/snippets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as fs from 'fs';
import * as path from 'path';

// todo: tests
/** Returns an import snippet */
export function buildSdkInitFileImportSnippet(filePath: string): string {
const pathToPosix = (originalPath: string): string => {
return originalPath.split(path.sep).join(path.posix.sep);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

l: why elect for the inline function pathToPosix over

const posixPath = filePath.split(path.sep).join(path.posix.sep);

return `import "${posixPath}"`

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True 😅 I had two functions first and moved pathToPosix inside the other one.

};

return `import "${pathToPosix(filePath)}";`;
}

// todo: tests
/** Adds an import statement right after <script setup> */
export function addImportStatement(filePath: string, importStatement: string): void {
AbhiPrasad marked this conversation as resolved.
Show resolved Hide resolved
try {
const data = fs.readFileSync(filePath, 'utf8');
const scriptIndex = data.indexOf('<script setup>');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m: Let's extract <script setup> into a constant, and add a comment about why we are looking for this.


// Insert the import statement after the script tag
const output = [
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

l: I think doing string.replace is a bit easier to understand then indexOf + constructing a new output via slice

const output = data.replace(SETUP_TAG, `${SETUP_TAG}\n${importStatement}`);

data.slice(0, scriptIndex + '<script setup>'.length),
'\n',
importStatement,
data.slice(scriptIndex + '<script setup>'.length),
].join('');

try {
fs.writeFileSync(filePath, output, 'utf8');
} catch (err) {
// eslint-disable-next-line no-console
console.error(`Error writing file: ${err}`);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m: Can we indicate that this comes from sentry? Same with console.error below.

}
} catch (err) {
// eslint-disable-next-line no-console
console.error(`Error reading file: ${err}`);
}
}
2 changes: 1 addition & 1 deletion packages/nuxt/src/common/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import type { init } from '@sentry/vue';

export type SentryVueOptions = Parameters<typeof init>[0] & object;
export type SentryVueOptions = Omit<Parameters<typeof init>[0] & object, 'app'>;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

l: Would be useful to leave a comment about why this we have a difference between vue init and nuxt init here.

2 changes: 1 addition & 1 deletion packages/nuxt/src/index.server.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export {};
export * from './server';
2 changes: 1 addition & 1 deletion packages/nuxt/src/index.types.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export {};
export * from './client';
35 changes: 31 additions & 4 deletions packages/nuxt/src/module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { type Resolver, addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit';
import * as fs from 'fs';
import * as path from 'path';
import { type Resolver, addPlugin, addServerPlugin, createResolver, defineNuxtModule } from '@nuxt/kit';
import { addImportStatement, buildSdkInitFileImportSnippet } from './common/snippets';
import type { SentryVueOptions } from './common/types';

export type ModuleOptions = SentryVueOptions;
Expand All @@ -11,13 +14,37 @@ export default defineNuxtModule<ModuleOptions>({
nuxt: '^3.0.0',
},
},
// Default configuration options of the Nuxt module
defaults: {},
setup(_moduleOptions, _nuxt) {
setup(_moduleOptions, nuxt) {
const resolver: Resolver = createResolver(import.meta.url);

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

l: Can we double check to see if this works with CJS? How does this get transpiled? We currently have build/module/module.cjs emitted.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the module, I am using the nuxt module builder which transpiles the files exactly how they should be imported in Nuxt. The module.cjs looks like this:

module.exports = function(...args) {
  return import('./module.mjs').then(m => m.default.call(this, ...args))
}
const _meta = module.exports.meta = require('./module.json')
module.exports.getMeta = () => Promise.resolve(_meta)

const pathToClientInit = findDefaultSdkInitFile('client');

if (pathToClientInit) {
nuxt.hook('app:templates', nuxtApp => {
if (nuxtApp.rootComponent) {
try {
addImportStatement(nuxtApp.rootComponent, buildSdkInitFileImportSnippet(pathToClientInit));
} catch (err) {
// eslint-disable-next-line no-console
console.error(err);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m: we should add some notes that this is coming from sentry and we encountered this error while trying to add imports.

}
});
}

if (resolver) {
addPlugin(resolver.resolve('runtime/plugins/sentry.client.js'));
addPlugin(resolver.resolve('./runtime/plugins/sentry.client'));
addServerPlugin(resolver.resolve('./runtime/plugins/sentry.server'));
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m: It seems like this PR has some server-side logic with the addServerPlugin and the server side sdk being exposed.

To ease reviewing, could we remove these changes from this PR and add it later when we look at the server-side stuff?

},
});

function findDefaultSdkInitFile(type: 'server' | 'client'): string | undefined {
const possibleFileExtensions = ['ts', 'js', 'mjs', 'cjs', 'mts'];

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const possibleFileExtensions = ['ts', 'js', 'mjs', 'cjs', 'mts'];
const possibleFileExtensions = ['ts', 'js', 'mjs', 'cjs', 'mts', 'cts'];

const cwd = process.cwd();
return possibleFileExtensions
.map(e => path.resolve(path.join(cwd, `sentry.${type}.config.${e}`)))
.find(filename => fs.existsSync(filename));
}
12 changes: 4 additions & 8 deletions packages/nuxt/src/runtime/plugins/sentry.client.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import { defineNuxtPlugin, useRuntimeConfig } from 'nuxt/app';
import { init } from '../../client';
import * as Sentry from '@sentry/vue';
import { defineNuxtPlugin } from 'nuxt/app';

export default defineNuxtPlugin(nuxtApp => {
const config = useRuntimeConfig();
const sentryConfig = config.public.sentry || {};

init({
...sentryConfig,
app: nuxtApp.vueApp,
nuxtApp.hook('app:created', vueApp => {
Sentry.addIntegration(Sentry.vueIntegration({ app: vueApp }));
});
});
4 changes: 4 additions & 0 deletions packages/nuxt/src/runtime/plugins/sentry.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { defineNitroPlugin } from 'nitropack/runtime';

// eslint-disable-next-line @typescript-eslint/no-empty-function
export default defineNitroPlugin(_nitroApp => {});
3 changes: 3 additions & 0 deletions packages/nuxt/src/server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// todo: export @sentry/node

export { init } from './sdk';
23 changes: 23 additions & 0 deletions packages/nuxt/src/server/sdk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { applySdkMetadata, setTag } from '@sentry/core';
import type { NodeClient, NodeOptions } from '@sentry/node';
import { getDefaultIntegrations as getDefaultNodeIntegrations } from '@sentry/node';
import { init as initNodeSdk } from '@sentry/node';

/**
*
* @param options
*/
export function init(options: NodeOptions): NodeClient | undefined {
const sentryOptions = {
defaultIntegrations: [...getDefaultNodeIntegrations(options)],
...options,
};

applySdkMetadata(sentryOptions, 'nuxt', ['nuxt', 'vue']);

const client = initNodeSdk(sentryOptions);

setTag('runtime', 'node');

return client;
}
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -25455,7 +25455,7 @@ nise@^5.1.4:
just-extend "^4.0.2"
path-to-regexp "^1.7.0"

nitropack@^2.9.6:
nitropack@2.9.6, nitropack@^2.9.6:
version "2.9.6"
resolved "https://registry.yarnpkg.com/nitropack/-/nitropack-2.9.6.tgz#90af114b796872f34e125e780e6148525149769f"
integrity sha512-HP2PE0dREcDIBVkL8Zm6eVyrDd10/GI9hTL00PHvjUM8I9Y/2cv73wRDmxNyInfrx/CJKHATb2U/pQrqpzJyXA==
Expand Down
Loading