plugin.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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 { getApiExtensions } from './api/api-extensions';
  26. import { MetricsResolver } from './api/metrics.resolver';
  27. import {
  28. DEFAULT_APP_PATH,
  29. defaultAvailableLanguages,
  30. defaultAvailableLocales,
  31. defaultLanguage,
  32. defaultLocale,
  33. loggerCtx,
  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. * @description
  80. * If you are running the AdminUiPlugin at the same time as the new `DashboardPlugin`, you should
  81. * set this to `true` in order to avoid a conflict caused by both plugins defining the same
  82. * schema extensions.
  83. *
  84. * @since 3.4.0
  85. */
  86. compatibilityMode?: boolean;
  87. }
  88. /**
  89. * @description
  90. *
  91. * :::warning Deprecated
  92. * From Vendure v3.5.0, the Angular-based Admin UI has been replaced by the new [React Admin Dashboard](/guides/extending-the-dashboard/getting-started/).
  93. * The Angular Admin UI will not be maintained after **July 2026**. Until then, we will continue patching critical bugs and security issues.
  94. * Community contributions will always be merged and released.
  95. * :::
  96. *
  97. * This plugin starts a static server for the Admin UI app, and proxies it via the `/admin/` path of the main Vendure server.
  98. *
  99. * The Admin UI allows you to administer all aspects of your store, from inventory management to order tracking. It is the tool used by
  100. * store administrators on a day-to-day basis for the management of the store.
  101. *
  102. * ## Installation
  103. *
  104. * `yarn add \@vendure/admin-ui-plugin`
  105. *
  106. * or
  107. *
  108. * `npm install \@vendure/admin-ui-plugin`
  109. *
  110. * @example
  111. * ```ts
  112. * import { AdminUiPlugin } from '\@vendure/admin-ui-plugin';
  113. *
  114. * const config: VendureConfig = {
  115. * // Add an instance of the plugin to the plugins array
  116. * plugins: [
  117. * AdminUiPlugin.init({ port: 3002 }),
  118. * ],
  119. * };
  120. * ```
  121. *
  122. * ## Metrics
  123. *
  124. * This plugin also defines a `metricSummary` query which is used by the Admin UI to display the order metrics on the dashboard.
  125. *
  126. * 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,
  127. * you can still use the `metricSummary` query by adding the `AdminUiPlugin` to the `plugins` array, but without calling the `init()` method:
  128. *
  129. * @example
  130. * ```ts
  131. * import { AdminUiPlugin } from '\@vendure/admin-ui-plugin';
  132. *
  133. * const config: VendureConfig = {
  134. * plugins: [
  135. * AdminUiPlugin, // <-- no call to .init()
  136. * ],
  137. * // ...
  138. * };
  139. * ```
  140. *
  141. * @docsCategory core plugins/AdminUiPlugin
  142. */
  143. @VendurePlugin({
  144. imports: [PluginCommonModule],
  145. adminApiExtensions: {
  146. schema: () => {
  147. const compatibilityMode = !!AdminUiPlugin.options?.compatibilityMode;
  148. return getApiExtensions(compatibilityMode);
  149. },
  150. resolvers: () => {
  151. const compatibilityMode = !!AdminUiPlugin.options?.compatibilityMode;
  152. return compatibilityMode ? [] : [MetricsResolver];
  153. },
  154. },
  155. providers: [MetricsService],
  156. compatibility: '^3.0.0',
  157. })
  158. export class AdminUiPlugin implements NestModule {
  159. private static options: AdminUiPluginOptions | undefined;
  160. constructor(
  161. private configService: ConfigService,
  162. private processContext: ProcessContext,
  163. ) {}
  164. /**
  165. * @description
  166. * Set the plugin options
  167. */
  168. static init(options: AdminUiPluginOptions): Type<AdminUiPlugin> {
  169. this.options = options;
  170. return AdminUiPlugin;
  171. }
  172. async configure(consumer: MiddlewareConsumer) {
  173. if (this.processContext.isWorker) {
  174. return;
  175. }
  176. if (!AdminUiPlugin.options) {
  177. Logger.info(
  178. `AdminUiPlugin's init() method was not called. The Admin UI will not be served.`,
  179. loggerCtx,
  180. );
  181. return;
  182. }
  183. const { app, hostname, route, adminUiConfig } = AdminUiPlugin.options;
  184. const adminUiAppPath = AdminUiPlugin.isDevModeApp(app)
  185. ? path.join(app.sourcePath, 'src')
  186. : (app && app.path) || DEFAULT_APP_PATH;
  187. const adminUiConfigPath = path.join(adminUiAppPath, 'vendure-ui-config.json');
  188. const indexHtmlPath = path.join(adminUiAppPath, 'index.html');
  189. const overwriteConfig = async () => {
  190. const uiConfig = this.getAdminUiConfig(adminUiConfig);
  191. await this.overwriteAdminUiConfig(adminUiConfigPath, uiConfig);
  192. await this.overwriteBaseHref(indexHtmlPath, route);
  193. };
  194. let port: number;
  195. if (AdminUiPlugin.isDevModeApp(app)) {
  196. port = app.port;
  197. } else {
  198. port = AdminUiPlugin.options.port;
  199. }
  200. if (AdminUiPlugin.isDevModeApp(app)) {
  201. Logger.info('Creating admin ui middleware (dev mode)', loggerCtx);
  202. consumer
  203. .apply(
  204. createProxyHandler({
  205. hostname,
  206. port,
  207. route,
  208. label: 'Admin UI',
  209. basePath: route,
  210. }),
  211. )
  212. .forRoutes(route);
  213. consumer
  214. .apply(
  215. createProxyHandler({
  216. hostname,
  217. port,
  218. route: 'sockjs-node',
  219. label: 'Admin UI live reload',
  220. basePath: 'sockjs-node',
  221. }),
  222. )
  223. .forRoutes('sockjs-node');
  224. Logger.info('Compiling Admin UI app in development mode', loggerCtx);
  225. app.compile().then(
  226. () => {
  227. Logger.info('Admin UI compiling and watching for changes...', loggerCtx);
  228. },
  229. (err: any) => {
  230. Logger.error(`Failed to compile: ${JSON.stringify(err)}`, loggerCtx, err.stack);
  231. },
  232. );
  233. await overwriteConfig();
  234. } else {
  235. Logger.info('Creating admin ui middleware (prod mode)', loggerCtx);
  236. consumer.apply(this.createStaticServer(app)).forRoutes(route);
  237. if (app && typeof app.compile === 'function') {
  238. Logger.info('Compiling Admin UI app in production mode...', loggerCtx);
  239. app.compile()
  240. .then(overwriteConfig)
  241. .then(
  242. () => {
  243. Logger.info('Admin UI successfully compiled', loggerCtx);
  244. },
  245. (err: any) => {
  246. Logger.error(`Failed to compile: ${JSON.stringify(err)}`, loggerCtx, err.stack);
  247. },
  248. );
  249. } else {
  250. await overwriteConfig();
  251. }
  252. }
  253. registerPluginStartupMessage('Admin UI', route);
  254. }
  255. private createStaticServer(app?: AdminUiAppConfig) {
  256. const adminUiAppPath = (app && app.path) || DEFAULT_APP_PATH;
  257. const limiter = rateLimit({
  258. windowMs: 60 * 1000,
  259. limit: process.env.NODE_ENV === 'production' ? 500 : 2000,
  260. standardHeaders: true,
  261. legacyHeaders: false,
  262. });
  263. const adminUiServer = express.Router();
  264. // This is a workaround for a type mismatch between express v5 (Vendure core)
  265. // and express v4 (several transitive dependencies). Can be removed once the
  266. // ecosystem has more significantly shifted to v5.
  267. adminUiServer.use(limiter as any);
  268. adminUiServer.use(express.static(adminUiAppPath));
  269. adminUiServer.use((req, res) => {
  270. res.sendFile('index.html', { root: adminUiAppPath });
  271. });
  272. return adminUiServer;
  273. }
  274. /**
  275. * Takes an optional AdminUiConfig provided in the plugin options, and returns a complete
  276. * config object for writing to disk.
  277. */
  278. private getAdminUiConfig(partialConfig?: Partial<AdminUiConfig>): AdminUiConfig {
  279. const { authOptions, apiOptions } = this.configService;
  280. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  281. const options = AdminUiPlugin.options!;
  282. const propOrDefault = <Prop extends keyof AdminUiConfig>(
  283. prop: Prop,
  284. defaultVal: AdminUiConfig[Prop],
  285. isArray: boolean = false,
  286. ): AdminUiConfig[Prop] => {
  287. if (isArray) {
  288. const isValidArray = !!partialConfig
  289. ? !!((partialConfig as AdminUiConfig)[prop] as any[])?.length
  290. : false;
  291. return !!partialConfig && isValidArray ? (partialConfig as AdminUiConfig)[prop] : defaultVal;
  292. } else {
  293. return partialConfig ? (partialConfig as AdminUiConfig)[prop] || defaultVal : defaultVal;
  294. }
  295. };
  296. return {
  297. adminApiPath: propOrDefault('adminApiPath', apiOptions.adminApiPath),
  298. apiHost: propOrDefault('apiHost', 'auto'),
  299. apiPort: propOrDefault('apiPort', 'auto'),
  300. tokenMethod: propOrDefault(
  301. 'tokenMethod',
  302. authOptions.tokenMethod === 'bearer' ? 'bearer' : 'cookie',
  303. ),
  304. authTokenHeaderKey: propOrDefault(
  305. 'authTokenHeaderKey',
  306. authOptions.authTokenHeaderKey || DEFAULT_AUTH_TOKEN_HEADER_KEY,
  307. ),
  308. channelTokenKey: propOrDefault(
  309. 'channelTokenKey',
  310. apiOptions.channelTokenKey || DEFAULT_CHANNEL_TOKEN_KEY,
  311. ),
  312. defaultLanguage: propOrDefault('defaultLanguage', defaultLanguage),
  313. defaultLocale: propOrDefault('defaultLocale', defaultLocale),
  314. availableLanguages: propOrDefault('availableLanguages', defaultAvailableLanguages, true),
  315. availableLocales: propOrDefault('availableLocales', defaultAvailableLocales, true),
  316. loginUrl: options.adminUiConfig?.loginUrl,
  317. brand: options.adminUiConfig?.brand,
  318. hideVendureBranding: propOrDefault(
  319. 'hideVendureBranding',
  320. options.adminUiConfig?.hideVendureBranding || false,
  321. ),
  322. hideVersion: propOrDefault('hideVersion', options.adminUiConfig?.hideVersion || false),
  323. loginImageUrl: options.adminUiConfig?.loginImageUrl,
  324. cancellationReasons: propOrDefault('cancellationReasons', undefined),
  325. };
  326. }
  327. /**
  328. * Overwrites the parts of the admin-ui app's `vendure-ui-config.json` file relating to connecting to
  329. * the server admin API.
  330. */
  331. private async overwriteAdminUiConfig(adminUiConfigPath: string, config: AdminUiConfig) {
  332. try {
  333. const content = await this.pollForFile(adminUiConfigPath);
  334. } catch (e: any) {
  335. Logger.error(e.message, loggerCtx);
  336. throw e;
  337. }
  338. try {
  339. await fs.writeFile(adminUiConfigPath, JSON.stringify(config, null, 2));
  340. } catch (e: any) {
  341. throw new Error(
  342. '[AdminUiPlugin] Could not write vendure-ui-config.json file:\n' + JSON.stringify(e.message),
  343. );
  344. }
  345. Logger.verbose('Applied configuration to vendure-ui-config.json file', loggerCtx);
  346. }
  347. /**
  348. * Overwrites the parts of the admin-ui app's `vendure-ui-config.json` file relating to connecting to
  349. * the server admin API.
  350. */
  351. private async overwriteBaseHref(indexHtmlPath: string, baseHref: string) {
  352. let indexHtmlContent: string;
  353. try {
  354. indexHtmlContent = await this.pollForFile(indexHtmlPath);
  355. } catch (e: any) {
  356. Logger.error(e.message, loggerCtx);
  357. throw e;
  358. }
  359. try {
  360. const withCustomBaseHref = indexHtmlContent.replace(
  361. /<base href=".+"\s*\/>/,
  362. `<base href="/${baseHref}/" />`,
  363. );
  364. await fs.writeFile(indexHtmlPath, withCustomBaseHref);
  365. } catch (e: any) {
  366. throw new Error('[AdminUiPlugin] Could not write index.html file:\n' + JSON.stringify(e.message));
  367. }
  368. Logger.verbose(`Applied baseHref "/${baseHref}/" to index.html file`, loggerCtx);
  369. }
  370. /**
  371. * It might be that the ui-devkit compiler has not yet copied the config
  372. * file to the expected location (particularly when running in watch mode),
  373. * so polling is used to check multiple times with a delay.
  374. */
  375. private async pollForFile(filePath: string) {
  376. const maxRetries = 10;
  377. const retryDelay = 200;
  378. let attempts = 0;
  379. const pause = () => new Promise(resolve => setTimeout(resolve, retryDelay));
  380. while (attempts < maxRetries) {
  381. try {
  382. Logger.verbose(`Checking for admin ui file: ${filePath}`, loggerCtx);
  383. const configFileContent = await fs.readFile(filePath, 'utf-8');
  384. return configFileContent;
  385. } catch (e: any) {
  386. attempts++;
  387. Logger.verbose(
  388. `Unable to locate admin ui file: ${filePath} (attempt ${attempts})`,
  389. loggerCtx,
  390. );
  391. }
  392. await pause();
  393. }
  394. throw new Error(`Unable to locate admin ui file: ${filePath}`);
  395. }
  396. private static isDevModeApp(
  397. app?: AdminUiAppConfig | AdminUiAppDevModeConfig,
  398. ): app is AdminUiAppDevModeConfig {
  399. if (!app) {
  400. return false;
  401. }
  402. return !!(app as AdminUiAppDevModeConfig).sourcePath;
  403. }
  404. }