From cc142c56c174eb95c22bdc75f84171076438b414 Mon Sep 17 00:00:00 2001 From: Aaron Chong Date: Sat, 20 Jul 2024 23:49:12 +0800 Subject: [PATCH] frontend migrations (#971) * rmf-auth Signed-off-by: Aaron Chong * Migrate admin Signed-off-by: Aaron Chong * Migrate doors Signed-off-by: Aaron Chong * Migrate dashboard deps, configs, scripts, storybook Signed-off-by: Aaron Chong * Migrate delivery alert store Signed-off-by: Aaron Chong * Lifts Signed-off-by: Aaron Chong * Add react-error-boundary Signed-off-by: Aaron Chong * robot and task summaries and components Signed-off-by: Aaron Chong * More fixes, changes and migrations Signed-off-by: Aaron Chong * Migration of using key=value labels Signed-off-by: Aaron Chong * Fix build error in dynamic module and react-scheduler peer dep Signed-off-by: Aaron Chong * Revert default config public url Signed-off-by: Aaron Chong * rmf-auth install jest-environment-jsdom Signed-off-by: Aaron Chong * Fix react-components ci Signed-off-by: Aaron Chong * Provide default trajectory server URL in minimal rmf build Signed-off-by: Aaron Chong * react-components, install jest-environment-jsdom Signed-off-by: Aaron Chong * dashboard, revert env in minimal rmf, user DOTENV_CONFIG_PATH Signed-off-by: Aaron Chong * dashboard, make test async Signed-off-by: Aaron Chong * api-server, asgi.scope instead of scope Signed-off-by: Aaron Chong * remove yarn from gitignore Signed-off-by: Aaron Chong * Remove usage of requests in task app, fix unix_millis_warn_time usage as map Signed-off-by: Aaron Chong * dashboard fix filter by labels Signed-off-by: Aaron Chong * Fix task summary Signed-off-by: Aaron Chong * Fix for getting task definition id from labels Signed-off-by: Aaron Chong * revert react-scheduler from latest to 2.7.8, due to race condition of custom event editor Signed-off-by: Aaron Chong --------- Signed-off-by: Aaron Chong --- packages/api-client/lib/index.ts | 5 + packages/api-client/lib/version.ts | 2 +- .../api-server/api_server/default_config.py | 2 +- .../api-server/api_server/fast_io/__init__.py | 2 +- packages/dashboard/.gitignore | 4 +- packages/dashboard/.storybook/main.js | 13 - packages/dashboard/.storybook/main.ts | 20 + packages/dashboard/.storybook/preview.js | 3 - packages/dashboard/.storybook/preview.ts | 14 + packages/dashboard/babel.config.js | 7 + packages/dashboard/config/env.js | 102 +++ packages/dashboard/config/getHttpsConfig.js | 60 ++ .../dashboard/config/jest/babelTransform.js | 29 + .../dashboard/config/jest/cssTransform.js | 14 + .../dashboard/config/jest/fileTransform.js | 40 + packages/dashboard/config/modules.js | 136 ++++ packages/dashboard/config/paths.js | 75 ++ packages/dashboard/config/webpack.config.js | 695 ++++++++++++++++++ .../persistentCache/createEnvironmentHash.js | 9 + .../config/webpackDevServer.config.js | 126 ++++ packages/dashboard/package.json | 5 +- packages/dashboard/scripts/build.js | 186 +++++ packages/dashboard/scripts/start.js | 141 ++++ .../admin/add-permission-dialog.stories.tsx | 12 +- .../admin/create-role-dialog.stories.tsx | 9 +- .../admin/create-user-dialog.stories.tsx | 8 +- .../admin/drawer.stories.tsx | 9 +- .../dashboard/src/components/admin/drawer.tsx | 2 +- .../admin/manage-roles-dialog.stories.tsx | 11 +- .../admin/permissions-card.stories.tsx | 9 +- .../admin/role-list-card.stories.tsx | 11 +- .../tests/add-permission-dialog.test.tsx | 13 +- .../admin/tests/create-role-dialog.test.tsx | 9 +- .../admin/tests/create-user-dialog.test.tsx | 9 +- .../admin/tests/manage-roles-dialog.test.tsx | 7 +- .../admin/tests/permissions-card.test.tsx | 4 +- .../admin/tests/role-list-card.test.tsx | 4 +- .../admin/tests/user-list-card.test.tsx | 10 +- .../admin/tests/user-profile.test.tsx | 4 +- .../admin/user-list-card.stories.tsx | 9 +- .../admin/user-profile.stories.tsx | 8 +- packages/dashboard/src/components/appbar.tsx | 33 - .../src/components/delivery-alert-store.tsx | 42 +- .../dashboard/src/components/door-summary.tsx | 44 +- .../dashboard/src/components/doors-app.tsx | 5 +- .../dashboard/src/components/lift-summary.tsx | 28 +- .../dashboard/src/components/lifts-app.tsx | 3 +- packages/dashboard/src/components/map-app.tsx | 2 +- .../components/robots/robot-decommission.tsx | 22 +- .../src/components/robots/robot-summary.tsx | 22 +- .../components/tasks/task-cancellation.tsx | 32 +- .../components/tasks/task-schedule-utils.ts | 9 +- .../src/components/tasks/task-summary.tsx | 59 +- .../src/components/tasks/tasks-app.tsx | 30 +- .../dashboard/src/components/tasks/utils.ts | 25 +- .../src/components/tests/appbar.test.tsx | 18 +- .../src/components/three-fiber/door-three.tsx | 18 +- .../three-fiber/layer-control.test.tsx | 2 + packages/dashboard/src/components/utils.ts | 3 +- .../src/managers/resource-manager-logos.ts | 4 +- .../tests/resource-manager-robots.test.ts | 2 + packages/dashboard/src/setupTests.ts | 7 + .../src/util/common-subscriptions.ts | 7 +- .../lib/doors/door-table-datagrid.tsx | 72 +- .../lib/lifts/lift-table-datagrid.tsx | 43 +- .../lib/tasks/create-task.stories.tsx | 12 +- .../lib/tasks/create-task.tsx | 8 +- packages/react-components/lib/tasks/index.ts | 1 + .../lib/tasks/task-booking-label-utils.tsx | 2 +- .../lib/tasks/task-table-datagrid.tsx | 10 +- .../lib/tasks/task-timeline.tsx | 5 - packages/react-components/package.json | 1 + .../rmf-auth/lib/components/login.stories.tsx | 9 +- packages/rmf-auth/package.json | 1 + pnpm-lock.yaml | 52 +- 75 files changed, 2046 insertions(+), 425 deletions(-) delete mode 100644 packages/dashboard/.storybook/main.js create mode 100644 packages/dashboard/.storybook/main.ts delete mode 100644 packages/dashboard/.storybook/preview.js create mode 100644 packages/dashboard/.storybook/preview.ts create mode 100644 packages/dashboard/babel.config.js create mode 100644 packages/dashboard/config/env.js create mode 100644 packages/dashboard/config/getHttpsConfig.js create mode 100644 packages/dashboard/config/jest/babelTransform.js create mode 100644 packages/dashboard/config/jest/cssTransform.js create mode 100644 packages/dashboard/config/jest/fileTransform.js create mode 100644 packages/dashboard/config/modules.js create mode 100644 packages/dashboard/config/paths.js create mode 100644 packages/dashboard/config/webpack.config.js create mode 100644 packages/dashboard/config/webpack/persistentCache/createEnvironmentHash.js create mode 100644 packages/dashboard/config/webpackDevServer.config.js create mode 100644 packages/dashboard/scripts/build.js create mode 100644 packages/dashboard/scripts/start.js rename packages/dashboard/src/{stories => components}/admin/add-permission-dialog.stories.tsx (54%) rename packages/dashboard/src/{stories => components}/admin/create-role-dialog.stories.tsx (52%) rename packages/dashboard/src/{stories => components}/admin/create-user-dialog.stories.tsx (57%) rename packages/dashboard/src/{stories => components}/admin/drawer.stories.tsx (51%) rename packages/dashboard/src/{stories => components}/admin/manage-roles-dialog.stories.tsx (62%) rename packages/dashboard/src/{stories => components}/admin/permissions-card.stories.tsx (66%) rename packages/dashboard/src/{stories => components}/admin/role-list-card.stories.tsx (71%) rename packages/dashboard/src/{stories => components}/admin/user-list-card.stories.tsx (76%) rename packages/dashboard/src/{stories => components}/admin/user-profile.stories.tsx (75%) diff --git a/packages/api-client/lib/index.ts b/packages/api-client/lib/index.ts index 20c9d8594..423ecb6ac 100644 --- a/packages/api-client/lib/index.ts +++ b/packages/api-client/lib/index.ts @@ -4,6 +4,7 @@ import { Alert, BeaconState, BuildingMap, + DeliveryAlert, DispenserState, DoorState, FleetState, @@ -103,6 +104,10 @@ export class SioClient { subscribeAlerts(listener: Listener): Subscription { return this.subscribe(`/alerts`, listener); } + + subscribeDeliveryAlerts(listener: Listener): Subscription { + return this.subscribe('/delivery_alerts', listener); + } } export * from './openapi'; diff --git a/packages/api-client/lib/version.ts b/packages/api-client/lib/version.ts index 4aead4617..e92be8828 100644 --- a/packages/api-client/lib/version.ts +++ b/packages/api-client/lib/version.ts @@ -1,5 +1,5 @@ // THIS FILE IS GENERATED export const version = { - rmfServer: '4fe30cc47dcabe4d029fafc04f6d7feb52a11021', + rmfServer: '4484e98b95f71637026e2ce89d14d31033e5d615', openapiGenerator: '', }; diff --git a/packages/api-server/api_server/default_config.py b/packages/api-server/api_server/default_config.py index 6857f4bdc..76780d80d 100644 --- a/packages/api-server/api_server/default_config.py +++ b/packages/api-server/api_server/default_config.py @@ -9,7 +9,7 @@ # url that rmf-server is being served on. # When being a proxy, this must be the url that rmf-server is mounted on. # E.g. https://example.com/rmf/api/v1 - "public_url": "", + "public_url": "http://localhost:8000", "cache_directory": "run/cache", # The directory where cached files should be stored. "log_level": "WARNING", # https://docs.python.org/3.8/library/logging.html#levels # a user that is automatically given admin privileges, note that this does not guarantee that the user exists in the identity provider. diff --git a/packages/api-server/api_server/fast_io/__init__.py b/packages/api-server/api_server/fast_io/__init__.py index 60c744091..6126fc42f 100644 --- a/packages/api-server/api_server/fast_io/__init__.py +++ b/packages/api-server/api_server/fast_io/__init__.py @@ -14,7 +14,7 @@ from reactivex.abc import DisposableBase from starlette.routing import compile_path -from api_server.logging import LoggerAdapter, get_logger +from api_server.logging import LoggerAdapter, default_logger, get_logger from api_server.models.user import User from .errors import * diff --git a/packages/dashboard/.gitignore b/packages/dashboard/.gitignore index c98ec5ab9..abe6a5761 100644 --- a/packages/dashboard/.gitignore +++ b/packages/dashboard/.gitignore @@ -25,7 +25,7 @@ npm-debug.log* web_server.log -yarn-debug.log* -yarn-error.log* /.rmf + +*storybook.log diff --git a/packages/dashboard/.storybook/main.js b/packages/dashboard/.storybook/main.js deleted file mode 100644 index 4161676ca..000000000 --- a/packages/dashboard/.storybook/main.js +++ /dev/null @@ -1,13 +0,0 @@ -module.exports = { - stories: ['../src/**/*.stories.tsx'], - addons: [ - { - name: '@storybook/preset-create-react-app', - options: { - scriptsPackageName: 'react-scripts', - }, - }, - '@storybook/addon-essentials', - '@storybook/addon-links', - ], -}; diff --git a/packages/dashboard/.storybook/main.ts b/packages/dashboard/.storybook/main.ts new file mode 100644 index 000000000..695d85843 --- /dev/null +++ b/packages/dashboard/.storybook/main.ts @@ -0,0 +1,20 @@ +import type { StorybookConfig } from '@storybook/react-webpack5'; + +const config: StorybookConfig = { + stories: ['../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + addons: [ + '@storybook/addon-webpack5-compiler-babel', + '@storybook/addon-onboarding', + '@storybook/addon-links', + '@storybook/addon-essentials', + '@storybook/addon-interactions', + ], + framework: { + name: '@storybook/react-webpack5', + options: {}, + }, + docs: { + autodocs: 'tag', + }, +}; +export default config; diff --git a/packages/dashboard/.storybook/preview.js b/packages/dashboard/.storybook/preview.js deleted file mode 100644 index b285aacaf..000000000 --- a/packages/dashboard/.storybook/preview.js +++ /dev/null @@ -1,3 +0,0 @@ -export const parameters = { - actions: { argTypesRegex: '^on[A-Z].*' }, -}; diff --git a/packages/dashboard/.storybook/preview.ts b/packages/dashboard/.storybook/preview.ts new file mode 100644 index 000000000..adcda96bd --- /dev/null +++ b/packages/dashboard/.storybook/preview.ts @@ -0,0 +1,14 @@ +import type { Preview } from '@storybook/react'; + +const preview: Preview = { + parameters: { + controls: { + matchers: { + color: /(background|color)$/i, + date: /Date$/i, + }, + }, + }, +}; + +export default preview; diff --git a/packages/dashboard/babel.config.js b/packages/dashboard/babel.config.js new file mode 100644 index 000000000..4945818af --- /dev/null +++ b/packages/dashboard/babel.config.js @@ -0,0 +1,7 @@ +module.exports = { + presets: [ + '@babel/preset-env', + ['@babel/preset-react', { runtime: 'automatic' }], + '@babel/preset-typescript', + ], +}; diff --git a/packages/dashboard/config/env.js b/packages/dashboard/config/env.js new file mode 100644 index 000000000..c3104daa0 --- /dev/null +++ b/packages/dashboard/config/env.js @@ -0,0 +1,102 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const paths = require('./paths'); + +// Make sure that including paths.js after env.js will read .env variables. +delete require.cache[require.resolve('./paths')]; + +const NODE_ENV = process.env.NODE_ENV; +if (!NODE_ENV) { + throw new Error('The NODE_ENV environment variable is required but was not specified.'); +} + +// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use +const dotenvFiles = [ + `${paths.dotenv}.${NODE_ENV}.local`, + // Don't include `.env.local` for `test` environment + // since normally you expect tests to produce the same + // results for everyone + NODE_ENV !== 'test' && `${paths.dotenv}.local`, + `${paths.dotenv}.${NODE_ENV}`, + paths.dotenv, +].filter(Boolean); + +// Load environment variables from .env* files. Suppress warnings using silent +// if this file is missing. dotenv will never modify any environment variables +// that have already been set. Variable expansion is supported in .env files. +// https://github.com/motdotla/dotenv +// https://github.com/motdotla/dotenv-expand +dotenvFiles.forEach((dotenvFile) => { + if (fs.existsSync(dotenvFile)) { + require('dotenv-expand')( + require('dotenv').config({ + path: dotenvFile, + }), + ); + } +}); + +// We support resolving modules according to `NODE_PATH`. +// This lets you use absolute paths in imports inside large monorepos: +// https://github.com/facebook/create-react-app/issues/253. +// It works similar to `NODE_PATH` in Node itself: +// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders +// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. +// Otherwise, we risk importing Node.js core modules into an app instead of webpack shims. +// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421 +// We also resolve them to make sure all tools using them work consistently. +const appDirectory = fs.realpathSync(process.cwd()); +process.env.NODE_PATH = (process.env.NODE_PATH || '') + .split(path.delimiter) + .filter((folder) => folder && !path.isAbsolute(folder)) + .map((folder) => path.resolve(appDirectory, folder)) + .join(path.delimiter); + +// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be +// injected into the application via DefinePlugin in webpack configuration. +const REACT_APP = /^REACT_APP_/i; + +function getClientEnvironment(publicUrl) { + const raw = Object.keys(process.env) + .filter((key) => REACT_APP.test(key)) + .reduce( + (env, key) => { + env[key] = process.env[key]; + return env; + }, + { + // Useful for determining whether we’re running in production mode. + // Most importantly, it switches React into the correct mode. + NODE_ENV: process.env.NODE_ENV || 'development', + // Useful for resolving the correct path to static assets in `public`. + // For example, . + // This should only be used as an escape hatch. Normally you would put + // images into the `src` and `import` them in code to get their paths. + PUBLIC_URL: publicUrl, + // We support configuring the sockjs pathname during development. + // These settings let a developer run multiple simultaneous projects. + // They are used as the connection `hostname`, `pathname` and `port` + // in webpackHotDevClient. They are used as the `sockHost`, `sockPath` + // and `sockPort` options in webpack-dev-server. + WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST, + WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH, + WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT, + // Whether or not react-refresh is enabled. + // It is defined here so it is available in the webpackHotDevClient. + FAST_REFRESH: process.env.FAST_REFRESH !== 'false', + }, + ); + // Stringify all values so we can feed into webpack DefinePlugin + const stringified = { + 'process.env': Object.keys(raw).reduce((env, key) => { + env[key] = JSON.stringify(raw[key]); + return env; + }, {}), + }; + + return { raw, stringified }; +} + +module.exports = getClientEnvironment; diff --git a/packages/dashboard/config/getHttpsConfig.js b/packages/dashboard/config/getHttpsConfig.js new file mode 100644 index 000000000..3b1f63932 --- /dev/null +++ b/packages/dashboard/config/getHttpsConfig.js @@ -0,0 +1,60 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const chalk = require('react-dev-utils/chalk'); +const paths = require('./paths'); + +// Ensure the certificate and key provided are valid and if not +// throw an easy to debug error +function validateKeyAndCerts({ cert, key, keyFile, crtFile }) { + let encrypted; + try { + // publicEncrypt will throw an error with an invalid cert + encrypted = crypto.publicEncrypt(cert, Buffer.from('test')); + } catch (err) { + throw new Error(`The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}`); + } + + try { + // privateDecrypt will throw an error with an invalid key + crypto.privateDecrypt(key, encrypted); + } catch (err) { + throw new Error(`The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${err.message}`); + } +} + +// Read file and throw an error if it doesn't exist +function readEnvFile(file, type) { + if (!fs.existsSync(file)) { + throw new Error( + `You specified ${chalk.cyan(type)} in your env, but the file "${chalk.yellow( + file, + )}" can't be found.`, + ); + } + return fs.readFileSync(file); +} + +// Get the https config +// Return cert files if provided in env, otherwise just true or false +function getHttpsConfig() { + const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env; + const isHttps = HTTPS === 'true'; + + if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) { + const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE); + const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE); + const config = { + cert: readEnvFile(crtFile, 'SSL_CRT_FILE'), + key: readEnvFile(keyFile, 'SSL_KEY_FILE'), + }; + + validateKeyAndCerts({ ...config, keyFile, crtFile }); + return config; + } + return isHttps; +} + +module.exports = getHttpsConfig; diff --git a/packages/dashboard/config/jest/babelTransform.js b/packages/dashboard/config/jest/babelTransform.js new file mode 100644 index 000000000..5b391e405 --- /dev/null +++ b/packages/dashboard/config/jest/babelTransform.js @@ -0,0 +1,29 @@ +'use strict'; + +const babelJest = require('babel-jest').default; + +const hasJsxRuntime = (() => { + if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') { + return false; + } + + try { + require.resolve('react/jsx-runtime'); + return true; + } catch (e) { + return false; + } +})(); + +module.exports = babelJest.createTransformer({ + presets: [ + [ + require.resolve('babel-preset-react-app'), + { + runtime: hasJsxRuntime ? 'automatic' : 'classic', + }, + ], + ], + babelrc: false, + configFile: false, +}); diff --git a/packages/dashboard/config/jest/cssTransform.js b/packages/dashboard/config/jest/cssTransform.js new file mode 100644 index 000000000..8f6511481 --- /dev/null +++ b/packages/dashboard/config/jest/cssTransform.js @@ -0,0 +1,14 @@ +'use strict'; + +// This is a custom Jest transformer turning style imports into empty objects. +// http://facebook.github.io/jest/docs/en/webpack.html + +module.exports = { + process() { + return 'module.exports = {};'; + }, + getCacheKey() { + // The output is always the same. + return 'cssTransform'; + }, +}; diff --git a/packages/dashboard/config/jest/fileTransform.js b/packages/dashboard/config/jest/fileTransform.js new file mode 100644 index 000000000..aab67618c --- /dev/null +++ b/packages/dashboard/config/jest/fileTransform.js @@ -0,0 +1,40 @@ +'use strict'; + +const path = require('path'); +const camelcase = require('camelcase'); + +// This is a custom Jest transformer turning file imports into filenames. +// http://facebook.github.io/jest/docs/en/webpack.html + +module.exports = { + process(src, filename) { + const assetFilename = JSON.stringify(path.basename(filename)); + + if (filename.match(/\.svg$/)) { + // Based on how SVGR generates a component name: + // https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6 + const pascalCaseFilename = camelcase(path.parse(filename).name, { + pascalCase: true, + }); + const componentName = `Svg${pascalCaseFilename}`; + return `const React = require('react'); + module.exports = { + __esModule: true, + default: ${assetFilename}, + ReactComponent: React.forwardRef(function ${componentName}(props, ref) { + return { + $$typeof: Symbol.for('react.element'), + type: 'svg', + ref: ref, + key: null, + props: Object.assign({}, props, { + children: ${assetFilename} + }) + }; + }), + };`; + } + + return `module.exports = ${assetFilename};`; + }, +}; diff --git a/packages/dashboard/config/modules.js b/packages/dashboard/config/modules.js new file mode 100644 index 000000000..3d23a8b07 --- /dev/null +++ b/packages/dashboard/config/modules.js @@ -0,0 +1,136 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const paths = require('./paths'); +const chalk = require('react-dev-utils/chalk'); +const resolve = require('resolve'); + +/** + * Get additional module paths based on the baseUrl of a compilerOptions object. + * + * @param {Object} options + */ +function getAdditionalModulePaths(options = {}) { + const baseUrl = options.baseUrl; + + if (!baseUrl) { + return ''; + } + + const baseUrlResolved = path.resolve(paths.appPath, baseUrl); + + // We don't need to do anything if `baseUrl` is set to `node_modules`. This is + // the default behavior. + if (path.relative(paths.appNodeModules, baseUrlResolved) === '') { + return null; + } + + // Allow the user set the `baseUrl` to `appSrc`. + if (path.relative(paths.appSrc, baseUrlResolved) === '') { + return [paths.appSrc]; + } + + // If the path is equal to the root directory we ignore it here. + // We don't want to allow importing from the root directly as source files are + // not transpiled outside of `src`. We do allow importing them with the + // absolute path (e.g. `src/Components/Button.js`) but we set that up with + // an alias. + if (path.relative(paths.appPath, baseUrlResolved) === '') { + return null; + } + + // Otherwise, throw an error. + throw new Error( + chalk.red.bold( + "Your project's `baseUrl` can only be set to `src` or `node_modules`." + + ' Create React App does not support other values at this time.', + ), + ); +} + +/** + * Get webpack aliases based on the baseUrl of a compilerOptions object. + * + * @param {*} options + */ +function getWebpackAliases(options = {}) { + const baseUrl = options.baseUrl; + + if (!baseUrl) { + return {}; + } + + const baseUrlResolved = path.resolve(paths.appPath, baseUrl); + + if (path.relative(paths.appPath, baseUrlResolved) === '') { + return { + src: paths.appSrc, + }; + } +} + +/** + * Get jest aliases based on the baseUrl of a compilerOptions object. + * + * @param {*} options + */ +function getJestAliases(options = {}) { + const baseUrl = options.baseUrl; + + if (!baseUrl) { + return {}; + } + + const baseUrlResolved = path.resolve(paths.appPath, baseUrl); + + if (path.relative(paths.appPath, baseUrlResolved) === '') { + return { + '^src/(.*)$': '/src/$1', + }; + } +} + +function getModules() { + // Check if TypeScript is setup + const hasTsConfig = fs.existsSync(paths.appTsConfig); + const hasJsConfig = fs.existsSync(paths.appJsConfig); + + if (hasTsConfig && hasJsConfig) { + throw new Error( + 'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.', + ); + } + + let config; + + // If there's a tsconfig.json we assume it's a + // TypeScript project and set up the config + // based on tsconfig.json + if (hasTsConfig) { + const ts = require( + resolve.sync('typescript', { + basedir: paths.appNodeModules, + }), + ); + config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config; + // Otherwise we'll check if there is jsconfig.json + // for non TS projects. + } else if (hasJsConfig) { + config = require(paths.appJsConfig); + } + + config = config || {}; + const options = config.compilerOptions || {}; + + const additionalModulePaths = getAdditionalModulePaths(options); + + return { + additionalModulePaths: additionalModulePaths, + webpackAliases: getWebpackAliases(options), + jestAliases: getJestAliases(options), + hasTsConfig, + }; +} + +module.exports = getModules(); diff --git a/packages/dashboard/config/paths.js b/packages/dashboard/config/paths.js new file mode 100644 index 000000000..ff00e6e17 --- /dev/null +++ b/packages/dashboard/config/paths.js @@ -0,0 +1,75 @@ +'use strict'; + +const path = require('path'); +const fs = require('fs'); +const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath'); + +// Make sure any symlinks in the project folder are resolved: +// https://github.com/facebook/create-react-app/issues/637 +const appDirectory = fs.realpathSync(process.cwd()); +const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath); + +// We use `PUBLIC_URL` environment variable or "homepage" field to infer +// "public path" at which the app is served. +// webpack needs to know it to put the right