Skip to content

feat(sveltekit): Add sentrySvelteKitPlugin #7788

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

Merged
merged 1 commit into from
Apr 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
1 change: 0 additions & 1 deletion packages/sveltekit/src/config/index.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/sveltekit/src/index.server.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './server';
export * from './config';
export * from './vite';
2 changes: 1 addition & 1 deletion packages/sveltekit/src/index.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// Some of the exports collide, which is not allowed, unless we redifine the colliding
// exports in this file - which we do below.
export * from './client';
export * from './config';
export * from './vite';
export * from './server';

import type { Integration, Options, StackParser } from '@sentry/types';
Expand Down
2 changes: 2 additions & 0 deletions packages/sveltekit/src/vite/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { withSentryViteConfig } from './withSentryViteConfig';
export { sentrySvelteKitPlugin } from './sentrySvelteKitPlugin';
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { logger } from '@sentry/utils';
import * as fs from 'fs';
import MagicString from 'magic-string';
import * as path from 'path';
import type { Plugin, TransformResult } from 'vite';

import { getUserConfigFile } from './utils';

const serverIndexFilePath = path.join('@sveltejs', 'kit', 'src', 'runtime', 'server', 'index.js');
const devClientAppFilePath = path.join('generated', 'client', 'app.js');
const prodClientAppFilePath = path.join('generated', 'client-optimized', 'app.js');
Expand Down Expand Up @@ -59,19 +60,3 @@ function addSentryConfigFileImport(

return { code: ms.toString(), map: ms.generateMap() };
}

/**
* Looks up the sentry.{@param platform}.config.(ts|js) file
* @returns the file path to the file or undefined if it doesn't exist
*/
export function getUserConfigFile(projectDir: string, platform: 'server' | 'client'): string | undefined {
const possibilities = [`sentry.${platform}.config.ts`, `sentry.${platform}.config.js`];

for (const filename of possibilities) {
if (fs.existsSync(path.resolve(projectDir, filename))) {
return filename;
}
}

return undefined;
}
54 changes: 54 additions & 0 deletions packages/sveltekit/src/vite/sentrySvelteKitPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type { Plugin, UserConfig } from 'vite';

import { injectSentryInitPlugin } from './injectInitPlugin';
import { hasSentryInitFiles } from './utils';

/**
* Vite Plugin for the Sentry SvelteKit SDK, taking care of:
*
* - Creating Sentry releases and uploading source maps to Sentry
* - Injecting Sentry.init calls if you use dedicated `sentry.(client|server).config.ts` files
Copy link
Member

Choose a reason for hiding this comment

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

should we think about removing this injection behaviour all together then?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yeah I was sort of debating if we should keep it as an alternative but I think the drawback is that we have to support both ways. Also the init location of hook vs. injected init calls differs slightly in the final bundles. Since IMO hooks are the better choice anyway, I'd say we remove it.

But I suggest we do it in a follow up PR, to make reverting easier if we have to, wdyt?

Copy link
Member

Choose a reason for hiding this comment

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

let's do it in a follow up PR!

*
* This plugin adds a few additional properties to your Vite config.
* Make sure, it is registered before the SvelteKit plugin.
*/
export function sentrySvelteKitPlugin(): Plugin {
return {
name: 'sentry-sveltekit',
enforce: 'pre', // we want this plugin to run early enough
config: originalConfig => {
return addSentryConfig(originalConfig);
},
};
}

function addSentryConfig(originalConfig: UserConfig): UserConfig {
const sentryPlugins = [];

const shouldAddInjectInitPlugin = hasSentryInitFiles();

if (shouldAddInjectInitPlugin) {
sentryPlugins.push(injectSentryInitPlugin);
}

const config = {
...originalConfig,
plugins: originalConfig.plugins ? [...sentryPlugins, ...originalConfig.plugins] : [...sentryPlugins],
};

const mergedDevServerFileSystemConfig: UserConfig['server'] = shouldAddInjectInitPlugin
? {
fs: {
...(config.server && config.server.fs),
allow: [...((config.server && config.server.fs && config.server.fs.allow) || []), '.'],
},
}
: {};

config.server = {
...config.server,
...mergedDevServerFileSystemConfig,
};

return config;
}
28 changes: 28 additions & 0 deletions packages/sveltekit/src/vite/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import * as fs from 'fs';
import * as path from 'path';

/**
* Checks if the user has a Sentry init file in the root of their project.
* @returns true if the user has a Sentry init file, false otherwise.
*/
export function hasSentryInitFiles(): boolean {
const hasSentryServerInit = !!getUserConfigFile(process.cwd(), 'server');
const hasSentryClientInit = !!getUserConfigFile(process.cwd(), 'client');
return hasSentryServerInit || hasSentryClientInit;
}

