webpack.config.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. /* eslint-env node */
  2. /* eslint import/no-nodejs-modules:0 */
  3. import fs from 'fs';
  4. import path from 'path';
  5. import {WebpackReactSourcemapsPlugin} from '@acemarke/react-prod-sourcemaps';
  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 MiniCssExtractPlugin from 'mini-css-extract-plugin';
  11. import webpack from 'webpack';
  12. import {Configuration as DevServerConfig} from 'webpack-dev-server';
  13. import WebpackHookPlugin from 'webpack-hook-plugin';
  14. import FixStyleOnlyEntriesPlugin from 'webpack-remove-empty-scripts';
  15. import IntegrationDocsFetchPlugin from './build-utils/integration-docs-fetch-plugin';
  16. import LastBuiltPlugin from './build-utils/last-built-plugin';
  17. import SentryInstrumentation from './build-utils/sentry-instrumentation';
  18. import {extractIOSDeviceNames} from './scripts/extract-ios-device-names';
  19. import babelConfig from './babel.config';
  20. // Runs as part of prebuild step to generate a list of identifier -> name mappings for iOS
  21. (async () => {
  22. await extractIOSDeviceNames();
  23. })();
  24. /**
  25. * Merges the devServer config into the webpack config
  26. *
  27. * See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43232
  28. */
  29. interface Configuration extends webpack.Configuration {
  30. devServer?: DevServerConfig;
  31. }
  32. const {env} = process;
  33. // Environment configuration
  34. env.NODE_ENV = env.NODE_ENV ?? 'development';
  35. const IS_PRODUCTION = env.NODE_ENV === 'production';
  36. const IS_TEST = env.NODE_ENV === 'test' || !!env.TEST_SUITE;
  37. // This is used to stop rendering dynamic content for tests/snapshots
  38. // We want it in the case where we are running tests and it is in CI,
  39. // this should not happen in local
  40. const IS_CI = !!env.CI;
  41. // We intentionally build in production mode for acceptance tests, so we explicitly use an env var to
  42. // say that the bundle will be used in acceptance tests. This affects webpack plugins and components
  43. // with dynamic data that render differently statically in tests.
  44. //
  45. // Note, cannot assume it is an acceptance test if `IS_CI` is true, as our image builds has the
  46. // `CI` env var set.
  47. const IS_ACCEPTANCE_TEST = !!env.IS_ACCEPTANCE_TEST;
  48. const IS_DEPLOY_PREVIEW = !!env.NOW_GITHUB_DEPLOYMENT;
  49. const IS_UI_DEV_ONLY = !!env.SENTRY_UI_DEV_ONLY;
  50. const DEV_MODE = !(IS_PRODUCTION || IS_CI);
  51. const WEBPACK_MODE: Configuration['mode'] = IS_PRODUCTION ? 'production' : 'development';
  52. const CONTROL_SILO_PORT = env.SENTRY_CONTROL_SILO_PORT;
  53. // Environment variables that are used by other tooling and should
  54. // not be user configurable.
  55. //
  56. // Ports used by webpack dev server to proxy to backend and webpack
  57. const SENTRY_BACKEND_PORT = env.SENTRY_BACKEND_PORT;
  58. const SENTRY_WEBPACK_PROXY_HOST = env.SENTRY_WEBPACK_PROXY_HOST;
  59. const SENTRY_WEBPACK_PROXY_PORT = env.SENTRY_WEBPACK_PROXY_PORT;
  60. const SENTRY_RELEASE_VERSION = env.SENTRY_RELEASE_VERSION;
  61. // Used by sentry devserver runner to force using webpack-dev-server
  62. const FORCE_WEBPACK_DEV_SERVER = !!env.FORCE_WEBPACK_DEV_SERVER;
  63. const HAS_WEBPACK_DEV_SERVER_CONFIG =
  64. !!SENTRY_BACKEND_PORT && !!SENTRY_WEBPACK_PROXY_PORT;
  65. // User/tooling configurable environment variables
  66. const NO_DEV_SERVER = !!env.NO_DEV_SERVER; // Do not run webpack dev server
  67. const SHOULD_FORK_TS = DEV_MODE && !env.NO_TS_FORK; // Do not run fork-ts plugin (or if not dev env)
  68. const SHOULD_HOT_MODULE_RELOAD = DEV_MODE && !!env.SENTRY_UI_HOT_RELOAD;
  69. const SHOULD_RUN_SPOTLIGHT = DEV_MODE && !env.NO_SPOTLIGHT; // Do not run spotlight sidecar
  70. // Deploy previews are built using vercel. We can check if we're in vercel's
  71. // build process by checking the existence of the PULL_REQUEST env var.
  72. const DEPLOY_PREVIEW_CONFIG = IS_DEPLOY_PREVIEW && {
  73. branch: env.NOW_GITHUB_COMMIT_REF,
  74. commitSha: env.NOW_GITHUB_COMMIT_SHA,
  75. githubOrg: env.NOW_GITHUB_COMMIT_ORG,
  76. githubRepo: env.NOW_GITHUB_COMMIT_REPO,
  77. };
  78. // When deploy previews are enabled always enable experimental SPA mode --
  79. // deploy previews are served standalone. Otherwise fallback to the environment
  80. // configuration.
  81. const SENTRY_EXPERIMENTAL_SPA =
  82. !DEPLOY_PREVIEW_CONFIG && !IS_UI_DEV_ONLY ? !!env.SENTRY_EXPERIMENTAL_SPA : true;
  83. // We should only read from the SENTRY_SPA_DSN env variable if SENTRY_EXPERIMENTAL_SPA
  84. // is true. This is to make sure we can validate that the experimental SPA mode is
  85. // working properly.
  86. const SENTRY_SPA_DSN = SENTRY_EXPERIMENTAL_SPA ? env.SENTRY_SPA_DSN : undefined;
  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 = env.SENTRY_STATIC_DIST_PATH || 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<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 localeChunkGroups: 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. localeChunkGroups[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: 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', '.jsx', '.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': {
  306. NODE_ENV: JSON.stringify(env.NODE_ENV),
  307. IS_ACCEPTANCE_TEST: JSON.stringify(IS_ACCEPTANCE_TEST),
  308. DEPLOY_PREVIEW_CONFIG: JSON.stringify(DEPLOY_PREVIEW_CONFIG),
  309. EXPERIMENTAL_SPA: JSON.stringify(SENTRY_EXPERIMENTAL_SPA),
  310. SPA_DSN: JSON.stringify(SENTRY_SPA_DSN),
  311. SENTRY_RELEASE_VERSION: JSON.stringify(SENTRY_RELEASE_VERSION),
  312. },
  313. }),
  314. /**
  315. * This removes empty js files for style only entries (e.g. sentry.less)
  316. */
  317. new FixStyleOnlyEntriesPlugin({verbose: false}),
  318. ...(SHOULD_FORK_TS
  319. ? [
  320. new ForkTsCheckerWebpackPlugin({
  321. typescript: {
  322. configFile: path.resolve(__dirname, './config/tsconfig.build.json'),
  323. configOverwrite: {
  324. compilerOptions: {incremental: true},
  325. },
  326. },
  327. devServer: false,
  328. // memorylimit is configured in package.json
  329. }),
  330. ]
  331. : []),
  332. /**
  333. * Restrict translation files that are pulled in through app/translations.jsx
  334. * and through moment/locale/* to only those which we create bundles for via
  335. * 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. crypto: require.resolve('crypto-browserify'),
  402. // `yarn why` says this is only needed in dev deps
  403. string_decoder: false,
  404. },
  405. modules: ['node_modules'],
  406. extensions: ['.jsx', '.js', '.json', '.ts', '.tsx', '.less'],
  407. },
  408. output: {
  409. crossOriginLoading: 'anonymous',
  410. clean: true, // Clean the output directory before emit.
  411. path: distPath,
  412. publicPath: '',
  413. filename: 'entrypoints/[name].js',
  414. chunkFilename: 'chunks/[name].[contenthash].js',
  415. sourceMapFilename: 'sourcemaps/[name].[contenthash].js.map',
  416. assetModuleFilename: 'assets/[name].[contenthash][ext]',
  417. },
  418. optimization: {
  419. chunkIds: 'named',
  420. moduleIds: 'named',
  421. splitChunks: {
  422. // Only affect async chunks, otherwise webpack could potentially split our initial chunks
  423. // Which means the app will not load because we'd need these additional chunks to be loaded in our
  424. // django template.
  425. chunks: 'async',
  426. maxInitialRequests: 10, // (default: 30)
  427. maxAsyncRequests: 10, // (default: 30)
  428. cacheGroups: {
  429. ...localeChunkGroups,
  430. },
  431. },
  432. // This only runs in production mode
  433. // Grabbed this example from https://github.com/webpack-contrib/css-minimizer-webpack-plugin
  434. minimizer: ['...', new CssMinimizerPlugin()],
  435. },
  436. devtool: IS_PRODUCTION ? 'source-map' : 'eval-cheap-module-source-map',
  437. };
  438. if (IS_TEST) {
  439. appConfig.resolve!.alias!['sentry-fixture'] = path.join(
  440. __dirname,
  441. 'fixtures',
  442. 'js-stubs'
  443. );
  444. }
  445. if (IS_TEST || IS_ACCEPTANCE_TEST) {
  446. appConfig.resolve!.alias!['integration-docs-platforms'] = path.join(
  447. __dirname,
  448. 'fixtures/integration-docs/_platforms.json'
  449. );
  450. } else {
  451. const plugin = new IntegrationDocsFetchPlugin({basePath: __dirname});
  452. appConfig.plugins?.push(plugin);
  453. appConfig.resolve!.alias!['integration-docs-platforms'] = plugin.modulePath;
  454. }
  455. if (IS_ACCEPTANCE_TEST) {
  456. appConfig.plugins?.push(new LastBuiltPlugin({basePath: __dirname}));
  457. }
  458. // Dev only! Hot module reloading
  459. if (
  460. FORCE_WEBPACK_DEV_SERVER ||
  461. (HAS_WEBPACK_DEV_SERVER_CONFIG && !NO_DEV_SERVER) ||
  462. IS_UI_DEV_ONLY
  463. ) {
  464. if (SHOULD_HOT_MODULE_RELOAD) {
  465. // Hot reload react components on save
  466. // We include the library here as to not break docker/google cloud builds
  467. // since we do not install devDeps there.
  468. const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
  469. appConfig.plugins?.push(new ReactRefreshWebpackPlugin());
  470. // TODO: figure out why defining output breaks hot reloading
  471. if (IS_UI_DEV_ONLY) {
  472. appConfig.output = {};
  473. }
  474. }
  475. appConfig.devServer = {
  476. headers: {
  477. 'Document-Policy': 'js-profiling',
  478. },
  479. // Cover the various environments we use (vercel, getsentry-dev, localhost)
  480. allowedHosts: [
  481. '.sentry.dev',
  482. '.dev.getsentry.net',
  483. '.localhost',
  484. '127.0.0.1',
  485. '.docker.internal',
  486. ],
  487. static: {
  488. directory: './src/sentry/static/sentry',
  489. watch: true,
  490. },
  491. host: SENTRY_WEBPACK_PROXY_HOST,
  492. // Don't reload on errors
  493. hot: 'only',
  494. port: Number(SENTRY_WEBPACK_PROXY_PORT),
  495. devMiddleware: {
  496. stats: 'errors-only',
  497. },
  498. client: {
  499. overlay: false,
  500. },
  501. };
  502. if (!IS_UI_DEV_ONLY) {
  503. // This proxies to local backend server
  504. const backendAddress = `http://127.0.0.1:${SENTRY_BACKEND_PORT}/`;
  505. const relayAddress = 'http://127.0.0.1:7899';
  506. // If we're running siloed servers we also need to proxy
  507. // those requests to the right server.
  508. let controlSiloProxy = {};
  509. if (CONTROL_SILO_PORT) {
  510. // TODO(hybridcloud) We also need to use this URL pattern
  511. // list to select control/region when making API requests in non-proxied
  512. // environments (like production). We'll likely need a way to consolidate this
  513. // with the configuration api.Client uses.
  514. const controlSiloAddress = `http://127.0.0.1:${CONTROL_SILO_PORT}`;
  515. controlSiloProxy = {
  516. '/auth/**': controlSiloAddress,
  517. '/account/**': controlSiloAddress,
  518. '/api/0/users/**': controlSiloAddress,
  519. '/api/0/api-tokens/**': controlSiloAddress,
  520. '/api/0/sentry-apps/**': controlSiloAddress,
  521. '/api/0/organizations/*/audit-logs/**': controlSiloAddress,
  522. '/api/0/organizations/*/broadcasts/**': controlSiloAddress,
  523. '/api/0/organizations/*/integrations/**': controlSiloAddress,
  524. '/api/0/organizations/*/config/integrations/**': controlSiloAddress,
  525. '/api/0/organizations/*/sentry-apps/**': controlSiloAddress,
  526. '/api/0/organizations/*/sentry-app-installations/**': controlSiloAddress,
  527. '/api/0/api-authorizations/**': controlSiloAddress,
  528. '/api/0/api-applications/**': controlSiloAddress,
  529. '/api/0/doc-integrations/**': controlSiloAddress,
  530. '/api/0/assistant/**': controlSiloAddress,
  531. };
  532. }
  533. appConfig.devServer = {
  534. ...appConfig.devServer,
  535. static: {
  536. ...(appConfig.devServer.static as object),
  537. publicPath: '/_static/dist/sentry',
  538. },
  539. // syntax for matching is using https://www.npmjs.com/package/micromatch
  540. proxy: {
  541. ...controlSiloProxy,
  542. '/api/store/**': relayAddress,
  543. '/api/{1..9}*({0..9})/**': relayAddress,
  544. '/api/0/relays/outcomes/': relayAddress,
  545. '!/_static/dist/sentry/**': backendAddress,
  546. },
  547. };
  548. appConfig.output!.publicPath = '/_static/dist/sentry/';
  549. }
  550. }
  551. // We want Spotlight only in Dev mode - Local and UI only
  552. if (SHOULD_RUN_SPOTLIGHT) {
  553. appConfig.plugins?.push(
  554. new WebpackHookPlugin({
  555. onBuildStart: ['yarn run spotlight-sidecar'],
  556. })
  557. );
  558. }
  559. // XXX(epurkhiser): Sentry (development) can be run in an experimental
  560. // pure-SPA mode, where ONLY /api* requests are proxied directly to the API
  561. // backend (in this case, sentry.io), otherwise ALL requests are rewritten
  562. // to a development index.html -- thus, completely separating the frontend
  563. // from serving any pages through the backend.
  564. //
  565. // THIS IS EXPERIMENTAL and has limitations (e.g. you can't use SSO)
  566. //
  567. // Various sentry pages still rely on django to serve html views.
  568. if (IS_UI_DEV_ONLY) {
  569. // XXX: If you change this also change its sibiling in:
  570. // - static/index.ejs
  571. // - static/app/utils/extractSlug.tsx
  572. const KNOWN_DOMAINS =
  573. /(?:\.?)((?:localhost|dev\.getsentry\.net|sentry\.dev)(?:\:\d*)?)$/;
  574. const extractSlug = (hostname: string) => {
  575. const match = hostname.match(KNOWN_DOMAINS);
  576. if (!match) {
  577. return null;
  578. }
  579. const [
  580. matchedExpression, // Expression includes optional leading `.`
  581. ] = match;
  582. const [slug] = hostname.replace(matchedExpression, '').split('.');
  583. return slug;
  584. };
  585. // Try and load certificates from mkcert if available. Use $ yarn mkcert-localhost
  586. const certPath = path.join(__dirname, 'config');
  587. const httpsOptions = !fs.existsSync(path.join(certPath, 'localhost.pem'))
  588. ? {}
  589. : {
  590. key: fs.readFileSync(path.join(certPath, 'localhost-key.pem')),
  591. cert: fs.readFileSync(path.join(certPath, 'localhost.pem')),
  592. };
  593. appConfig.devServer = {
  594. ...appConfig.devServer,
  595. compress: true,
  596. server: {
  597. type: 'https',
  598. options: httpsOptions,
  599. },
  600. headers: {
  601. 'Access-Control-Allow-Origin': '*',
  602. 'Access-Control-Allow-Credentials': 'true',
  603. 'Document-Policy': 'js-profiling',
  604. },
  605. static: {
  606. publicPath: '/_assets/',
  607. },
  608. proxy: [
  609. {
  610. context: ['/api/', '/avatar/', '/organization-avatar/', '/extensions/'],
  611. target: 'https://sentry.io',
  612. secure: false,
  613. changeOrigin: true,
  614. headers: {
  615. Referer: 'https://sentry.io/',
  616. 'Document-Policy': 'js-profiling',
  617. origin: 'https://sentry.io',
  618. },
  619. cookieDomainRewrite: {'.sentry.io': 'localhost'},
  620. router: ({hostname}) => {
  621. const orgSlug = extractSlug(hostname);
  622. return orgSlug ? `https://${orgSlug}.sentry.io` : 'https://sentry.io';
  623. },
  624. },
  625. {
  626. // Handle dev-ui region silo requests.
  627. // Normally regions act as subdomains, but doing so in dev-ui
  628. // would result in requests bypassing webpack proxy and being sent
  629. // directly to region servers. These requests would fail because of CORS.
  630. // Instead Client prefixes region requests with `/region/$name` which
  631. // we rewrite in the proxy.
  632. context: ['/region/'],
  633. target: 'https://us.sentry.io',
  634. secure: false,
  635. changeOrigin: true,
  636. headers: {
  637. Referer: 'https://sentry.io/',
  638. 'Document-Policy': 'js-profiling',
  639. origin: 'https://sentry.io',
  640. },
  641. cookieDomainRewrite: {'.sentry.io': 'localhost'},
  642. pathRewrite: {
  643. '^/region/[^/]*': '',
  644. },
  645. router: req => {
  646. const regionPathPattern = /^\/region\/([^\/]+)/;
  647. const regionname = req.path.match(regionPathPattern);
  648. if (regionname) {
  649. return `https://${regionname[1]}.sentry.io`;
  650. }
  651. return 'https://sentry.io';
  652. },
  653. },
  654. ],
  655. historyApiFallback: {
  656. rewrites: [{from: /^\/.*$/, to: '/_assets/index.html'}],
  657. },
  658. };
  659. appConfig.optimization = {
  660. runtimeChunk: 'single',
  661. };
  662. }
  663. if (IS_UI_DEV_ONLY || SENTRY_EXPERIMENTAL_SPA) {
  664. appConfig.output!.publicPath = '/_assets/';
  665. /**
  666. * Generate a index.html file used for running the app in pure client mode.
  667. * This is currently used for PR deploy previews, where only the frontend
  668. * is deployed.
  669. */
  670. const HtmlWebpackPlugin = require('html-webpack-plugin');
  671. appConfig.plugins?.push(
  672. new HtmlWebpackPlugin({
  673. // Local dev vs vercel slightly differs...
  674. ...(IS_UI_DEV_ONLY
  675. ? {devServer: `https://127.0.0.1:${SENTRY_WEBPACK_PROXY_PORT}`}
  676. : {}),
  677. favicon: path.resolve(sentryDjangoAppPath, 'images', 'favicon_dev.png'),
  678. template: path.resolve(staticPrefix, 'index.ejs'),
  679. mobile: true,
  680. excludeChunks: ['pipeline'],
  681. title: 'Sentry',
  682. window: {
  683. __SENTRY_DEV_UI: true,
  684. },
  685. })
  686. );
  687. }
  688. const minificationPlugins = [
  689. // This compression-webpack-plugin generates pre-compressed files
  690. // ending in .gz, to be picked up and served by our internal static media
  691. // server as well as nginx when paired with the gzip_static module.
  692. //
  693. // TODO(ts): The current @types/compression-webpack-plugin is still targeting
  694. // webpack@4, for now we just as any it.
  695. new CompressionPlugin({
  696. algorithm: 'gzip',
  697. test: /\.(js|map|css|svg|html|txt|ico|eot|ttf)$/,
  698. }) as any,
  699. // NOTE: In production mode webpack will automatically minify javascript
  700. // using the TerserWebpackPlugin.
  701. ];
  702. if (IS_PRODUCTION) {
  703. // NOTE: can't do plugins.push(Array) because webpack/webpack#2217
  704. minificationPlugins.forEach(plugin => appConfig.plugins?.push(plugin));
  705. }
  706. // Cache webpack builds
  707. if (env.WEBPACK_CACHE_PATH) {
  708. appConfig.cache = {
  709. type: 'filesystem',
  710. cacheLocation: path.resolve(__dirname, env.WEBPACK_CACHE_PATH),
  711. buildDependencies: {
  712. // This makes all dependencies of this file - build dependencies
  713. config: [__filename],
  714. // By default webpack and loaders are build dependencies
  715. },
  716. };
  717. }
  718. export default appConfig;