webpack.config.ts 26 KB

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