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(sveltekit): Auto-detect SvelteKit adapters #8193

Merged
merged 3 commits into from May 30, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
65 changes: 65 additions & 0 deletions packages/sveltekit/src/vite/detectAdapter.ts
@@ -0,0 +1,65 @@
import type { Package } from '@sentry/types';
import * as fs from 'fs';
import * as path from 'path';

/**
* Supported @sveltejs/adapters-[adapter] SvelteKit adapters
*/
export type SupportedSvelteKitAdapters = 'node' | 'auto' | 'vercel' | 'other';
Copy link
Member Author

Choose a reason for hiding this comment

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

adapter-auto and adapter-vercel can both be used to deploy to Vercel. Hence we permit both of them.


/**
* Tries to detect the used adapter for SvelteKit by looking at the dependencies.
* returns the name of the adapter or 'other' if no supported adapter was found.
*/
export async function detectAdapter(debug?: boolean): Promise<SupportedSvelteKitAdapters> {
const pkgJson = await loadPackageJson();

const allDependencies = [...Object.keys(pkgJson.dependencies || {}), ...Object.keys(pkgJson.devDependencies || {})];

let adapter: SupportedSvelteKitAdapters = 'other';
if (allDependencies.find(dep => dep === '@sveltejs/adapter-vercel')) {
adapter = 'vercel';
} else if (allDependencies.find(dep => dep === '@sveltejs/adapter-node')) {
adapter = 'node';
} else if (allDependencies.find(dep => dep === '@sveltejs/adapter-auto')) {
adapter = 'auto';
}

if (debug) {
if (adapter === 'other') {
// eslint-disable-next-line no-console
console.warn(
"[Sentry SvelteKit Plugin] Couldn't detect SvelteKit adapter. Please set the 'adapter' option manually.",
);
} else {
// eslint-disable-next-line no-console
console.log(`[Sentry SvelteKit Plugin] Detected SvelteKit ${adapter} adapter`);
}
}

return adapter;
}

/**
* Imports the pacakge.json file and returns the parsed JSON object.
*/
async function loadPackageJson(): Promise<Partial<Package>> {
const pkgFile = path.join(process.cwd(), 'package.json');

try {
if (!fs.existsSync(pkgFile)) {
throw `File ${pkgFile} doesn't exist}`;
Lms24 marked this conversation as resolved.
Show resolved Hide resolved
}

const pkgJsonContent = (await fs.promises.readFile(pkgFile, 'utf-8')).toString();

return JSON.parse(pkgJsonContent);
} catch (e) {
// eslint-disable-next-line no-console
console.warn("[Sentry SvelteKit Plugin] Couldn't load package.json:");
// eslint-disable-next-line no-console
console.log(e);
Lms24 marked this conversation as resolved.
Show resolved Hide resolved

return {};
}
}
21 changes: 21 additions & 0 deletions packages/sveltekit/src/vite/sentryVitePlugins.ts
Expand Up @@ -3,6 +3,8 @@ import type { Plugin } from 'vite';

import type { AutoInstrumentSelection } from './autoInstrument';
import { makeAutoInstrumentationPlugin } from './autoInstrument';
import type { SupportedSvelteKitAdapters } from './detectAdapter';
import { detectAdapter } from './detectAdapter';
import { makeCustomSentryVitePlugin } from './sourceMaps';

