plugin.ts 13 KB

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