webpack.config.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. import {WebpackReactSourcemapsPlugin} from '@acemarke/react-prod-sourcemaps';
  2. import {RsdoctorWebpackPlugin} from '@rsdoctor/webpack-plugin';
  3. import {sentryWebpackPlugin} from '@sentry/webpack-plugin';
  4. import browserslist from 'browserslist';
  5. import CompressionPlugin from 'compression-webpack-plugin';
  6. import CopyPlugin from 'copy-webpack-plugin';
  7. import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
  8. import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
  9. import lightningcss from 'lightningcss';
  10. import MiniCssExtractPlugin from 'mini-css-extract-plugin';
  11. import fs from 'node:fs';
  12. import path from 'node:path';
  13. import TerserPlugin from 'terser-webpack-plugin';
  14. import webpack from 'webpack';
  15. import type {ProxyConfigArray, Static} from 'webpack-dev-server';
  16. import FixStyleOnlyEntriesPlugin from 'webpack-remove-empty-scripts';
  17. import LastBuiltPlugin from './build-utils/last-built-plugin';
  18. import SentryInstrumentation from './build-utils/sentry-instrumentation';
  19. import babelConfig from './babel.config';
  20. import packageJson from './package.json';
  21. type MinimizerPluginOptions = {
  22. targets: lightningcss.TransformAttributeOptions['targets'];
  23. };
  24. const {env} = process;
  25. // Environment configuration
  26. env.NODE_ENV = env.NODE_ENV ?? 'development';
  27. const IS_PRODUCTION = env.NODE_ENV === 'production';
  28. const IS_TEST = env.NODE_ENV === 'test' || !!env.TEST_SUITE;
  29. // This is used to stop rendering dynamic content for tests/snapshots
  30. // We want it in the case where we are running tests and it is in CI,
  31. // this should not happen in local
  32. const IS_CI = !!env.CI;
  33. // We intentionally build in production mode for acceptance tests, so we explicitly use an env var to
  34. // say that the bundle will be used in acceptance tests. This affects webpack plugins and components
  35. // with dynamic data that render differently statically in tests.
  36. //
  37. // Note, cannot assume it is an acceptance test if `IS_CI` is true, as our image builds has the
  38. // `CI` env var set.
  39. const IS_ACCEPTANCE_TEST = !!env.IS_ACCEPTANCE_TEST;
  40. const IS_DEPLOY_PREVIEW = !!env.NOW_GITHUB_DEPLOYMENT;
  41. const IS_UI_DEV_ONLY = !!env.SENTRY_UI_DEV_ONLY;
  42. const DEV_MODE = !(IS_PRODUCTION || IS_CI);
  43. const WEBPACK_MODE: webpack.Configuration['mode'] = IS_PRODUCTION
  44. ? 'production'
  45. : 'development';
  46. const CONTROL_SILO_PORT = env.SENTRY_CONTROL_SILO_PORT;
  47. // Environment variables that are used by other tooling and should
  48. // not be user configurable.
  49. //
  50. // Ports used by webpack dev server to proxy to backend and webpack
  51. const SENTRY_BACKEND_PORT = env.SENTRY_BACKEND_PORT;
  52. const SENTRY_WEBPACK_PROXY_HOST = env.SENTRY_WEBPACK_PROXY_HOST;
  53. const SENTRY_WEBPACK_PROXY_PORT = env.SENTRY_WEBPACK_PROXY_PORT;
  54. const SENTRY_RELEASE_VERSION = env.SENTRY_RELEASE_VERSION;
  55. // Used by sentry devserver runner to force using webpack-dev-server
  56. const FORCE_WEBPACK_DEV_SERVER = !!env.FORCE_WEBPACK_DEV_SERVER;
  57. const HAS_WEBPACK_DEV_SERVER_CONFIG =
  58. !!SENTRY_BACKEND_PORT && !!SENTRY_WEBPACK_PROXY_PORT;
  59. // User/tooling configurable environment variables
  60. const NO_DEV_SERVER = !!env.NO_DEV_SERVER; // Do not run webpack dev server
  61. const SHOULD_FORK_TS = DEV_MODE && !env.NO_TS_FORK; // Do not run fork-ts plugin (or if not dev env)
  62. const SHOULD_HOT_MODULE_RELOAD = DEV_MODE && !!env.SENTRY_UI_HOT_RELOAD;
  63. const SHOULD_ADD_RSDOCTOR = Boolean(env.RSDOCTOR);
  64. // Deploy previews are built using vercel. We can check if we're in vercel's
  65. // build process by checking the existence of the PULL_REQUEST env var.
  66. const DEPLOY_PREVIEW_CONFIG = IS_DEPLOY_PREVIEW && {
  67. branch: env.NOW_GITHUB_COMMIT_REF,
  68. commitSha: env.NOW_GITHUB_COMMIT_SHA,
  69. githubOrg: env.NOW_GITHUB_COMMIT_ORG,
  70. githubRepo: env.NOW_GITHUB_COMMIT_REPO,
  71. };
  72. // When deploy previews are enabled always enable experimental SPA mode --
  73. // deploy previews are served standalone. Otherwise fallback to the environment
  74. // configuration.
  75. const SENTRY_EXPERIMENTAL_SPA =
  76. !DEPLOY_PREVIEW_CONFIG && !IS_UI_DEV_ONLY ? !!env.SENTRY_EXPERIMENTAL_SPA : true;
  77. // We should only read from the SENTRY_SPA_DSN env variable if SENTRY_EXPERIMENTAL_SPA
  78. // is true. This is to make sure we can validate that the experimental SPA mode is
  79. // working properly.
  80. const SENTRY_SPA_DSN = SENTRY_EXPERIMENTAL_SPA ? env.SENTRY_SPA_DSN : undefined;
  81. const CODECOV_TOKEN = env.CODECOV_TOKEN;
  82. // value should come back as either 'true' or 'false' or undefined
  83. const ENABLE_CODECOV_BA = env.CODECOV_ENABLE_BA === 'true';
  84. // this is the path to the django "sentry" app, we output the webpack build here to `dist`
  85. // so that `django collectstatic` and so that we can serve the post-webpack bundles
  86. const sentryDjangoAppPath = path.join(__dirname, 'src/sentry/static/sentry');
  87. const distPath = path.join(sentryDjangoAppPath, 'dist');
  88. const staticPrefix = path.join(__dirname, 'static');
  89. // Locale file extraction build step
  90. if (env.SENTRY_EXTRACT_TRANSLATIONS === '1') {
  91. babelConfig.plugins?.push([
  92. 'module:babel-gettext-extractor',
  93. {
  94. fileName: 'build/javascript.po',
  95. baseDirectory: path.join(__dirname),
  96. functionNames: {
  97. gettext: ['msgid'],
  98. ngettext: ['msgid', 'msgid_plural', 'count'],
  99. gettextComponentTemplate: ['msgid'],
  100. t: ['msgid'],
  101. tn: ['msgid', 'msgid_plural', 'count'],
  102. tct: ['msgid'],
  103. },
  104. },
  105. ]);
  106. }
  107. // Locale compilation and optimizations.
  108. //
  109. // Locales are code-split from the app and vendor chunk into separate chunks
  110. // that will be loaded by layout.html depending on the users configured locale.
  111. //
  112. // Code splitting happens using the splitChunks plugin, configured under the
  113. // `optimization` key of the webpack module. We create chunk (cache) groups for
  114. // each of our supported locales and extract the PO files and moment.js locale
  115. // files into each chunk.
  116. //
  117. // A plugin is used to remove the locale chunks from the app entry's chunk
  118. // dependency list, so that our compiled bundle does not expect that *all*
  119. // locale chunks must be loaded
  120. const localeCatalogPath = path.join(
  121. __dirname,
  122. 'src',
  123. 'sentry',
  124. 'locale',
  125. 'catalogs.json'
  126. );
  127. type LocaleCatalog = {
  128. supported_locales: string[];
  129. };
  130. const localeCatalog: LocaleCatalog = JSON.parse(
  131. fs.readFileSync(localeCatalogPath, 'utf8')
  132. );
  133. // Translates a locale name to a language code.
  134. //
  135. // * po files are kept in a directory represented by the locale name [0]
  136. // * moment.js locales are stored as language code files
  137. //
  138. // [0] https://docs.djangoproject.com/en/2.1/topics/i18n/#term-locale-name
  139. const localeToLanguage = (locale: string) => locale.toLowerCase().replace('_', '-');
  140. const supportedLocales = localeCatalog.supported_locales;
  141. const supportedLanguages = supportedLocales.map(localeToLanguage);
  142. type CacheGroups = Exclude<
  143. NonNullable<webpack.Configuration['optimization']>['splitChunks'],
  144. false | undefined
  145. >['cacheGroups'];
  146. type CacheGroupTest = (
  147. module: webpack.Module,
  148. context: Parameters<webpack.optimize.SplitChunksPlugin['options']['getCacheGroups']>[1]
  149. ) => boolean;
  150. // A mapping of chunk groups used for locale code splitting
  151. const cacheGroups: CacheGroups = {};
  152. supportedLocales
  153. // No need to split the english locale out as it will be completely empty and
  154. // is not included in the django layout.html.
  155. .filter(l => l !== 'en')
  156. .forEach(locale => {
  157. const language = localeToLanguage(locale);
  158. const group = `locale/${language}`;
  159. // List of module path tests to group into locale chunks
  160. const localeGroupTests = [
  161. new RegExp(`locale\\/${locale}\\/.*\\.po$`),
  162. new RegExp(`moment\\/locale\\/${language}\\.js$`),
  163. ];
  164. // module test taken from [0] and modified to support testing against
  165. // multiple expressions.
  166. //
  167. // [0] https://github.com/webpack/webpack/blob/7a6a71f1e9349f86833de12a673805621f0fc6f6/lib/optimize/SplitChunksPlugin.js#L309-L320
  168. const groupTest: CacheGroupTest = (module, {chunkGraph}) =>
  169. localeGroupTests.some(pattern =>
  170. pattern.test(module?.nameForCondition?.() ?? '')
  171. ? true
  172. : chunkGraph.getModuleChunks(module).some(c => c.name && pattern.test(c.name))
  173. );
  174. // We are defining a chunk that combines the django language files with
  175. // moment's locales as if you want one, you will want the other.
  176. //
  177. // In the application code you will still need to import via their module
  178. // paths and not the chunk name
  179. cacheGroups[group] = {
  180. chunks: 'async',
  181. name: group,
  182. test: groupTest,
  183. enforce: true,
  184. };
  185. });
  186. const babelOptions = {...babelConfig, cacheDirectory: true};
  187. const babelLoaderConfig = {
  188. loader: 'babel-loader',
  189. options: babelOptions,
  190. };
  191. /**
  192. * Main Webpack config for Sentry React SPA.
  193. */
  194. const appConfig: webpack.Configuration = {
  195. mode: WEBPACK_MODE,
  196. entry: {
  197. /**
  198. * Main Sentry SPA
  199. *
  200. * The order here matters for `getsentry`
  201. */
  202. app: ['sentry/utils/statics-setup', 'sentry'],
  203. /**
  204. * Pipeline View for integrations
  205. */
  206. pipeline: ['sentry/utils/statics-setup', 'sentry/views/integrationPipeline'],
  207. /**
  208. * Legacy CSS Webpack appConfig for Django-powered views.
  209. * This generates a single "sentry.css" file that imports ALL component styles
  210. * for use on Django-powered pages.
  211. */
  212. sentry: 'less/sentry.less',
  213. },
  214. context: staticPrefix,
  215. module: {
  216. /**
  217. * XXX: Modifying the order/contents of these rules may break `getsentry`
  218. * Please remember to test it.
  219. */
  220. rules: [
  221. {
  222. test: /\.[tj]sx?$/,
  223. include: [staticPrefix],
  224. exclude: /(vendor|node_modules|dist)/,
  225. use: babelLoaderConfig,
  226. },
  227. {
  228. test: /\.po$/,
  229. use: {
  230. loader: 'po-catalog-loader',
  231. options: {
  232. referenceExtensions: ['.js', '.tsx'],
  233. domain: 'sentry',
  234. },
  235. },
  236. },
  237. {
  238. test: /\.pegjs$/,
  239. use: [{loader: path.resolve(__dirname, './build-utils/peggy-loader.ts')}],
  240. },
  241. {
  242. test: /\.css/,
  243. use: ['style-loader', 'css-loader'],
  244. },
  245. {
  246. test: /\.less$/,
  247. include: [staticPrefix],
  248. use: [
  249. {
  250. loader: MiniCssExtractPlugin.loader,
  251. options: {
  252. publicPath: 'auto',
  253. },
  254. },
  255. 'css-loader',
  256. 'less-loader',
  257. ],
  258. },
  259. {
  260. test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg|mp4)($|\?)/,
  261. type: 'asset',
  262. },
  263. ],
  264. noParse: [
  265. // don't parse known, pre-built javascript files (improves webpack perf)
  266. /jed\/jed\.js/,
  267. /marked\/lib\/marked\.js/,
  268. /terser\/dist\/bundle\.min\.js/,
  269. ],
  270. },
  271. plugins: [
  272. /**
  273. * Adds build time measurement instrumentation, which will be reported back
  274. * to sentry
  275. */
  276. new SentryInstrumentation(),
  277. // Do not bundle moment's locale files as we will lazy load them using
  278. // dynamic imports in the application code
  279. new webpack.IgnorePlugin({
  280. contextRegExp: /moment$/,
  281. resourceRegExp: /^\.\/locale$/,
  282. }),
  283. /**
  284. * TODO(epurkhiser): Figure out if we still need these
  285. */
  286. new webpack.ProvidePlugin({
  287. process: 'process/browser',
  288. Buffer: ['buffer', 'Buffer'],
  289. }),
  290. /**
  291. * Extract CSS into separate files.
  292. */
  293. new MiniCssExtractPlugin({
  294. // We want the sentry css file to be unversioned for frontend-only deploys
  295. // We will cache using `Cache-Control` headers
  296. filename: 'entrypoints/[name].css',
  297. }),
  298. /**
  299. * Defines environment specific flags.
  300. */
  301. new webpack.DefinePlugin({
  302. 'process.env.IS_ACCEPTANCE_TEST': JSON.stringify(IS_ACCEPTANCE_TEST),
  303. 'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV),
  304. 'process.env.DEPLOY_PREVIEW_CONFIG': JSON.stringify(DEPLOY_PREVIEW_CONFIG),
  305. 'process.env.EXPERIMENTAL_SPA': JSON.stringify(SENTRY_EXPERIMENTAL_SPA),
  306. 'process.env.SPA_DSN': JSON.stringify(SENTRY_SPA_DSN),
  307. 'process.env.SENTRY_RELEASE_VERSION': JSON.stringify(SENTRY_RELEASE_VERSION),
  308. }),
  309. /**
  310. * This removes empty js files for style only entries (e.g. sentry.less)
  311. */
  312. new FixStyleOnlyEntriesPlugin({verbose: false}),
  313. ...(SHOULD_FORK_TS
  314. ? [
  315. new ForkTsCheckerWebpackPlugin({
  316. typescript: {
  317. configFile: path.resolve(__dirname, './config/tsconfig.build.json'),
  318. configOverwrite: {
  319. compilerOptions: {incremental: true},
  320. },
  321. memoryLimit: 4096,
  322. },
  323. devServer: false,
  324. }),
  325. ]
  326. : []),
  327. ...(SHOULD_ADD_RSDOCTOR ? [new RsdoctorWebpackPlugin({})] : []),
  328. /**
  329. * Restrict translation files that are pulled in through
  330. * initializeLocale.tsx and through moment/locale/* to only those which we
  331. * create bundles for via locale/catalogs.json.
  332. *
  333. * Without this, webpack will still output all of the unused locale files despite
  334. * the application never loading any of them.
  335. */
  336. new webpack.ContextReplacementPlugin(
  337. /sentry-locale$/,
  338. path.join(__dirname, 'src', 'sentry', 'locale', path.sep),
  339. true,
  340. new RegExp(`(${supportedLocales.join('|')})/.*\\.po$`)
  341. ),
  342. new webpack.ContextReplacementPlugin(
  343. /moment\/locale/,
  344. new RegExp(`(${supportedLanguages.join('|')})\\.js$`)
  345. ),
  346. /**
  347. * Copies file logo-sentry.svg to the dist/entrypoints directory so that it can be accessed by
  348. * the backend
  349. */
  350. new CopyPlugin({
  351. patterns: [
  352. {
  353. from: path.join(staticPrefix, 'images/logo-sentry.svg'),
  354. to: 'entrypoints/logo-sentry.svg',
  355. toType: 'file',
  356. },
  357. // Add robots.txt when deploying in preview mode so public previews do
  358. // not get indexed by bots.
  359. ...(IS_DEPLOY_PREVIEW
  360. ? [
  361. {
  362. from: path.join(staticPrefix, 'robots-dev.txt'),
  363. to: 'robots.txt',
  364. toType: 'file' as const,
  365. },
  366. ]
  367. : []),
  368. ],
  369. }),
  370. WebpackReactSourcemapsPlugin({
  371. mode: IS_PRODUCTION ? 'strict' : undefined,
  372. debug: false,
  373. }),
  374. ],
  375. resolve: {
  376. alias: {
  377. sentry: path.join(staticPrefix, 'app'),
  378. 'sentry-images': path.join(staticPrefix, 'images'),
  379. 'sentry-logos': path.join(sentryDjangoAppPath, 'images', 'logos'),
  380. 'sentry-fonts': path.join(staticPrefix, 'fonts'),
  381. // Aliasing this for getsentry's build, otherwise `less/select2` will not be able
  382. // to be resolved
  383. less: path.join(staticPrefix, 'less'),
  384. 'sentry-test': path.join(__dirname, 'tests', 'js', 'sentry-test'),
  385. 'sentry-locale': path.join(__dirname, 'src', 'sentry', 'locale'),
  386. 'ios-device-list': path.join(
  387. __dirname,
  388. 'node_modules',
  389. 'ios-device-list',
  390. 'dist',
  391. 'ios-device-list.min.js'
  392. ),
  393. },
  394. fallback: {
  395. vm: false,
  396. stream: false,
  397. // Node crypto is imported in @sentry-internal/global-search but not used here
  398. crypto: false,
  399. // `yarn why` says this is only needed in dev deps
  400. string_decoder: false,
  401. // For framer motion v6, might be able to remove on v11
  402. 'process/browser': require.resolve('process/browser'),
  403. },
  404. // Might be an issue if changing file extensions during development
  405. cache: true,
  406. // Prefers local modules over node_modules
  407. preferAbsolute: true,
  408. modules: ['node_modules'],
  409. extensions: ['.js', '.tsx', '.ts', '.json', '.less'],
  410. symlinks: false,
  411. },
  412. output: {
  413. crossOriginLoading: 'anonymous',
  414. clean: true, // Clean the output directory before emit.
  415. path: distPath,
  416. publicPath: '',
  417. filename: 'entrypoints/[name].js',
  418. chunkFilename: 'chunks/[name].[contenthash].js',
  419. sourceMapFilename: 'sourcemaps/[name].[contenthash].js.map',
  420. assetModuleFilename: 'assets/[name].[contenthash][ext]',
  421. },
  422. optimization: {
  423. chunkIds: 'named',
  424. moduleIds: 'named',
  425. splitChunks: {
  426. // Only affect async chunks, otherwise webpack could potentially split our initial chunks
  427. // Which means the app will not load because we'd need these additional chunks to be loaded in our
  428. // django template.
  429. chunks: 'async',
  430. maxInitialRequests: 10, // (default: 30)
  431. maxAsyncRequests: 10, // (default: 30)
  432. cacheGroups,
  433. },
  434. minimizer: [
  435. new TerserPlugin({
  436. parallel: true,
  437. minify: TerserPlugin.esbuildMinify,
  438. }),
  439. new CssMinimizerPlugin<MinimizerPluginOptions>({
  440. parallel: true,
  441. minify: CssMinimizerPlugin.lightningCssMinify,
  442. minimizerOptions: {
  443. targets: lightningcss.browserslistToTargets(
  444. browserslist(packageJson.browserslist.production)
  445. ),
  446. },
  447. }),
  448. ],
  449. },
  450. devtool: IS_PRODUCTION ? 'source-map' : 'eval-cheap-module-source-map',
  451. };
  452. if (IS_TEST) {
  453. (appConfig.resolve!.alias! as any)['sentry-fixture'] = path.join(
  454. __dirname,
  455. 'tests',
  456. 'js',
  457. 'fixtures'
  458. );
  459. }
  460. if (IS_ACCEPTANCE_TEST) {
  461. appConfig.plugins?.push(new LastBuiltPlugin({basePath: __dirname}));
  462. }
  463. // Dev only! Hot module reloading
  464. if (
  465. FORCE_WEBPACK_DEV_SERVER ||
  466. (HAS_WEBPACK_DEV_SERVER_CONFIG && !NO_DEV_SERVER) ||
  467. IS_UI_DEV_ONLY
  468. ) {
  469. if (SHOULD_HOT_MODULE_RELOAD) {
  470. // Hot reload react components on save
  471. // We include the library here as to not break docker/google cloud builds
  472. // since we do not install devDeps there.
  473. const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
  474. appConfig.plugins?.push(new ReactRefreshWebpackPlugin());
  475. // TODO: figure out why defining output breaks hot reloading
  476. if (IS_UI_DEV_ONLY) {
  477. appConfig.output = {};
  478. }
  479. }
  480. appConfig.devServer = {
  481. headers: {
  482. 'Document-Policy': 'js-profiling',
  483. },
  484. // Cover the various environments we use (vercel, getsentry-dev, localhost, ngrok)
  485. allowedHosts: [
  486. '.sentry.dev',
  487. '.dev.getsentry.net',
  488. '.localhost',
  489. '127.0.0.1',
  490. '.docker.internal',
  491. '.ngrok.dev',
  492. '.ngrok.io',
  493. '.ngrok.app',
  494. ],
  495. static: {
  496. directory: './src/sentry/static/sentry',
  497. watch: true,
  498. },
  499. host: SENTRY_WEBPACK_PROXY_HOST,
  500. // Don't reload on errors
  501. hot: 'only',
  502. port: Number(SENTRY_WEBPACK_PROXY_PORT),
  503. devMiddleware: {
  504. stats: 'errors-only',
  505. },
  506. client: {
  507. overlay: false,
  508. },
  509. };
  510. if (!IS_UI_DEV_ONLY) {
  511. // This proxies to local backend server
  512. const backendAddress = `http://127.0.0.1:${SENTRY_BACKEND_PORT}/`;
  513. const relayAddress = 'http://127.0.0.1:7899';
  514. // If we're running siloed servers we also need to proxy
  515. // those requests to the right server.
  516. let controlSiloProxy: ProxyConfigArray = [];
  517. if (CONTROL_SILO_PORT) {
  518. // TODO(hybridcloud) We also need to use this URL pattern
  519. // list to select control/region when making API requests in non-proxied
  520. // environments (like production). We'll likely need a way to consolidate this
  521. // with the configuration api.Client uses.
  522. const controlSiloAddress = `http://127.0.0.1:${CONTROL_SILO_PORT}`;
  523. controlSiloProxy = [
  524. {
  525. context: [
  526. '/auth/**',
  527. '/account/**',
  528. '/api/0/users/**',
  529. '/api/0/api-tokens/**',
  530. '/api/0/sentry-apps/**',
  531. '/api/0/organizations/*/audit-logs/**',
  532. '/api/0/organizations/*/broadcasts/**',
  533. '/api/0/organizations/*/integrations/**',
  534. '/api/0/organizations/*/config/integrations/**',
  535. '/api/0/organizations/*/sentry-apps/**',
  536. '/api/0/organizations/*/sentry-app-installations/**',
  537. '/api/0/api-authorizations/**',
  538. '/api/0/api-applications/**',
  539. '/api/0/doc-integrations/**',
  540. '/api/0/assistant/**',
  541. ],
  542. target: controlSiloAddress,
  543. },
  544. ];
  545. }
  546. appConfig.devServer = {
  547. ...appConfig.devServer,
  548. static: {
  549. ...(appConfig.devServer.static as Static),
  550. publicPath: '/_static/dist/sentry',
  551. },
  552. // syntax for matching is using https://www.npmjs.com/package/micromatch
  553. proxy: [
  554. ...controlSiloProxy,
  555. {
  556. context: [
  557. '/api/store/**',
  558. '/api/{1..9}*({0..9})/**',
  559. '/api/0/relays/outcomes/**',
  560. ],
  561. target: relayAddress,
  562. },
  563. {
  564. context: ['!/_static/dist/sentry/**'],
  565. target: backendAddress,
  566. },
  567. ],
  568. };
  569. appConfig.output!.publicPath = '/_static/dist/sentry/';
  570. }
  571. }
  572. // XXX(epurkhiser): Sentry (development) can be run in an experimental
  573. // pure-SPA mode, where ONLY /api* requests are proxied directly to the API
  574. // backend (in this case, sentry.io), otherwise ALL requests are rewritten
  575. // to a development index.html -- thus, completely separating the frontend
  576. // from serving any pages through the backend.
  577. //
  578. // THIS IS EXPERIMENTAL and has limitations (e.g. you can't use SSO)
  579. //
  580. // Various sentry pages still rely on django to serve html views.
  581. if (IS_UI_DEV_ONLY) {
  582. // XXX: If you change this also change its sibiling in:
  583. // - static/index.ejs
  584. // - static/app/utils/extractSlug.tsx
  585. const KNOWN_DOMAINS =
  586. /(?:\.?)((?:localhost|dev\.getsentry\.net|sentry\.dev)(?:\:\d*)?)$/;
  587. const extractSlug = (hostname: string) => {
  588. const match = hostname.match(KNOWN_DOMAINS);
  589. if (!match) {
  590. return null;
  591. }
  592. const [
  593. matchedExpression, // Expression includes optional leading `.`
  594. ] = match;
  595. const [slug] = hostname.replace(matchedExpression, '').split('.');
  596. return slug;
  597. };
  598. // Try and load certificates from mkcert if available. Use $ yarn mkcert-localhost
  599. const certPath = path.join(__dirname, 'config');
  600. const httpsOptions = !fs.existsSync(path.join(certPath, 'localhost.pem'))
  601. ? {}
  602. : {
  603. key: fs.readFileSync(path.join(certPath, 'localhost-key.pem')),
  604. cert: fs.readFileSync(path.join(certPath, 'localhost.pem')),
  605. };
  606. appConfig.devServer = {
  607. ...appConfig.devServer,
  608. compress: true,
  609. server: {
  610. type: 'https',
  611. options: httpsOptions,
  612. },
  613. headers: {
  614. 'Access-Control-Allow-Origin': '*',
  615. 'Access-Control-Allow-Credentials': 'true',
  616. 'Document-Policy': 'js-profiling',
  617. },
  618. static: {
  619. publicPath: '/_assets/',
  620. },
  621. proxy: [
  622. {
  623. context: ['/api/', '/avatar/', '/organization-avatar/', '/extensions/'],
  624. target: 'https://sentry.io',
  625. secure: false,
  626. changeOrigin: true,
  627. headers: {
  628. Referer: 'https://sentry.io/',
  629. 'Document-Policy': 'js-profiling',
  630. origin: 'https://sentry.io',
  631. },
  632. cookieDomainRewrite: {'.sentry.io': 'localhost'},
  633. router: ({hostname}) => {
  634. const orgSlug = extractSlug(hostname);
  635. return orgSlug ? `https://${orgSlug}.sentry.io` : 'https://sentry.io';
  636. },
  637. },
  638. {
  639. // Handle dev-ui region silo requests.
  640. // Normally regions act as subdomains, but doing so in dev-ui
  641. // would result in requests bypassing webpack proxy and being sent
  642. // directly to region servers. These requests would fail because of CORS.
  643. // Instead Client prefixes region requests with `/region/$name` which
  644. // we rewrite in the proxy.
  645. context: ['/region/'],
  646. target: 'https://us.sentry.io',
  647. secure: false,
  648. changeOrigin: true,
  649. headers: {
  650. Referer: 'https://sentry.io/',
  651. 'Document-Policy': 'js-profiling',
  652. origin: 'https://sentry.io',
  653. },
  654. cookieDomainRewrite: {'.sentry.io': 'localhost'},
  655. pathRewrite: {
  656. '^/region/[^/]*': '',
  657. },
  658. router: req => {
  659. const regionPathPattern = /^\/region\/([^\/]+)/;
  660. const regionname = req.path.match(regionPathPattern);
  661. if (regionname) {
  662. return `https://${regionname[1]}.sentry.io`;
  663. }
  664. return 'https://sentry.io';
  665. },
  666. },
  667. ],
  668. historyApiFallback: {
  669. rewrites: [{from: /^\/.*$/, to: '/_assets/index.html'}],
  670. },
  671. };
  672. appConfig.optimization = {
  673. runtimeChunk: 'single',
  674. };
  675. }
  676. if (IS_UI_DEV_ONLY || SENTRY_EXPERIMENTAL_SPA) {
  677. appConfig.output!.publicPath = '/_assets/';
  678. /**
  679. * Generate a index.html file used for running the app in pure client mode.
  680. * This is currently used for PR deploy previews, where only the frontend
  681. * is deployed.
  682. */
  683. const HtmlWebpackPlugin = require('html-webpack-plugin');
  684. appConfig.plugins?.push(
  685. new HtmlWebpackPlugin({
  686. // Local dev vs vercel slightly differs...
  687. ...(IS_UI_DEV_ONLY
  688. ? {devServer: `https://127.0.0.1:${SENTRY_WEBPACK_PROXY_PORT}`}
  689. : {}),
  690. favicon: path.resolve(sentryDjangoAppPath, 'images', 'favicon-dev.png'),
  691. template: path.resolve(staticPrefix, 'index.ejs'),
  692. mobile: true,
  693. excludeChunks: ['pipeline'],
  694. title: 'Sentry',
  695. window: {
  696. __SENTRY_DEV_UI: true,
  697. },
  698. })
  699. );
  700. }
  701. const minificationPlugins = [
  702. // This compression-webpack-plugin generates pre-compressed files
  703. // ending in .gz, to be picked up and served by our internal static media
  704. // server as well as nginx when paired with the gzip_static module.
  705. new CompressionPlugin({
  706. algorithm: 'gzip',
  707. test: /\.(js|map|css|svg|html|txt|ico|eot|ttf)$/,
  708. }),
  709. ];
  710. if (IS_PRODUCTION) {
  711. // NOTE: can't do plugins.push(Array) because webpack/webpack#2217
  712. minificationPlugins.forEach(plugin => appConfig.plugins?.push(plugin));
  713. }
  714. if (CODECOV_TOKEN && ENABLE_CODECOV_BA) {
  715. const {codecovWebpackPlugin} = require('@codecov/webpack-plugin');
  716. // defaulting to an empty string which in turn will fallback to env var or
  717. // determine merge commit sha from git
  718. const GH_COMMIT_SHA = env.GH_COMMIT_SHA ?? '';
  719. appConfig.plugins?.push(
  720. codecovWebpackPlugin({
  721. enableBundleAnalysis: true,
  722. bundleName: 'app-webpack-bundle',
  723. uploadToken: CODECOV_TOKEN,
  724. debug: true,
  725. gitService: 'github',
  726. uploadOverrides: {
  727. sha: GH_COMMIT_SHA,
  728. },
  729. })
  730. );
  731. }
  732. // Cache webpack builds
  733. if (env.WEBPACK_CACHE_PATH) {
  734. appConfig.cache = {
  735. type: 'filesystem',
  736. cacheLocation: path.resolve(__dirname, env.WEBPACK_CACHE_PATH),
  737. buildDependencies: {
  738. // This makes all dependencies of this file - build dependencies
  739. config: [__filename],
  740. // By default webpack and loaders are build dependencies
  741. },
  742. };
  743. }
  744. appConfig.plugins?.push(
  745. sentryWebpackPlugin({
  746. applicationKey: 'sentry-spa',
  747. telemetry: false,
  748. sourcemaps: {
  749. disable: true,
  750. },
  751. release: {
  752. create: false,
  753. },
  754. reactComponentAnnotation: {
  755. enabled: true,
  756. },
  757. bundleSizeOptimizations: {
  758. // This is enabled so that our SDKs send exceptions to Sentry
  759. excludeDebugStatements: false,
  760. excludeReplayIframe: true,
  761. excludeReplayShadowDom: true,
  762. },
  763. })
  764. );
  765. export default appConfig;