@sentry/wizard
Version:
Sentry wizard helping you to configure your project
402 lines • 22.5 kB
JavaScript
"use strict";
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.instrumentSentryOnEntryServer = exports.updateStartScript = exports.initializeSentryOnEntryClient = exports.updateBuildScript = exports.instrumentRootRoute = exports.loadRemixConfig = exports.isRemixV2 = exports.insertServerInstrumentationFile = exports.createServerInstrumentationFile = exports.runRemixReveal = void 0;
var fs = __importStar(require("fs"));
var path = __importStar(require("path"));
var url = __importStar(require("url"));
var childProcess = __importStar(require("child_process"));
// @ts-expect-error - clack is ESM and TS complains about that. It works though
var prompts_1 = __importDefault(require("@clack/prompts"));
var chalk_1 = __importDefault(require("chalk"));
var semver_1 = require("semver");
var magicast_1 = require("magicast");
var package_json_1 = require("../utils/package-json");
var utils_1 = require("./utils");
var root_v1_1 = require("./codemods/root-v1");
var root_v2_1 = require("./codemods/root-v2");
var handle_error_1 = require("./codemods/handle-error");
var clack_utils_1 = require("../utils/clack-utils");
var express_server_1 = require("./codemods/express-server");
var REMIX_CONFIG_FILE = 'remix.config.js';
var REMIX_REVEAL_COMMAND = 'npx remix reveal';
function runRemixReveal(isTS) {
// Check if entry files already exist
var clientEntryFilename = "entry.client.".concat(isTS ? 'tsx' : 'jsx');
var serverEntryFilename = "entry.server.".concat(isTS ? 'tsx' : 'jsx');
var clientEntryPath = path.join(process.cwd(), 'app', clientEntryFilename);
var serverEntryPath = path.join(process.cwd(), 'app', serverEntryFilename);
if (fs.existsSync(clientEntryPath) && fs.existsSync(serverEntryPath)) {
prompts_1.default.log.info("Found entry files ".concat(chalk_1.default.cyan(clientEntryFilename), " and ").concat(chalk_1.default.cyan(serverEntryFilename), "."));
}
else {
prompts_1.default.log.info("Couldn't find entry files in your project. Trying to run ".concat(chalk_1.default.cyan(REMIX_REVEAL_COMMAND), "..."));
prompts_1.default.log.info(childProcess.execSync(REMIX_REVEAL_COMMAND).toString());
}
}
exports.runRemixReveal = runRemixReveal;
function insertClientInitCall(dsn, originalHooksMod) {
var initCall = magicast_1.builders.functionCall('Sentry.init', {
dsn: dsn,
tracesSampleRate: 1.0,
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
integrations: [
magicast_1.builders.functionCall('Sentry.browserTracingIntegration', magicast_1.builders.raw('{ useEffect, useLocation, useMatches }')),
magicast_1.builders.functionCall('Sentry.replayIntegration'),
],
});
var originalHooksModAST = originalHooksMod.$ast;
var initCallInsertionIndex = (0, utils_1.getAfterImportsInsertionIndex)(originalHooksModAST);
originalHooksModAST.body.splice(initCallInsertionIndex, 0,
// @ts-expect-error - 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);
}
function createServerInstrumentationFile(dsn) {
return __awaiter(this, void 0, void 0, function () {
var instrumentationFile, instrumentationFileMod, initCall, instrumentationFileModAST, initCallInsertionIndex;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
instrumentationFile = 'instrumentation.server.mjs';
instrumentationFileMod = (0, magicast_1.parseModule)('');
instrumentationFileMod.imports.$add({
from: '@sentry/remix',
imported: '*',
local: 'Sentry',
});
initCall = magicast_1.builders.functionCall('Sentry.init', {
dsn: dsn,
tracesSampleRate: 1.0,
autoInstrumentRemix: true,
});
instrumentationFileModAST = instrumentationFileMod.$ast;
initCallInsertionIndex = (0, utils_1.getAfterImportsInsertionIndex)(instrumentationFileModAST);
instrumentationFileModAST.body.splice(initCallInsertionIndex, 0,
// @ts-expect-error - 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);
return [4 /*yield*/, (0, magicast_1.writeFile)(instrumentationFileModAST, instrumentationFile)];
case 1:
_a.sent();
return [2 /*return*/, instrumentationFile];
}
});
});
}
exports.createServerInstrumentationFile = createServerInstrumentationFile;
function insertServerInstrumentationFile(dsn) {
return __awaiter(this, void 0, void 0, function () {
var instrumentationFile, expressServerPath, originalExpressServerMod;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, createServerInstrumentationFile(dsn)];
case 1:
instrumentationFile = _a.sent();
return [4 /*yield*/, (0, express_server_1.findCustomExpressServerImplementation)()];
case 2:
expressServerPath = _a.sent();
if (!expressServerPath) {
return [2 /*return*/, false];
}
return [4 /*yield*/, (0, magicast_1.loadFile)(expressServerPath)];
case 3:
originalExpressServerMod = _a.sent();
if ((0, utils_1.serverHasInstrumentationImport)(expressServerPath, originalExpressServerMod.$code)) {
prompts_1.default.log.warn("File ".concat(chalk_1.default.cyan(path.basename(expressServerPath)), " already contains instrumentation import.\nSkipping adding instrumentation functionality to ").concat(chalk_1.default.cyan(path.basename(expressServerPath)), "."));
return [2 /*return*/, true];
}
originalExpressServerMod.$code = "import './".concat(instrumentationFile, "';\n").concat(originalExpressServerMod.$code);
fs.writeFileSync(expressServerPath, originalExpressServerMod.$code);
return [2 /*return*/, true];
}
});
});
}
exports.insertServerInstrumentationFile = insertServerInstrumentationFile;
function isRemixV2(remixConfig, packageJson) {
var _a;
var remixVersion = (0, package_json_1.getPackageVersion)('@remix-run/react', packageJson);
if (!remixVersion) {
return false;
}
var minVer = (0, semver_1.minVersion)(remixVersion);
if (!minVer) {
return false;
}
var isV2Remix = (0, semver_1.gte)(minVer, '2.0.0');
return isV2Remix || ((_a = remixConfig === null || remixConfig === void 0 ? void 0 : remixConfig.future) === null || _a === void 0 ? void 0 : _a.v2_errorBoundary) || false;
}
exports.isRemixV2 = isRemixV2;
function loadRemixConfig() {
return __awaiter(this, void 0, void 0, function () {
var configFilePath, configUrl, remixConfigModule, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
configFilePath = path.join(process.cwd(), REMIX_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:
remixConfigModule = (_a.sent());
return [2 /*return*/, (remixConfigModule === null || remixConfigModule === void 0 ? void 0 : remixConfigModule.default) || {}];
case 3:
e_1 = _a.sent();
prompts_1.default.log.error("Couldn't load ".concat(REMIX_CONFIG_FILE, "."));
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.loadRemixConfig = loadRemixConfig;
function instrumentRootRoute(isV2, isTS) {
return __awaiter(this, void 0, void 0, function () {
var rootFilename;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
rootFilename = "root.".concat(isTS ? 'tsx' : 'jsx');
if (!isV2) return [3 /*break*/, 2];
return [4 /*yield*/, (0, root_v2_1.instrumentRootRouteV2)(rootFilename)];
case 1:
_a.sent();
return [3 /*break*/, 4];
case 2: return [4 /*yield*/, (0, root_v1_1.instrumentRootRouteV1)(rootFilename)];
case 3:
_a.sent();
_a.label = 4;
case 4:
prompts_1.default.log.success("Successfully instrumented root route ".concat(chalk_1.default.cyan(rootFilename), "."));
return [2 /*return*/];
}
});
});
}
exports.instrumentRootRoute = instrumentRootRoute;
function updateBuildScript(args) {
return __awaiter(this, void 0, void 0, function () {
var packageJson, buildCommand, instrumentedBuildCommand;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, (0, clack_utils_1.getPackageDotJson)()];
case 1:
packageJson = _a.sent();
if (!packageJson.scripts) {
packageJson.scripts = {};
}
buildCommand = args.isHydrogen
? 'shopify hydrogen build'
: 'remix build';
instrumentedBuildCommand = "".concat(buildCommand, " --sourcemap && sentry-upload-sourcemaps --org ").concat(args.org, " --project ").concat(args.project) +
(args.url ? " --url ".concat(args.url) : '') +
(args.isHydrogen ? ' --buildPath ./dist' : '');
if (!packageJson.scripts.build) {
packageJson.scripts.build = instrumentedBuildCommand;
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
}
else if (packageJson.scripts.build.includes(buildCommand)) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
packageJson.scripts.build = packageJson.scripts.build.replace(buildCommand, instrumentedBuildCommand);
}
else {
throw new Error("`build` script doesn't contain a known build command. Please update it manually.");
}
return [4 /*yield*/, fs.promises.writeFile(path.join(process.cwd(), 'package.json'), JSON.stringify(packageJson, null, 2))];
case 2:
_a.sent();
prompts_1.default.log.success("Successfully updated ".concat(chalk_1.default.cyan('build'), " script in ").concat(chalk_1.default.cyan('package.json'), " to generate and upload sourcemaps."));
return [2 /*return*/];
}
});
});
}
exports.updateBuildScript = updateBuildScript;
function initializeSentryOnEntryClient(dsn, isTS) {
return __awaiter(this, void 0, void 0, function () {
var clientEntryFilename, originalEntryClient, originalEntryClientMod;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
clientEntryFilename = "entry.client.".concat(isTS ? 'tsx' : 'jsx');
originalEntryClient = path.join(process.cwd(), 'app', clientEntryFilename);
return [4 /*yield*/, (0, magicast_1.loadFile)(originalEntryClient)];
case 1:
originalEntryClientMod = _a.sent();
if ((0, utils_1.hasSentryContent)(originalEntryClient, originalEntryClientMod.$code)) {
return [2 /*return*/];
}
originalEntryClientMod.imports.$add({
from: '@sentry/remix',
imported: '*',
local: 'Sentry',
});
originalEntryClientMod.imports.$add({
from: 'react',
imported: 'useEffect',
local: 'useEffect',
});
originalEntryClientMod.imports.$add({
from: '@remix-run/react',
imported: 'useLocation',
local: 'useLocation',
});
originalEntryClientMod.imports.$add({
from: '@remix-run/react',
imported: 'useMatches',
local: 'useMatches',
});
insertClientInitCall(dsn, originalEntryClientMod);
return [4 /*yield*/, (0, magicast_1.writeFile)(originalEntryClientMod.$ast, path.join(process.cwd(), 'app', clientEntryFilename))];
case 2:
_a.sent();
prompts_1.default.log.success("Successfully initialized Sentry on client entry point ".concat(chalk_1.default.cyan(clientEntryFilename)));
return [2 /*return*/];
}
});
});
}
exports.initializeSentryOnEntryClient = initializeSentryOnEntryClient;
function updateStartScript(instrumentationFile) {
return __awaiter(this, void 0, void 0, function () {
var packageJson, startCommand;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, (0, clack_utils_1.getPackageDotJson)()];
case 1:
packageJson = _a.sent();
if (!packageJson.scripts || !packageJson.scripts.start) {
throw new Error("Couldn't find a `start` script in your package.json. Please add one manually.");
}
if (packageJson.scripts.start.includes('NODE_OPTIONS')) {
prompts_1.default.log.warn("Found existing NODE_OPTIONS in ".concat(chalk_1.default.cyan('start'), " script. Skipping adding Sentry initialization."));
return [2 /*return*/];
}
if (!packageJson.scripts.start.includes('remix-serve') &&
// Adding a following empty space not to match a path that includes `node`
!packageJson.scripts.start.includes('node ')) {
prompts_1.default.log.warn("Found a ".concat(chalk_1.default.cyan('start'), " script that doesn't use ").concat(chalk_1.default.cyan('remix-serve'), " or ").concat(chalk_1.default.cyan('node'), ". Skipping adding Sentry initialization."));
return [2 /*return*/];
}
startCommand = packageJson.scripts.start;
packageJson.scripts.start = "NODE_OPTIONS='--import ./".concat(instrumentationFile, "' ").concat(startCommand);
return [4 /*yield*/, fs.promises.writeFile(path.join(process.cwd(), 'package.json'), JSON.stringify(packageJson, null, 2))];
case 2:
_a.sent();
prompts_1.default.log.success("Successfully updated ".concat(chalk_1.default.cyan('start'), " script in ").concat(chalk_1.default.cyan('package.json'), " to include Sentry initialization on start."));
return [2 /*return*/];
}
});
});
}
exports.updateStartScript = updateStartScript;
function instrumentSentryOnEntryServer(isV2, isTS) {
return __awaiter(this, void 0, void 0, function () {
var serverEntryFilename, originalEntryServer, originalEntryServerMod, handleErrorInstrumented;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
serverEntryFilename = "entry.server.".concat(isTS ? 'tsx' : 'jsx');
originalEntryServer = path.join(process.cwd(), 'app', serverEntryFilename);
return [4 /*yield*/, (0, magicast_1.loadFile)(originalEntryServer)];
case 1:
originalEntryServerMod = _a.sent();
if ((0, utils_1.hasSentryContent)(originalEntryServer, originalEntryServerMod.$code)) {
return [2 /*return*/];
}
originalEntryServerMod.imports.$add({
from: '@sentry/remix',
imported: '*',
local: 'Sentry',
});
if (isV2) {
handleErrorInstrumented = (0, handle_error_1.instrumentHandleError)(originalEntryServerMod, serverEntryFilename);
if (handleErrorInstrumented) {
prompts_1.default.log.success("Instrumented ".concat(chalk_1.default.cyan('handleError'), " in ").concat(chalk_1.default.cyan("".concat(serverEntryFilename))));
}
}
return [4 /*yield*/, (0, magicast_1.writeFile)(originalEntryServerMod.$ast, path.join(process.cwd(), 'app', serverEntryFilename))];
case 2:
_a.sent();
prompts_1.default.log.success("Successfully initialized Sentry on server entry point ".concat(chalk_1.default.cyan(serverEntryFilename), "."));
return [2 /*return*/];
}
});
});
}
exports.instrumentSentryOnEntryServer = instrumentSentryOnEntryServer;
//# sourceMappingURL=sdk-setup.js.map