/**
* Looks up the sentry.{@param platform}.config.(ts|js) file
* @returns the file path to the file or undefined if it doesn't exist
*/
export function getUserConfigFile(projectDir: string, platform: 'server' | 'client'): string | undefined {
const possibilities = [`sentry.${platform}.config.ts`, `sentry.${platform}.config.js`];

for (const filename of possibilities) {
if (fs.existsSync(path.resolve(projectDir, filename))) {
return filename;
}
}

return undefined;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { UserConfig, UserConfigExport } from 'vite';

import { getUserConfigFile, injectSentryInitPlugin } from './vitePlugins';
import { injectSentryInitPlugin } from './injectInitPlugin';
import { hasSentryInitFiles } from './utils';

/**
* This function adds Sentry-specific configuration to your Vite config.
Expand Down Expand Up @@ -60,9 +61,3 @@ function addSentryConfig(originalConfig: UserConfig): UserConfig {

return config;
}

function hasSentryInitFiles(): boolean {
const hasSentryServerInit = !!getUserConfigFile(process.cwd(), 'server');
const hasSentryClientInit = !!getUserConfigFile(process.cwd(), 'client');
return hasSentryServerInit || hasSentryClientInit;
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type * as fs from 'fs';
import { vi } from 'vitest';

import { injectSentryInitPlugin } from '../../src/config/vitePlugins';
import { injectSentryInitPlugin } from '../../src/vite/injectInitPlugin';

vi.mock('fs', async () => {
const original = await vi.importActual<typeof fs>('fs');
Expand Down
108 changes: 108 additions & 0 deletions packages/sveltekit/test/vite/sentrySvelteKitPlugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { vi } from 'vitest';

import { sentrySvelteKitPlugin } from './../../src/vite/sentrySvelteKitPlugin';
import * as utils from './../../src/vite/utils';

describe('sentrySvelteKitPlugin', () => {
it('returns a Vite plugin with name, enforce, and config hook', () => {
const plugin = sentrySvelteKitPlugin();
expect(plugin).toHaveProperty('name');
expect(plugin).toHaveProperty('enforce');
expect(plugin).toHaveProperty('config');
expect(plugin.name).toEqual('sentry-sveltekit');
expect(plugin.enforce).toEqual('pre');
});

describe('config hook', () => {
const hasSentryInitFilesSpy = vi.spyOn(utils, 'hasSentryInitFiles').mockReturnValue(true);

beforeEach(() => {
hasSentryInitFilesSpy.mockClear();
});

it('adds the injectInitPlugin and adjusts the dev server config if init config files exist', () => {
const plugin = sentrySvelteKitPlugin();
const originalConfig = {};

// @ts-ignore - plugin.config exists and is callable
const modifiedConfig = plugin.config(originalConfig);

expect(modifiedConfig).toEqual({
plugins: [
{
enforce: 'pre',
name: 'sentry-init-injection-plugin',
transform: expect.any(Function),
},
],
server: {
fs: {
allow: ['.'],
},
},
});
expect(hasSentryInitFilesSpy).toHaveBeenCalledTimes(1);
});

it('merges user-defined options with Sentry-specifc ones', () => {
const plugin = sentrySvelteKitPlugin();
const originalConfig = {
test: {
include: ['src/**/*.{test,spec}.{js,ts}'],
},
build: {
sourcemap: 'css',
},
plugins: [{ name: 'some plugin' }],
server: {
fs: {
allow: ['./build/**/*.{js}'],
},
},
};

// @ts-ignore - plugin.config exists and is callable
const modifiedConfig = plugin.config(originalConfig);

expect(modifiedConfig).toEqual({
test: {
include: ['src/**/*.{test,spec}.{js,ts}'],
},
build: {
sourcemap: 'css',
},
plugins: [
{
enforce: 'pre',
name: 'sentry-init-injection-plugin',
transform: expect.any(Function),
},
{ name: 'some plugin' },
],
server: {
fs: {
allow: ['./build/**/*.{js}', '.'],
},
},
});
expect(hasSentryInitFilesSpy).toHaveBeenCalledTimes(1);
});

it("doesn't add the injectInitPlugin if init config files don't exist", () => {
hasSentryInitFilesSpy.mockReturnValue(false);
const plugin = sentrySvelteKitPlugin();
const originalConfig = {
plugins: [{ name: 'some plugin' }],
};

// @ts-ignore - plugin.config exists and is callable
const modifiedConfig = plugin.config(originalConfig);

expect(modifiedConfig).toEqual({
plugins: [{ name: 'some plugin' }],
server: {},
});
expect(hasSentryInitFilesSpy).toHaveBeenCalledTimes(1);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type fs from 'fs';
import type { Plugin, UserConfig } from 'vite';
import { vi } from 'vitest';

import { withSentryViteConfig } from '../../src/config/withSentryViteConfig';
import { withSentryViteConfig } from '../../src/vite/withSentryViteConfig';

let existsFile = true;
vi.mock('fs', async () => {
Expand Down