plugin.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. import { MiddlewareConsumer, NestModule } from '@nestjs/common';
  2. import {
  3. DEFAULT_AUTH_TOKEN_HEADER_KEY,
  4. DEFAULT_CHANNEL_TOKEN_KEY,
  5. } from '@vendure/common/lib/shared-constants';
  6. import {
  7. AdminUiAppConfig,
  8. AdminUiAppDevModeConfig,
  9. AdminUiConfig,
  10. Type,
  11. } from '@vendure/common/lib/shared-types';
  12. import {
  13. ConfigService,
  14. createProxyHandler,
  15. Logger,
  16. PluginCommonModule,
  17. ProcessContext,
  18. registerPluginStartupMessage,
  19. VendurePlugin,
  20. } from '@vendure/core';
  21. import express from 'express';
  22. import { rateLimit } from 'express-rate-limit';
  23. import fs from 'fs-extra';
  24. import path from 'path';
  25. import { adminApiExtensions } from './api/api-extensions';
  26. import { MetricsResolver } from './api/metrics.resolver';
  27. import {
  28. defaultAvailableLanguages,
  29. defaultLanguage,
  30. defaultLocale,
  31. DEFAULT_APP_PATH,
  32. loggerCtx,
  33. defaultAvailableLocales,
  34. } from './constants';
  35. import { MetricsService } from './service/metrics.service';
  36. /**
  37. * @description
  38. * Configuration options for the {@link AdminUiPlugin}.
  39. *
  40. * @docsCategory core plugins/AdminUiPlugin
  41. */
  42. export interface AdminUiPluginOptions {
  43. /**
  44. * @description
  45. * The route to the Admin UI.
  46. *
  47. * Note: If you are using the `compileUiExtensions` function to compile a custom version of the Admin UI, then
  48. * the route should match the `baseHref` option passed to that function. The default value of `baseHref` is `/admin/`,
  49. * so it only needs to be changed if you set this `route` option to something other than `"admin"`.
  50. */
  51. route: string;
  52. /**
  53. * @description
  54. * The port on which the server will listen. This port will be proxied by the AdminUiPlugin to the same port that
  55. * the Vendure server is running on.
  56. */
  57. port: number;
  58. /**
  59. * @description
  60. * The hostname of the server serving the static admin ui files.
  61. *
  62. * @default 'localhost'
  63. */
  64. hostname?: string;
  65. /**
  66. * @description
  67. * By default, the AdminUiPlugin comes bundles with a pre-built version of the
  68. * Admin UI. This option can be used to override this default build with a different
  69. * version, e.g. one pre-compiled with one or more ui extensions.
  70. */
  71. app?: AdminUiAppConfig | AdminUiAppDevModeConfig;
  72. /**
  73. * @description
  74. * Allows the contents of the `vendure-ui-config.json` file to be set, e.g.
  75. * for specifying the Vendure GraphQL API host, available UI languages, etc.
  76. */
  77. adminUiConfig?: Partial<AdminUiConfig>;
  78. }
  79. /**
  80. * @description
  81. * This plugin starts a static server for the Admin UI app, and proxies it via the `/admin/` path of the main Vendure server.
  82. *
  83. * The Admin UI allows you to administer all aspects of your store, from inventory management to order tracking. It is the tool used by
  84. * store administrators on a day-to-day basis for the management of the store.
  85. *
  86. * ## Installation
  87. *
  88. * `yarn add \@vendure/admin-ui-plugin`
  89. *
  90. * or
  91. *
  92. * `npm install \@vendure/admin-ui-plugin`
  93. *
  94. * @example
  95. * ```ts
  96. * import { AdminUiPlugin } from '\@vendure/admin-ui-plugin';
  97. *
  98. * const config: VendureConfig = {
  99. * // Add an instance of the plugin to the plugins array
  100. * plugins: [
  101. * AdminUiPlugin.init({ port: 3002 }),
  102. * ],
  103. * };
  104. * ```
  105. *
  106. * ## Metrics
  107. *
  108. * This plugin also defines a `metricSummary` query which is used by the Admin UI to display the order metrics on the dashboard.
  109. *
  110. * If you are building a stand-alone version of the Admin UI app, and therefore don't need this plugin to server the Admin UI,
  111. * you can still use the `metricSummary` query by adding the `AdminUiPlugin` to the `plugins` array, but without calling the `init()` method:
  112. *
  113. * @example
  114. * ```ts
  115. * import { AdminUiPlugin } from '\@vendure/admin-ui-plugin';
  116. *
  117. * const config: VendureConfig = {
  118. * plugins: [
  119. * AdminUiPlugin, // <-- no call to .init()
  120. * ],
  121. * // ...
  122. * };
  123. * ```
  124. *
  125. * @docsCategory core plugins/AdminUiPlugin
  126. */
  127. @VendurePlugin({
  128. imports: [PluginCommonModule],
  129. adminApiExtensions: {
  130. schema: adminApiExtensions,
  131. resolvers: [MetricsResolver],
  132. },
  133. providers: [MetricsService],
  134. compatibility: '^3.0.0',
  135. })
  136. export class AdminUiPlugin implements NestModule {
  137. private static options: AdminUiPluginOptions | undefined;
  138. constructor(
  139. private configService: ConfigService,
  140. private processContext: ProcessContext,
  141. ) {}
  142. /**
  143. * @description
  144. * Set the plugin options
  145. */
  146. static init(options: AdminUiPluginOptions): Type<AdminUiPlugin> {
  147. this.options = options;
  148. return AdminUiPlugin;
  149. }
  150. async configure(consumer: MiddlewareConsumer) {
  151. if (this.processContext.isWorker) {
  152. return;
  153. }
  154. if (!AdminUiPlugin.options) {
  155. Logger.info(
  156. `AdminUiPlugin's init() method was not called. The Admin UI will not be served.`,
  157. loggerCtx,
  158. );
  159. return;
  160. }
  161. const { app, hostname, route, adminUiConfig } = AdminUiPlugin.options;
  162. const adminUiAppPath = AdminUiPlugin.isDevModeApp(app)
  163. ? path.join(app.sourcePath, 'src')
  164. : (app && app.path) || DEFAULT_APP_PATH;
  165. const adminUiConfigPath = path.join(adminUiAppPath, 'vendure-ui-config.json');
  166. const indexHtmlPath = path.join(adminUiAppPath, 'index.html');
  167. const overwriteConfig = async () => {
  168. const uiConfig = this.getAdminUiConfig(adminUiConfig);
  169. await this.overwriteAdminUiConfig(adminUiConfigPath, uiConfig);
  170. await this.overwriteBaseHref(indexHtmlPath, route);
  171. };
  172. let port: number;
  173. if (AdminUiPlugin.isDevModeApp(app)) {
  174. port = app.port;
  175. } else {
  176. port = AdminUiPlugin.options.port;
  177. }
  178. if (AdminUiPlugin.isDevModeApp(app)) {
  179. Logger.info('Creating admin ui middleware (dev mode)', loggerCtx);
  180. consumer
  181. .apply(
  182. createProxyHandler({
  183. hostname,
  184. port,
  185. route,
  186. label: 'Admin UI',
  187. basePath: route,
  188. }),
  189. )
  190. .forRoutes(route);
  191. consumer
  192. .apply(
  193. createProxyHandler({
  194. hostname,
  195. port,
  196. route: 'sockjs-node',
  197. label: 'Admin UI live reload',
  198. basePath: 'sockjs-node',
  199. }),
  200. )
  201. .forRoutes('sockjs-node');
  202. Logger.info('Compiling Admin UI app in development mode', loggerCtx);
  203. app.compile().then(
  204. () => {
  205. Logger.info('Admin UI compiling and watching for changes...', loggerCtx);
  206. },
  207. (err: any) => {
  208. Logger.error(`Failed to compile: ${JSON.stringify(err)}`, loggerCtx, err.stack);
  209. },
  210. );
  211. await overwriteConfig();
  212. } else {
  213. Logger.info('Creating admin ui middleware (prod mode)', loggerCtx);
  214. consumer.apply(this.createStaticServer(app)).forRoutes(route);
  215. if (app && typeof app.compile === 'function') {
  216. Logger.info('Compiling Admin UI app in production mode...', loggerCtx);
  217. app.compile()
  218. .then(overwriteConfig)
  219. .then(
  220. () => {
  221. Logger.info('Admin UI successfully compiled', loggerCtx);
  222. },
  223. (err: any) => {
  224. Logger.error(`Failed to compile: ${JSON.stringify(err)}`, loggerCtx, err.stack);
  225. },
  226. );
  227. } else {
  228. await overwriteConfig();
  229. }
  230. }
  231. registerPluginStartupMessage('Admin UI', route);
  232. }
  233. private createStaticServer(app?: AdminUiAppConfig) {
  234. const adminUiAppPath = (app && app.path) || DEFAULT_APP_PATH;
  235. const limiter = rateLimit({
  236. windowMs: 60 * 1000,
  237. limit: process.env.NODE_ENV === 'production' ? 500 : 2000,
  238. standardHeaders: true,
  239. legacyHeaders: false,
  240. });
  241. const adminUiServer = express.Router();
  242. // This is a workaround for a type mismatch between express v5 (Vendure core)
  243. // and express v4 (several transitive dependencies). Can be removed once the
  244. // ecosystem has more significantly shifted to v5.
  245. adminUiServer.use(limiter as any);
  246. adminUiServer.use(express.static(adminUiAppPath));
  247. adminUiServer.use((req, res) => {
  248. res.sendFile(path.join(adminUiAppPath, 'index.html'));
  249. });
  250. return adminUiServer;
  251. }
  252. /**
  253. * Takes an optional AdminUiConfig provided in the plugin options, and returns a complete
  254. * config object for writing to disk.
  255. */
  256. private getAdminUiConfig(partialConfig?: Partial<AdminUiConfig>): AdminUiConfig {
  257. const { authOptions, apiOptions } = this.configService;
  258. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  259. const options = AdminUiPlugin.options!;
  260. const propOrDefault = <Prop extends keyof AdminUiConfig>(
  261. prop: Prop,
  262. defaultVal: AdminUiConfig[Prop],
  263. isArray: boolean = false,
  264. ): AdminUiConfig[Prop] => {
  265. if (isArray) {
  266. const isValidArray = !!partialConfig
  267. ? !!((partialConfig as AdminUiConfig)[prop] as any[])?.length
  268. : false;
  269. return !!partialConfig && isValidArray ? (partialConfig as AdminUiConfig)[prop] : defaultVal;
  270. } else {
  271. return partialConfig ? (partialConfig as AdminUiConfig)[prop] || defaultVal : defaultVal;
  272. }
  273. };
  274. return {
  275. adminApiPath: propOrDefault('adminApiPath', apiOptions.adminApiPath),
  276. apiHost: propOrDefault('apiHost', 'auto'),
  277. apiPort: propOrDefault('apiPort', 'auto'),
  278. tokenMethod: propOrDefault(
  279. 'tokenMethod',
  280. authOptions.tokenMethod === 'bearer' ? 'bearer' : 'cookie',
  281. ),
  282. authTokenHeaderKey: propOrDefault(
  283. 'authTokenHeaderKey',
  284. authOptions.authTokenHeaderKey || DEFAULT_AUTH_TOKEN_HEADER_KEY,
  285. ),
  286. channelTokenKey: propOrDefault(
  287. 'channelTokenKey',
  288. apiOptions.channelTokenKey || DEFAULT_CHANNEL_TOKEN_KEY,
  289. ),
  290. defaultLanguage: propOrDefault('defaultLanguage', defaultLanguage),
  291. defaultLocale: propOrDefault('defaultLocale', defaultLocale),
  292. availableLanguages: propOrDefault('availableLanguages', defaultAvailableLanguages, true),
  293. availableLocales: propOrDefault('availableLocales', defaultAvailableLocales, true),
  294. loginUrl: options.adminUiConfig?.loginUrl,
  295. brand: options.adminUiConfig?.brand,
  296. hideVendureBranding: propOrDefault(
  297. 'hideVendureBranding',
  298. options.adminUiConfig?.hideVendureBranding || false,
  299. ),
  300. hideVersion: propOrDefault('hideVersion', options.adminUiConfig?.hideVersion || false),
  301. loginImageUrl: options.adminUiConfig?.loginImageUrl,
  302. cancellationReasons: propOrDefault('cancellationReasons', undefined),
  303. };
  304. }
  305. /**
  306. * Overwrites the parts of the admin-ui app's `vendure-ui-config.json` file relating to connecting to
  307. * the server admin API.
  308. */
  309. private async overwriteAdminUiConfig(adminUiConfigPath: string, config: AdminUiConfig) {
  310. try {
  311. const content = await this.pollForFile(adminUiConfigPath);
  312. } catch (e: any) {
  313. Logger.error(e.message, loggerCtx);
  314. throw e;
  315. }
  316. try {
  317. await fs.writeFile(adminUiConfigPath, JSON.stringify(config, null, 2));
  318. } catch (e: any) {
  319. throw new Error(
  320. '[AdminUiPlugin] Could not write vendure-ui-config.json file:\n' + JSON.stringify(e.message),
  321. );
  322. }
  323. Logger.verbose('Applied configuration to vendure-ui-config.json file', loggerCtx);
  324. }
  325. /**
  326. * Overwrites the parts of the admin-ui app's `vendure-ui-config.json` file relating to connecting to
  327. * the server admin API.
  328. */
  329. private async overwriteBaseHref(indexHtmlPath: string, baseHref: string) {
  330. let indexHtmlContent: string;
  331. try {
  332. indexHtmlContent = await this.pollForFile(indexHtmlPath);
  333. } catch (e: any) {
  334. Logger.error(e.message, loggerCtx);
  335. throw e;
  336. }
  337. try {
  338. const withCustomBaseHref = indexHtmlContent.replace(
  339. /<base href=".+"\s*\/>/,
  340. `<base href="/${baseHref}/" />`,
  341. );
  342. await fs.writeFile(indexHtmlPath, withCustomBaseHref);
  343. } catch (e: any) {
  344. throw new Error('[AdminUiPlugin] Could not write index.html file:\n' + JSON.stringify(e.message));
  345. }
  346. Logger.verbose(`Applied baseHref "/${baseHref}/" to index.html file`, loggerCtx);
  347. }
  348. /**
  349. * It might be that the ui-devkit compiler has not yet copied the config
  350. * file to the expected location (particularly when running in watch mode),
  351. * so polling is used to check multiple times with a delay.
  352. */
  353. private async pollForFile(filePath: string) {
  354. const maxRetries = 10;
  355. const retryDelay = 200;
  356. let attempts = 0;
  357. const pause = () => new Promise(resolve => setTimeout(resolve, retryDelay));
  358. while (attempts < maxRetries) {
  359. try {
  360. Logger.verbose(`Checking for admin ui file: ${filePath}`, loggerCtx);
  361. const configFileContent = await fs.readFile(filePath, 'utf-8');
  362. return configFileContent;
  363. } catch (e: any) {
  364. attempts++;
  365. Logger.verbose(
  366. `Unable to locate admin ui file: ${filePath} (attempt ${attempts})`,
  367. loggerCtx,
  368. );
  369. }
  370. await pause();
  371. }
  372. throw new Error(`Unable to locate admin ui file: ${filePath}`);
  373. }
  374. private static isDevModeApp(
  375. app?: AdminUiAppConfig | AdminUiAppDevModeConfig,
  376. ): app is AdminUiAppDevModeConfig {
  377. if (!app) {
  378. return false;
  379. }
  380. return !!(app as AdminUiAppDevModeConfig).sourcePath;
  381. }
  382. }