plugin.ts 11 KB

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