webpack.config.ts 26 KB

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