webpack.config.ts 26 KB

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