123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741 |
- import fs from 'fs';
- import path from 'path';
- import CompressionPlugin from 'compression-webpack-plugin';
- import CopyPlugin from 'copy-webpack-plugin';
- import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
- import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
- import MiniCssExtractPlugin from 'mini-css-extract-plugin';
- import webpack from 'webpack';
- import {Configuration as DevServerConfig} from 'webpack-dev-server';
- import FixStyleOnlyEntriesPlugin from 'webpack-remove-empty-scripts';
- import IntegrationDocsFetchPlugin from './build-utils/integration-docs-fetch-plugin';
- import LastBuiltPlugin from './build-utils/last-built-plugin';
- import SentryInstrumentation from './build-utils/sentry-instrumentation';
- import {extractIOSDeviceNames} from './scripts/extract-ios-device-names';
- import babelConfig from './babel.config';
- (async () => {
- await extractIOSDeviceNames();
- })();
- interface Configuration extends webpack.Configuration {
- devServer?: DevServerConfig;
- }
- const {env} = process;
- env.NODE_ENV = env.NODE_ENV ?? 'development';
- const IS_PRODUCTION = env.NODE_ENV === 'production';
- const IS_TEST = env.NODE_ENV === 'test' || !!env.TEST_SUITE;
- const IS_CI = !!env.CI;
- const IS_ACCEPTANCE_TEST = !!env.IS_ACCEPTANCE_TEST;
- const IS_DEPLOY_PREVIEW = !!env.NOW_GITHUB_DEPLOYMENT;
- const IS_UI_DEV_ONLY = !!env.SENTRY_UI_DEV_ONLY;
- const DEV_MODE = !(IS_PRODUCTION || IS_CI);
- const WEBPACK_MODE: Configuration['mode'] = IS_PRODUCTION ? 'production' : 'development';
- const CONTROL_SILO_PORT = env.SENTRY_CONTROL_SILO_PORT;
- const SENTRY_BACKEND_PORT = env.SENTRY_BACKEND_PORT;
- const SENTRY_WEBPACK_PROXY_HOST = env.SENTRY_WEBPACK_PROXY_HOST;
- const SENTRY_WEBPACK_PROXY_PORT = env.SENTRY_WEBPACK_PROXY_PORT;
- const SENTRY_RELEASE_VERSION = env.SENTRY_RELEASE_VERSION;
- const FORCE_WEBPACK_DEV_SERVER = !!env.FORCE_WEBPACK_DEV_SERVER;
- const HAS_WEBPACK_DEV_SERVER_CONFIG =
- !!SENTRY_BACKEND_PORT && !!SENTRY_WEBPACK_PROXY_PORT;
- const NO_DEV_SERVER = !!env.NO_DEV_SERVER;
- const SHOULD_FORK_TS = DEV_MODE && !env.NO_TS_FORK;
- const SHOULD_HOT_MODULE_RELOAD = DEV_MODE && !!env.SENTRY_UI_HOT_RELOAD;
- const SHOULD_LAZY_LOAD = DEV_MODE && !!env.SENTRY_UI_LAZY_LOAD;
- const DEPLOY_PREVIEW_CONFIG = IS_DEPLOY_PREVIEW && {
- branch: env.NOW_GITHUB_COMMIT_REF,
- commitSha: env.NOW_GITHUB_COMMIT_SHA,
- githubOrg: env.NOW_GITHUB_COMMIT_ORG,
- githubRepo: env.NOW_GITHUB_COMMIT_REPO,
- };
- const SENTRY_EXPERIMENTAL_SPA =
- !DEPLOY_PREVIEW_CONFIG && !IS_UI_DEV_ONLY ? !!env.SENTRY_EXPERIMENTAL_SPA : true;
- const SENTRY_SPA_DSN = SENTRY_EXPERIMENTAL_SPA ? env.SENTRY_SPA_DSN : undefined;
- const sentryDjangoAppPath = path.join(__dirname, 'src/sentry/static/sentry');
- const distPath = env.SENTRY_STATIC_DIST_PATH || path.join(sentryDjangoAppPath, 'dist');
- const staticPrefix = path.join(__dirname, 'static');
- if (env.SENTRY_EXTRACT_TRANSLATIONS === '1') {
- babelConfig.plugins?.push([
- 'module:babel-gettext-extractor',
- {
- fileName: 'build/javascript.po',
- baseDirectory: path.join(__dirname),
- functionNames: {
- gettext: ['msgid'],
- ngettext: ['msgid', 'msgid_plural', 'count'],
- gettextComponentTemplate: ['msgid'],
- t: ['msgid'],
- tn: ['msgid', 'msgid_plural', 'count'],
- tct: ['msgid'],
- },
- },
- ]);
- }
- const localeCatalogPath = path.join(
- __dirname,
- 'src',
- 'sentry',
- 'locale',
- 'catalogs.json'
- );
- type LocaleCatalog = {
- supported_locales: string[];
- };
- const localeCatalog: LocaleCatalog = JSON.parse(
- fs.readFileSync(localeCatalogPath, 'utf8')
- );
- const localeToLanguage = (locale: string) => locale.toLowerCase().replace('_', '-');
- const supportedLocales = localeCatalog.supported_locales;
- const supportedLanguages = supportedLocales.map(localeToLanguage);
- type CacheGroups = Exclude<
- NonNullable<Configuration['optimization']>['splitChunks'],
- false | undefined
- >['cacheGroups'];
- type CacheGroupTest = (
- module: webpack.Module,
- context: Parameters<webpack.optimize.SplitChunksPlugin['options']['getCacheGroups']>[1]
- ) => boolean;
- // A mapping of chunk groups used for locale code splitting
- const localeChunkGroups: CacheGroups = {};
- supportedLocales
-
-
- .filter(l => l !== 'en')
- .forEach(locale => {
- const language = localeToLanguage(locale);
- const group = `locale/${language}`;
-
- const localeGroupTests = [
- new RegExp(`locale\\/${locale}\\/.*\\.po$`),
- new RegExp(`moment\\/locale\\/${language}\\.js$`),
- ];
-
-
-
-
- const groupTest: CacheGroupTest = (module, {chunkGraph}) =>
- localeGroupTests.some(pattern =>
- pattern.test(module?.nameForCondition?.() ?? '')
- ? true
- : chunkGraph.getModuleChunks(module).some(c => c.name && pattern.test(c.name))
- );
- // We are defining a chunk that combines the django language files with
- // moment's locales as if you want one, you will want the other.
- //
- // In the application code you will still need to import via their module
- // paths and not the chunk name
- localeChunkGroups[group] = {
- chunks: 'async',
- name: group,
- test: groupTest,
- enforce: true,
- };
- });
- const babelOptions = {...babelConfig, cacheDirectory: true};
- const babelLoaderConfig = {
- loader: 'babel-loader',
- options: babelOptions,
- };
- const appConfig: Configuration = {
- mode: WEBPACK_MODE,
- entry: {
-
- app: ['sentry/utils/statics-setup', 'sentry'],
-
- pipeline: ['sentry/utils/statics-setup', 'sentry/views/integrationPipeline'],
-
- sentry: 'less/sentry.less',
- },
- context: staticPrefix,
- module: {
-
- rules: [
- {
- test: /\.[tj]sx?$/,
- include: [staticPrefix],
- exclude: /(vendor|node_modules|dist)/,
- use: babelLoaderConfig,
- },
- {
- test: /\.po$/,
- use: {
- loader: 'po-catalog-loader',
- options: {
- referenceExtensions: ['.js', '.jsx', '.tsx'],
- domain: 'sentry',
- },
- },
- },
- {
- test: /\.pegjs/,
- use: {loader: 'pegjs-loader'},
- },
- {
- test: /\.css/,
- use: ['style-loader', 'css-loader'],
- },
- {
- test: /\.less$/,
- include: [staticPrefix],
- use: [
- {
- loader: MiniCssExtractPlugin.loader,
- options: {
- publicPath: 'auto',
- },
- },
- 'css-loader',
- 'less-loader',
- ],
- },
- {
- test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg|mp4)($|\?)/,
- type: 'asset',
- },
- ],
- noParse: [
-
- /jed\/jed\.js/,
- /marked\/lib\/marked\.js/,
- /terser\/dist\/bundle\.min\.js/,
- ],
- },
- plugins: [
-
- new SentryInstrumentation(),
-
-
- new webpack.IgnorePlugin({
- contextRegExp: /moment$/,
- resourceRegExp: /^\.\/locale$/,
- }),
-
- new webpack.ProvidePlugin({
- process: 'process/browser',
- Buffer: ['buffer', 'Buffer'],
- }),
-
- new MiniCssExtractPlugin({
-
-
- filename: 'entrypoints/[name].css',
- }),
-
- new webpack.DefinePlugin({
- 'process.env': {
- NODE_ENV: JSON.stringify(env.NODE_ENV),
- IS_ACCEPTANCE_TEST: JSON.stringify(IS_ACCEPTANCE_TEST),
- DEPLOY_PREVIEW_CONFIG: JSON.stringify(DEPLOY_PREVIEW_CONFIG),
- EXPERIMENTAL_SPA: JSON.stringify(SENTRY_EXPERIMENTAL_SPA),
- SPA_DSN: JSON.stringify(SENTRY_SPA_DSN),
- SENTRY_RELEASE_VERSION: JSON.stringify(SENTRY_RELEASE_VERSION),
- },
- }),
-
- new FixStyleOnlyEntriesPlugin({verbose: false}),
- ...(SHOULD_FORK_TS
- ? [
- new ForkTsCheckerWebpackPlugin({
- typescript: {
- configFile: path.resolve(__dirname, './config/tsconfig.build.json'),
- configOverwrite: {
- compilerOptions: {incremental: true},
- },
- memoryLimit: 3072,
- },
- devServer: false,
- }),
- ]
- : []),
-
- new webpack.ContextReplacementPlugin(
- /sentry-locale$/,
- path.join(__dirname, 'src', 'sentry', 'locale', path.sep),
- true,
- new RegExp(`(${supportedLocales.join('|')})/.*\\.po$`)
- ),
- new webpack.ContextReplacementPlugin(
- /moment\/locale/,
- new RegExp(`(${supportedLanguages.join('|')})\\.js$`)
- ),
-
- new CopyPlugin({
- patterns: [
- {
- from: path.join(staticPrefix, 'images/logo-sentry.svg'),
- to: 'entrypoints/logo-sentry.svg',
- toType: 'file',
- },
-
-
- ...(IS_DEPLOY_PREVIEW
- ? [
- {
- from: path.join(staticPrefix, 'robots-dev.txt'),
- to: 'robots.txt',
- toType: 'file' as const,
- },
- ]
- : []),
- ],
- }),
- ],
- resolve: {
- alias: {
- 'react-dom$': 'react-dom/profiling',
- 'scheduler/tracing': 'scheduler/tracing-profiling',
- sentry: path.join(staticPrefix, 'app'),
- 'sentry-images': path.join(staticPrefix, 'images'),
- 'sentry-logos': path.join(sentryDjangoAppPath, 'images', 'logos'),
- 'sentry-fonts': path.join(staticPrefix, 'fonts'),
-
-
- less: path.join(staticPrefix, 'less'),
- 'sentry-test': path.join(__dirname, 'tests', 'js', 'sentry-test'),
- 'sentry-locale': path.join(__dirname, 'src', 'sentry', 'locale'),
- 'ios-device-list': path.join(
- __dirname,
- 'node_modules',
- 'ios-device-list',
- 'dist',
- 'ios-device-list.min.js'
- ),
- },
- fallback: {
- vm: false,
- stream: false,
- crypto: require.resolve('crypto-browserify'),
-
- string_decoder: false,
- },
- modules: ['node_modules'],
- extensions: ['.jsx', '.js', '.json', '.ts', '.tsx', '.less'],
- },
- output: {
- clean: true,
- path: distPath,
- publicPath: '',
- filename: 'entrypoints/[name].js',
- chunkFilename: 'chunks/[name].[contenthash].js',
- sourceMapFilename: 'sourcemaps/[name].[contenthash].js.map',
- assetModuleFilename: 'assets/[name].[contenthash][ext]',
- },
- optimization: {
- chunkIds: 'named',
- moduleIds: 'named',
- splitChunks: {
-
-
-
- chunks: 'async',
- maxInitialRequests: 10,
- maxAsyncRequests: 10,
- cacheGroups: {
- ...localeChunkGroups,
- },
- },
-
-
- minimizer: ['...', new CssMinimizerPlugin()],
- },
- devtool: IS_PRODUCTION ? 'source-map' : 'eval-cheap-module-source-map',
- };
- if (IS_TEST || IS_ACCEPTANCE_TEST) {
- appConfig.resolve!.alias!['integration-docs-platforms'] = path.join(
- __dirname,
- 'fixtures/integration-docs/_platforms.json'
- );
- } else {
- const plugin = new IntegrationDocsFetchPlugin({basePath: __dirname});
- appConfig.plugins?.push(plugin);
- appConfig.resolve!.alias!['integration-docs-platforms'] = plugin.modulePath;
- }
- if (IS_ACCEPTANCE_TEST) {
- appConfig.plugins?.push(new LastBuiltPlugin({basePath: __dirname}));
- }
- if (
- FORCE_WEBPACK_DEV_SERVER ||
- (HAS_WEBPACK_DEV_SERVER_CONFIG && !NO_DEV_SERVER) ||
- IS_UI_DEV_ONLY
- ) {
- if (SHOULD_HOT_MODULE_RELOAD) {
-
-
-
- const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
- appConfig.plugins?.push(new ReactRefreshWebpackPlugin());
-
- if (IS_UI_DEV_ONLY) {
- appConfig.output = {};
- }
- if (SHOULD_LAZY_LOAD) {
- appConfig.experiments = {
- lazyCompilation: {
-
- imports: true,
-
- entries: false,
- },
- };
- }
- }
- appConfig.devServer = {
- headers: {
- 'Access-Control-Allow-Origin': '*',
- 'Access-Control-Allow-Credentials': 'true',
- 'Document-Policy': 'js-profiling',
- },
-
- allowedHosts: [
- '.sentry.dev',
- '.dev.getsentry.net',
- '.localhost',
- '127.0.0.1',
- '.docker.internal',
- ],
- static: {
- directory: './src/sentry/static/sentry',
- watch: true,
- },
- host: SENTRY_WEBPACK_PROXY_HOST,
-
- hot: 'only',
- port: Number(SENTRY_WEBPACK_PROXY_PORT),
- devMiddleware: {
- stats: 'errors-only',
- },
- client: {
- overlay: false,
- },
- };
- if (!IS_UI_DEV_ONLY) {
-
- const backendAddress = `http://127.0.0.1:${SENTRY_BACKEND_PORT}/`;
- const relayAddress = 'http://127.0.0.1:7899';
-
-
- let controlSiloProxy = {};
- if (CONTROL_SILO_PORT) {
-
-
-
-
- const controlSiloAddress = `http://127.0.0.1:${CONTROL_SILO_PORT}`;
- controlSiloProxy = {
- '/api/0/users/**': controlSiloAddress,
- '/api/0/sentry-apps/**': controlSiloAddress,
- '/api/0/organizations/*/audit-logs/**': controlSiloAddress,
- '/api/0/organizations/*/broadcasts/**': controlSiloAddress,
- '/api/0/organizations/*/integrations/**': controlSiloAddress,
- '/api/0/organizations/*/config/integrations/**': controlSiloAddress,
- '/api/0/organizations/*/sentry-apps/**': controlSiloAddress,
- '/api/0/organizations/*/sentry-app-installations/**': controlSiloAddress,
- '/api/0/api-authorizations/**': controlSiloAddress,
- '/api/0/api-applications/**': controlSiloAddress,
- '/api/0/doc-integrations/**': controlSiloAddress,
- '/api/0/assistant/**': controlSiloAddress,
- };
- }
- appConfig.devServer = {
- ...appConfig.devServer,
- static: {
- ...(appConfig.devServer.static as object),
- publicPath: '/_static/dist/sentry',
- },
-
- proxy: {
- ...controlSiloProxy,
- '/api/store/**': relayAddress,
- '/api/{1..9}*({0..9})/**': relayAddress,
- '/api/0/relays/outcomes/': relayAddress,
- '!/_static/dist/sentry/**': backendAddress,
- },
- };
- appConfig.output!.publicPath = '/_static/dist/sentry/';
- }
- }
- if (IS_UI_DEV_ONLY) {
-
-
-
- const KNOWN_DOMAINS =
- /(?:\.?)((?:localhost|dev\.getsentry\.net|sentry\.dev)(?:\:\d*)?)$/;
- const extractSlug = (hostname: string) => {
- const match = hostname.match(KNOWN_DOMAINS);
- if (!match) {
- return null;
- }
- const [
- matchedExpression,
- ] = match;
- const [slug] = hostname.replace(matchedExpression, '').split('.');
- return slug;
- };
-
- const certPath = path.join(__dirname, 'config');
- const httpsOptions = !fs.existsSync(path.join(certPath, 'localhost.pem'))
- ? {}
- : {
- key: fs.readFileSync(path.join(certPath, 'localhost-key.pem')),
- cert: fs.readFileSync(path.join(certPath, 'localhost.pem')),
- };
- appConfig.devServer = {
- ...appConfig.devServer,
- compress: true,
- server: {
- type: 'https',
- options: httpsOptions,
- },
- headers: {
- 'Document-Policy': 'js-profiling',
- },
- static: {
- publicPath: '/_assets/',
- },
- proxy: [
- {
- context: ['/api/', '/avatar/', '/organization-avatar/', '/extensions/'],
- target: 'https://sentry.io',
- secure: false,
- changeOrigin: true,
- headers: {
- Referer: 'https://sentry.io/',
- 'Document-Policy': 'js-profiling',
- },
- cookieDomainRewrite: {'.sentry.io': 'localhost'},
- router: ({hostname}) => {
- const orgSlug = extractSlug(hostname);
- return orgSlug ? `https://${orgSlug}.sentry.io` : 'https://sentry.io';
- },
- },
- ],
- historyApiFallback: {
- rewrites: [{from: /^\/.*$/, to: '/_assets/index.html'}],
- },
- };
- appConfig.optimization = {
- runtimeChunk: 'single',
- };
- }
- if (IS_UI_DEV_ONLY || SENTRY_EXPERIMENTAL_SPA) {
- appConfig.output!.publicPath = '/_assets/';
-
- const HtmlWebpackPlugin = require('html-webpack-plugin');
- appConfig.plugins?.push(
- new HtmlWebpackPlugin({
-
- ...(IS_UI_DEV_ONLY
- ? {devServer: `https://127.0.0.1:${SENTRY_WEBPACK_PROXY_PORT}`}
- : {}),
- favicon: path.resolve(sentryDjangoAppPath, 'images', 'favicon_dev.png'),
- template: path.resolve(staticPrefix, 'index.ejs'),
- mobile: true,
- excludeChunks: ['pipeline'],
- title: 'Sentry',
- window: {
- __SENTRY_DEV_UI: true,
- },
- })
- );
- }
- const minificationPlugins = [
-
-
-
-
-
-
- new CompressionPlugin({
- algorithm: 'gzip',
- test: /\.(js|map|css|svg|html|txt|ico|eot|ttf)$/,
- }) as any,
-
-
- ];
- if (IS_PRODUCTION) {
-
- minificationPlugins.forEach(plugin => appConfig.plugins?.push(plugin));
- }
- if (env.WEBPACK_CACHE_PATH) {
- appConfig.cache = {
- type: 'filesystem',
- cacheLocation: path.resolve(__dirname, env.WEBPACK_CACHE_PATH),
- buildDependencies: {
-
- config: [__filename],
-
- },
- };
- }
- export default appConfig;
|