UNPKG

@sentry/wizard

Version:

Sentry wizard helping you to configure your project

452 lines 23.2 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.loadSvelteConfig = exports.createOrMergeSvelteKitFiles = void 0; var fs = __importStar(require("fs")); var path = __importStar(require("path")); var url = __importStar(require("url")); var chalk_1 = __importDefault(require("chalk")); // @ts-ignore - clack is ESM and TS complains about that. It works though var prompts_1 = __importDefault(require("@clack/prompts")); // @ts-ignore - magicast is ESM and TS complains about that. It works though var magicast_1 = require("magicast"); // @ts-ignore - magicast is ESM and TS complains about that. It works though var helpers_1 = require("magicast/helpers"); var templates_1 = require("./templates"); var SVELTE_CONFIG_FILE = 'svelte.config.js'; function createOrMergeSvelteKitFiles(dsn, svelteConfig) { return __awaiter(this, void 0, void 0, function () { var _a, clientHooksPath, serverHooksPath, originalClientHooksFile, originalServerHooksFile, viteConfig; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = getHooksConfigDirs(svelteConfig), clientHooksPath = _a.clientHooksPath, serverHooksPath = _a.serverHooksPath; originalClientHooksFile = findHooksFile(clientHooksPath); originalServerHooksFile = findHooksFile(serverHooksPath); viteConfig = findHooksFile(path.resolve(process.cwd(), 'vite.config')); if (!!originalClientHooksFile) return [3 /*break*/, 2]; prompts_1.default.log.info('No client hooks file found, creating a new one.'); return [4 /*yield*/, createNewHooksFile("".concat(clientHooksPath, ".js"), 'client', dsn)]; case 1: _b.sent(); _b.label = 2; case 2: if (!!originalServerHooksFile) return [3 /*break*/, 4]; prompts_1.default.log.info('No server hooks file found, creating a new one.'); return [4 /*yield*/, createNewHooksFile("".concat(serverHooksPath, ".js"), 'server', dsn)]; case 3: _b.sent(); _b.label = 4; case 4: if (!originalClientHooksFile) return [3 /*break*/, 6]; return [4 /*yield*/, mergeHooksFile(originalClientHooksFile, 'client', dsn)]; case 5: _b.sent(); _b.label = 6; case 6: if (!originalServerHooksFile) return [3 /*break*/, 8]; return [4 /*yield*/, mergeHooksFile(originalServerHooksFile, 'server', dsn)]; case 7: _b.sent(); _b.label = 8; case 8: if (!viteConfig) return [3 /*break*/, 10]; return [4 /*yield*/, modifyViteConfig(viteConfig)]; case 9: _b.sent(); _b.label = 10; case 10: return [2 /*return*/]; } }); }); } exports.createOrMergeSvelteKitFiles = createOrMergeSvelteKitFiles; /** * Attempts to read the svelte.config.js file to find the location of the hooks files. * If users specified a custom location, we'll use that. Otherwise, we'll use the default. */ function getHooksConfigDirs(svelteConfig) { var _a, _b, _c, _d, _e, _f; var relativeUserClientHooksPath = (_c = (_b = (_a = svelteConfig === null || svelteConfig === void 0 ? void 0 : svelteConfig.kit) === null || _a === void 0 ? void 0 : _a.files) === null || _b === void 0 ? void 0 : _b.hooks) === null || _c === void 0 ? void 0 : _c.client; var relativeUserServerHooksPath = (_f = (_e = (_d = svelteConfig === null || svelteConfig === void 0 ? void 0 : svelteConfig.kit) === null || _d === void 0 ? void 0 : _d.files) === null || _e === void 0 ? void 0 : _e.hooks) === null || _f === void 0 ? void 0 : _f.server; var userClientHooksPath = relativeUserClientHooksPath && path.resolve(process.cwd(), relativeUserClientHooksPath); var userServerHooksPath = relativeUserServerHooksPath && path.resolve(process.cwd(), relativeUserServerHooksPath); var defaulHooksDir = path.resolve(process.cwd(), 'src'); var defaultClientHooksPath = path.resolve(defaulHooksDir, 'hooks.client'); // file ending missing on purpose var defaultServerHooksPath = path.resolve(defaulHooksDir, 'hooks.server'); // same here return { clientHooksPath: userClientHooksPath || defaultClientHooksPath, serverHooksPath: userServerHooksPath || defaultServerHooksPath, }; } /** * Checks if a hooks file exists and returns the full path to the file with the correct file type. */ function findHooksFile(hooksFile) { var possibleFileTypes = ['.js', '.ts', '.mjs']; return possibleFileTypes .map(function (type) { return "".concat(hooksFile).concat(type); }) .find(function (file) { return fs.existsSync(file); }); } /** * Reads the template, replaces the dsn placeholder with the actual dsn and writes the file to @param hooksFileDest */ function createNewHooksFile(hooksFileDest, hooktype, dsn) { return __awaiter(this, void 0, void 0, function () { var filledTemplate; return __generator(this, function (_a) { switch (_a.label) { case 0: filledTemplate = hooktype === 'client' ? (0, templates_1.getClientHooksTemplate)(dsn) : (0, templates_1.getServerHooksTemplate)(dsn); return [4 /*yield*/, fs.promises.mkdir(path.dirname(hooksFileDest), { recursive: true })]; case 1: _a.sent(); return [4 /*yield*/, fs.promises.writeFile(hooksFileDest, filledTemplate)]; case 2: _a.sent(); prompts_1.default.log.success("Created ".concat(hooksFileDest)); return [2 /*return*/]; } }); }); } /** * Merges the users' hooks file with Sentry-related code. * * Both hooks: * - add import * as Sentry * - add Sentry.init * - add handleError hook wrapper * * Additionally in Server hook: * - add handle hook handler */ function mergeHooksFile(hooksFile, hookType, dsn) { return __awaiter(this, void 0, void 0, function () { var originalHooksMod, modifiedCode; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, (0, magicast_1.loadFile)(hooksFile)]; case 1: originalHooksMod = _a.sent(); if (hasSentryContent(path.basename(hooksFile), originalHooksMod.$code)) { // We don't want to mess with files that already have Sentry content. // Let's just bail out at this point. return [2 /*return*/]; } originalHooksMod.imports.$add({ from: '@sentry/sveltekit', imported: '*', local: 'Sentry', }); if (hookType === 'client') { insertClientInitCall(dsn, originalHooksMod); } else { insertServerInitCall(dsn, originalHooksMod); } wrapHandleError(originalHooksMod); if (hookType === 'server') { wrapHandle(originalHooksMod); } modifiedCode = originalHooksMod.generate().code; return [4 /*yield*/, fs.promises.writeFile(hooksFile, modifiedCode)]; case 2: _a.sent(); prompts_1.default.log.success("Added Sentry code to ".concat(hooksFile)); return [2 /*return*/]; } }); }); } function insertClientInitCall(dsn, // eslint-disable-next-line @typescript-eslint/no-explicit-any originalHooksMod) { var initCallComment = "\n // If you don't want to use Session Replay, remove the `Replay` integration, \n // `replaysSessionSampleRate` and `replaysOnErrorSampleRate` options."; // This assignment of any values is fine because we're just creating a function call in magicast // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment var initCall = magicast_1.builders.functionCall('Sentry.init', { dsn: dsn, tracesSampleRate: 1.0, replaysSessionSampleRate: 0.1, replaysOnErrorSampleRate: 1.0, integrations: [magicast_1.builders.newExpression('Sentry.Replay')], }); // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment var initCallWithComment = magicast_1.builders.raw( // eslint-disable-next-line @typescript-eslint/no-unsafe-argument "".concat(initCallComment, "\n").concat((0, magicast_1.generateCode)(initCall).code)); var originalHooksModAST = originalHooksMod.$ast; var initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST); originalHooksModAST.body.splice(initCallInsertionIndex, 0, // @ts-ignore - string works here because the AST is proxified by magicast // eslint-disable-next-line @typescript-eslint/no-unsafe-argument (0, magicast_1.generateCode)(initCallWithComment).code); } function insertServerInitCall(dsn, // eslint-disable-next-line @typescript-eslint/no-explicit-any originalHooksMod) { // This assignment of any values is fine because we're just creating a function call in magicast // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment var initCall = magicast_1.builders.functionCall('Sentry.init', { dsn: dsn, tracesSampleRate: 1.0, }); var originalHooksModAST = originalHooksMod.$ast; var initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST); originalHooksModAST.body.splice(initCallInsertionIndex, 0, // @ts-ignore - string works here because the AST is proxified by magicast // eslint-disable-next-line @typescript-eslint/no-unsafe-argument (0, magicast_1.generateCode)(initCall).code); } // eslint-disable-next-line @typescript-eslint/no-explicit-any function wrapHandleError(mod) { var modAst = mod.exports.$ast; var namedExports = modAst.body.filter(function (node) { return node.type === 'ExportNamedDeclaration'; }); var foundHandleError = false; namedExports.forEach(function (modExport) { var declaration = modExport.declaration; if (!declaration) { return; } if (declaration.type === 'FunctionDeclaration') { if (!declaration.id || declaration.id.name !== 'handleError') { return; } foundHandleError = true; var userCode = (0, magicast_1.generateCode)(declaration).code; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment mod.exports.handleError = magicast_1.builders.raw("Sentry.handleErrorWithSentry(".concat(userCode.replace('handleError', '_handleError'), ")")); // because magicast doesn't overwrite the original function export, we need to remove it manually modAst.body = modAst.body.filter(function (node) { return node !== modExport; }); } else if (declaration.type === 'VariableDeclaration') { var declarations = declaration.declarations; declarations.forEach(function (declaration) { // @ts-ignore - id should always have a name in this case if (!declaration.id || declaration.id.name !== 'handleError') { return; } foundHandleError = true; var userCode = declaration.init; var stringifiedUserCode = userCode ? (0, magicast_1.generateCode)(userCode).code : ''; // @ts-ignore - we can just place a string here, magicast will convert it to a node declaration.init = "Sentry.handleErrorWithSentry(".concat(stringifiedUserCode, ")"); }); } }); if (!foundHandleError) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment mod.exports.handleError = magicast_1.builders.functionCall('Sentry.handleErrorWithSentry'); } } // eslint-disable-next-line @typescript-eslint/no-explicit-any function wrapHandle(mod) { var modAst = mod.exports.$ast; var namedExports = modAst.body.filter(function (node) { return node.type === 'ExportNamedDeclaration'; }); var foundHandle = false; namedExports.forEach(function (modExport) { var declaration = modExport.declaration; if (!declaration) { return; } if (declaration.type === 'FunctionDeclaration') { if (!declaration.id || declaration.id.name !== 'handle') { return; } foundHandle = true; var userCode = (0, magicast_1.generateCode)(declaration).code; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment mod.exports.handle = magicast_1.builders.raw("sequence(Sentry.sentryHandle(), ".concat(userCode.replace('handle', '_handle'), ")")); // because of an issue with magicast, we need to remove the original export modAst.body = modAst.body.filter(function (node) { return node !== modExport; }); } else if (declaration.type === 'VariableDeclaration') { var declarations = declaration.declarations; declarations.forEach(function (declaration) { // @ts-ignore - id should always have a name in this case if (!declaration.id || declaration.id.name !== 'handle') { return; } var userCode = declaration.init; var stringifiedUserCode = userCode ? (0, magicast_1.generateCode)(userCode).code : ''; // @ts-ignore - we can just place a string here, magicast will convert it to a node declaration.init = "sequence(Sentry.sentryHandle(), ".concat(stringifiedUserCode, ")"); foundHandle = true; }); } }); if (!foundHandle) { // can't use builders.functionCall here because it doesn't yet // support member expressions (Sentry.sentryHandle()) in args // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment mod.exports.handle = magicast_1.builders.raw('sequence(Sentry.sentryHandle())'); } try { mod.imports.$add({ from: '@sveltejs/kit/hooks', imported: 'sequence', local: 'sequence', }); } catch (_) { // It's possible sequence is already imported. in this case, magicast throws but that's fine. } } /** Checks if the Sentry SvelteKit SDK is already mentioned in the file */ function hasSentryContent(fileName, fileContent) { if (fileContent.includes('@sentry/sveltekit')) { prompts_1.default.log.warn("File ".concat(chalk_1.default.cyan(path.basename(fileName)), " already contains Sentry code.\nSkipping adding Sentry functionality to ").concat(chalk_1.default.cyan(path.basename(fileName)), ".")); return true; } return false; } function loadSvelteConfig() { return __awaiter(this, void 0, void 0, function () { var configFilePath, configUrl, svelteConfigModule, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: configFilePath = path.join(process.cwd(), SVELTE_CONFIG_FILE); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); if (!fs.existsSync(configFilePath)) { return [2 /*return*/, {}]; } configUrl = url.pathToFileURL(configFilePath).href; return [4 /*yield*/, import(configUrl)]; case 2: svelteConfigModule = (_a.sent()); return [2 /*return*/, (svelteConfigModule === null || svelteConfigModule === void 0 ? void 0 : svelteConfigModule.default) || {}]; case 3: e_1 = _a.sent(); prompts_1.default.log.error("Couldn't load ".concat(SVELTE_CONFIG_FILE, ".\nPlease make sure, you're running this wizard with Node 16 or newer")); prompts_1.default.log.info(chalk_1.default.dim(typeof e_1 === 'object' && e_1 != null && 'toString' in e_1 ? e_1.toString() : typeof e_1 === 'string' ? e_1 : 'Unknown error')); return [2 /*return*/, {}]; case 4: return [2 /*return*/]; } }); }); } exports.loadSvelteConfig = loadSvelteConfig; function modifyViteConfig(viteConfigPath) { return __awaiter(this, void 0, void 0, function () { var viteConfigContent, viteModule, code; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, fs.promises.readFile(viteConfigPath, 'utf-8')]; case 1: viteConfigContent = (_a.sent()).toString(); if (hasSentryContent(viteConfigPath, viteConfigContent)) { return [2 /*return*/]; } viteModule = (0, magicast_1.parseModule)(viteConfigContent); (0, helpers_1.addVitePlugin)(viteModule, { imported: 'sentrySvelteKit', from: '@sentry/sveltekit', constructor: 'sentrySvelteKit', index: 0, }); code = (0, magicast_1.generateCode)(viteModule.$ast).code; return [4 /*yield*/, fs.promises.writeFile(viteConfigPath, code)]; case 2: _a.sent(); return [2 /*return*/]; } }); }); } /** * We want to insert the init call on top of the file but after all import statements */ function getInitCallInsertionIndex(originalHooksModAST) { // We need to deep-copy here because reverse mutates in place var copiedBodyNodes = __spreadArray([], originalHooksModAST.body, true); var lastImportDeclaration = copiedBodyNodes .reverse() .find(function (node) { return node.type === 'ImportDeclaration'; }); var initCallInsertionIndex = lastImportDeclaration ? originalHooksModAST.body.indexOf(lastImportDeclaration) + 1 : 0; return initCallInsertionIndex; } //# sourceMappingURL=sdk-setup.js.map