webpack.config.ts 25 KB

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