type SourceMapsUploadOptions = {
Expand Down Expand Up @@ -39,6 +41,24 @@ export type SentrySvelteKitPluginOptions = {
* @default false.
*/
debug?: boolean;

/**
* Specify which SvelteKit adapter you're using.
* By default, the SDK will attempt auto-detect the used adapter at build time and apply the
* correct config for source maps upload or auto-instrumentation.
*
* Currently, the SDK supports the following adapters:
* - node (@sveltejs/adapter-node)
* - auto (@sveltejs/adapter-auto) only Vercel
* - vercel (@sveltejs/adapter-auto) only Serverless functions, no edge runtime
*
* Set this option, if the SDK detects the wrong adapter or you want to use an adapter
* that is not in this list. If you specify 'other', you'll most likely need to configure
* source maps upload yourself.
*
* @default {} the SDK attempts to auto-detect the used adapter at build time
*/
adapter?: SupportedSvelteKitAdapters;
} & SourceMapsUploadOptions &
AutoInstrumentOptions;

Expand All @@ -59,6 +79,7 @@ export async function sentrySvelteKit(options: SentrySvelteKitPluginOptions = {}
const mergedOptions = {
...DEFAULT_PLUGIN_OPTIONS,
...options,
adapter: options.adapter || (await detectAdapter(options.debug || false)),
};

const sentryPlugins: Plugin[] = [];
Expand Down
76 changes: 76 additions & 0 deletions packages/sveltekit/test/vite/detectAdapter.test.ts
@@ -0,0 +1,76 @@
import { vi } from 'vitest';

import { detectAdapter } from '../../src/vite/detectAdapter';

let existsFile = true;
const pkgJson = {
dependencies: {},
};
describe('detectAdapter', () => {
beforeEach(() => {
existsFile = true;
vi.clearAllMocks();
pkgJson.dependencies = {};
});

vi.mock('fs', () => {
return {
existsSync: () => existsFile,
promises: {
readFile: () => {
return Promise.resolve(JSON.stringify(pkgJson));
},
},
};
});

const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});

it.each(['auto', 'vercel', 'node'])(
'returns the adapter name (adapter %s) and logs it to the console',
async adapter => {
pkgJson.dependencies[`@sveltejs/adapter-${adapter}`] = '1.0.0';
const detectedAdapter = await detectAdapter(true);
expect(detectedAdapter).toEqual(adapter);
expect(consoleLogSpy).toHaveBeenCalledTimes(1);
expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining(`Detected SvelteKit ${adapter} adapter`));
},
);

it('returns "other" if no supported adapter was found', async () => {
pkgJson.dependencies['@sveltejs/adapter-netlify'] = '1.0.0';
const detectedAdapter = await detectAdapter();
expect(detectedAdapter).toEqual('other');
});

it('logs a warning if in debug mode and no supported adapter was found', async () => {
pkgJson.dependencies['@sveltejs/adapter-netlify'] = '1.0.0';
const detectedAdapter = await detectAdapter(true);
expect(detectedAdapter).toEqual('other');
expect(consoleWarnSpy).toHaveBeenCalledTimes(1);
expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining("Couldn't detect SvelteKit adapter"));
});

it('returns "other" if package.json isnt available and emits a warning log', async () => {
existsFile = false;
const detectedAdapter = await detectAdapter();
expect(detectedAdapter).toEqual('other');

expect(consoleWarnSpy).toHaveBeenCalledTimes(1);
expect(consoleLogSpy).toHaveBeenCalledTimes(1);
});

it('prefers all other adapters over adapter auto', async () => {
pkgJson.dependencies['@sveltejs/adapter-auto'] = '1.0.0';
pkgJson.dependencies['@sveltejs/adapter-vercel'] = '1.0.0';
pkgJson.dependencies['@sveltejs/adapter-node'] = '1.0.0';

const detectedAdapter = await detectAdapter();
expect(detectedAdapter).toEqual('vercel');

delete pkgJson.dependencies['@sveltejs/adapter-vercel'];
const detectedAdapter2 = await detectAdapter();
expect(detectedAdapter2).toEqual('node');
});
});
7 changes: 7 additions & 0 deletions packages/sveltekit/test/vite/sentrySvelteKitPlugins.test.ts
Expand Up @@ -17,6 +17,13 @@ vi.mock('fs', async () => {
};
});

vi.spyOn(console, 'log').mockImplementation(() => {
/* noop */
});
vi.spyOn(console, 'warn').mockImplementation(() => {
/* noop */
});

describe('sentryVite()', () => {
it('returns an array of Vite plugins', async () => {
const plugins = await sentrySvelteKit();
Expand Down
2 changes: 2 additions & 0 deletions packages/types/src/package.ts
Expand Up @@ -2,4 +2,6 @@
export interface Package {
Lms24 marked this conversation as resolved.
Show resolved Hide resolved
name: string;
version: string;
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
}