plugin.ts 12 KB

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