plugin.ts 11 KB

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