create-vendure-app.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /* tslint:disable:no-console */
  2. import chalk from 'chalk';
  3. import program from 'commander';
  4. import detectPort from 'detect-port';
  5. import fs from 'fs-extra';
  6. import Listr from 'listr';
  7. import os from 'os';
  8. import path from 'path';
  9. import { Observable } from 'rxjs';
  10. import { REQUIRED_NODE_VERSION, SERVER_PORT } from './constants';
  11. import { gatherCiUserResponses, gatherUserResponses } from './gather-user-responses';
  12. import {
  13. checkDbConnection,
  14. checkNodeVersion,
  15. checkThatNpmCanReadCwd,
  16. getDependencies,
  17. installPackages,
  18. isSafeToCreateProjectIn,
  19. isServerPortInUse,
  20. shouldUseYarn,
  21. } from './helpers';
  22. import { CliLogLevel } from './types';
  23. // tslint:disable-next-line:no-var-requires
  24. const packageJson = require('../package.json');
  25. checkNodeVersion(REQUIRED_NODE_VERSION);
  26. let projectName: string | undefined;
  27. // Set the environment variable which can then be used to
  28. // conditionally modify behaviour of core or plugins.
  29. const createEnvVar: import('@vendure/common/lib/shared-constants').CREATING_VENDURE_APP =
  30. 'CREATING_VENDURE_APP';
  31. process.env[createEnvVar] = 'true';
  32. program
  33. .version(packageJson.version)
  34. .arguments('<project-directory>')
  35. .usage(`${chalk.green('<project-directory>')} [options]`)
  36. .action(name => {
  37. projectName = name;
  38. })
  39. .option(
  40. '--log-level <logLevel>',
  41. `Log level, either 'silent', 'info', or 'verbose'`,
  42. /^(silent|info|verbose)$/i,
  43. 'silent',
  44. )
  45. .option('--use-npm', 'Uses npm rather than Yarn as the default package manager')
  46. .option('--ci', 'Runs without prompts for use in CI scenarios')
  47. .parse(process.argv);
  48. const options = program.opts();
  49. createApp(projectName, options.useNpm, options.logLevel || 'silent', options.ci);
  50. async function createApp(
  51. name: string | undefined,
  52. useNpm: boolean,
  53. logLevel: CliLogLevel,
  54. isCi: boolean = false,
  55. ) {
  56. if (!runPreChecks(name, useNpm)) {
  57. return;
  58. }
  59. if (await isServerPortInUse()) {
  60. console.log(chalk.red(`Port ${SERVER_PORT} is in use. Please make it available and then re-try.`));
  61. process.exit(1);
  62. }
  63. console.log(`Welcome to @vendure/create v${packageJson.version}!`);
  64. console.log();
  65. console.log(`Let's configure a new Vendure project. First a few questions:`);
  66. console.log();
  67. const root = path.resolve(name);
  68. const appName = path.basename(root);
  69. const {
  70. dbType,
  71. usingTs,
  72. configSource,
  73. indexSource,
  74. indexWorkerSource,
  75. migrationSource,
  76. readmeSource,
  77. populateProducts,
  78. } = isCi ? await gatherCiUserResponses(root) : await gatherUserResponses(root);
  79. const useYarn = useNpm ? false : shouldUseYarn();
  80. const originalDirectory = process.cwd();
  81. process.chdir(root);
  82. if (!useYarn && !checkThatNpmCanReadCwd()) {
  83. process.exit(1);
  84. }
  85. const packageJsonContents = {
  86. name: appName,
  87. version: '0.1.0',
  88. private: true,
  89. scripts: {
  90. 'run:server': usingTs ? 'ts-node ./src/index.ts' : 'node ./src/index.js',
  91. 'run:worker': usingTs ? 'ts-node ./src/index-worker.ts' : 'node ./src/index-worker.js',
  92. start: useYarn ? 'concurrently yarn:run:*' : 'concurrently npm:run:*',
  93. ...(usingTs ? { build: 'tsc' } : undefined),
  94. 'migration:generate': usingTs ? 'ts-node migration generate' : 'node migration generate',
  95. 'migration:run': usingTs ? 'ts-node migration run' : 'node migration run',
  96. 'migration:revert': usingTs ? 'ts-node migration revert' : 'node migration revert',
  97. },
  98. };
  99. console.log();
  100. console.log(`Setting up your new Vendure project in ${chalk.green(root)}`);
  101. console.log('This may take a few minutes...');
  102. console.log();
  103. const tasks = new Listr([
  104. {
  105. title: 'Installing dependencies',
  106. task: (() => {
  107. return new Observable(subscriber => {
  108. subscriber.next('Creating package.json');
  109. fs.writeFileSync(
  110. path.join(root, 'package.json'),
  111. JSON.stringify(packageJsonContents, null, 2) + os.EOL,
  112. );
  113. const { dependencies, devDependencies } = getDependencies(
  114. usingTs,
  115. dbType,
  116. isCi ? `@${packageJson.version}` : '',
  117. );
  118. subscriber.next(`Installing ${dependencies.join(', ')}`);
  119. installPackages(root, useYarn, dependencies, false, logLevel, isCi)
  120. .then(() => {
  121. if (devDependencies.length) {
  122. subscriber.next(`Installing ${devDependencies.join(', ')}`);
  123. return installPackages(root, useYarn, devDependencies, true, logLevel, isCi);
  124. }
  125. })
  126. .then(() => subscriber.complete())
  127. .catch(err => subscriber.error(err));
  128. });
  129. }) as any,
  130. },
  131. {
  132. title: 'Generating app scaffold',
  133. task: ctx => {
  134. return new Observable(subscriber => {
  135. fs.ensureDirSync(path.join(root, 'src'));
  136. const assetPath = (fileName: string) => path.join(__dirname, '../assets', fileName);
  137. const srcPathScript = (fileName: string): string =>
  138. path.join(root, 'src', `${fileName}.${usingTs ? 'ts' : 'js'}`);
  139. const rootPathScript = (fileName: string): string =>
  140. path.join(root, `${fileName}.${usingTs ? 'ts' : 'js'}`);
  141. ctx.configFile = srcPathScript('vendure-config');
  142. fs.writeFile(ctx.configFile, configSource)
  143. .then(() => fs.writeFile(srcPathScript('index'), indexSource))
  144. .then(() => fs.writeFile(srcPathScript('index-worker'), indexWorkerSource))
  145. .then(() => fs.writeFile(rootPathScript('migration'), migrationSource))
  146. .then(() => fs.writeFile(path.join(root, 'README.md'), readmeSource))
  147. .then(() =>
  148. fs.copyFile(assetPath('gitignore.template'), path.join(root, '.gitignore')),
  149. )
  150. .then(() => {
  151. subscriber.next(`Created files`);
  152. if (usingTs) {
  153. return fs.copyFile(
  154. assetPath('tsconfig.template.json'),
  155. path.join(root, 'tsconfig.json'),
  156. );
  157. }
  158. })
  159. .then(() => createDirectoryStructure(root))
  160. .then(() => {
  161. subscriber.next(`Created directory structure`);
  162. return copyEmailTemplates(root);
  163. })
  164. .then(() => {
  165. subscriber.next(`Copied email templates`);
  166. subscriber.complete();
  167. })
  168. .catch(err => subscriber.error(err));
  169. });
  170. },
  171. },
  172. {
  173. title: 'Initializing server',
  174. task: async ctx => {
  175. try {
  176. if (usingTs) {
  177. // register ts-node so that the config file can be loaded
  178. require(path.join(root, 'node_modules/ts-node')).register();
  179. }
  180. const { populate } = await import(
  181. path.join(root, 'node_modules/@vendure/core/cli/populate')
  182. );
  183. const { bootstrap, DefaultLogger, LogLevel, JobQueueService } = await import(
  184. path.join(root, 'node_modules/@vendure/core/dist/index')
  185. );
  186. const { config } = await import(ctx.configFile);
  187. const assetsDir = path.join(__dirname, '../assets');
  188. const initialDataPath = path.join(assetsDir, 'initial-data.json');
  189. const port = await detectPort(3000);
  190. const vendureLogLevel =
  191. logLevel === 'silent'
  192. ? LogLevel.Error
  193. : logLevel === 'verbose'
  194. ? LogLevel.Verbose
  195. : LogLevel.Info;
  196. const bootstrapFn = async () => {
  197. await checkDbConnection(config.dbConnectionOptions, root);
  198. const _app = await bootstrap({
  199. ...config,
  200. apiOptions: {
  201. ...(config.apiOptions ?? {}),
  202. port,
  203. },
  204. silent: logLevel === 'silent',
  205. dbConnectionOptions: {
  206. ...config.dbConnectionOptions,
  207. synchronize: true,
  208. },
  209. logger: new DefaultLogger({ level: vendureLogLevel }),
  210. importExportOptions: {
  211. importAssetsDir: path.join(assetsDir, 'images'),
  212. },
  213. });
  214. await _app.get(JobQueueService).start();
  215. return _app;
  216. };
  217. const app = await populate(
  218. bootstrapFn,
  219. initialDataPath,
  220. populateProducts ? path.join(assetsDir, 'products.csv') : undefined,
  221. );
  222. // Pause to ensure the worker jobs have time to complete.
  223. if (isCi) {
  224. console.log('[CI] Pausing before close...');
  225. }
  226. await new Promise(resolve => setTimeout(resolve, isCi ? 30000 : 2000));
  227. await app.close();
  228. if (isCi) {
  229. console.log('[CI] Pausing after close...');
  230. await new Promise(resolve => setTimeout(resolve, 10000));
  231. }
  232. } catch (e) {
  233. console.log(e);
  234. throw e;
  235. }
  236. },
  237. },
  238. ]);
  239. try {
  240. await tasks.run();
  241. } catch (e) {
  242. console.error(chalk.red(JSON.stringify(e)));
  243. process.exit(1);
  244. }
  245. const startCommand = useYarn ? 'yarn start' : 'npm run start';
  246. console.log();
  247. console.log(chalk.green(`Success! Created a new Vendure server at ${root}`));
  248. console.log();
  249. console.log(`We suggest that you start by typing:`);
  250. console.log();
  251. console.log(chalk.green(` cd ${name}`));
  252. console.log(chalk.green(` ${startCommand}`));
  253. console.log();
  254. console.log('Happy hacking!');
  255. process.exit(0);
  256. }
  257. /**
  258. * Run some initial checks to ensure that it is okay to proceed with creating
  259. * a new Vendure project in the given location.
  260. */
  261. function runPreChecks(name: string | undefined, useNpm: boolean): name is string {
  262. if (typeof name === 'undefined') {
  263. console.error('Please specify the project directory:');
  264. console.log(` ${chalk.cyan(program.name())} ${chalk.green('<project-directory>')}`);
  265. console.log();
  266. console.log('For example:');
  267. console.log(` ${chalk.cyan(program.name())} ${chalk.green('my-vendure-app')}`);
  268. process.exit(1);
  269. return false;
  270. }
  271. const root = path.resolve(name);
  272. fs.ensureDirSync(name);
  273. if (!isSafeToCreateProjectIn(root, name)) {
  274. process.exit(1);
  275. }
  276. return true;
  277. }
  278. /**
  279. * Generate the default directory structure for a new Vendure project
  280. */
  281. async function createDirectoryStructure(root: string) {
  282. await fs.ensureDir(path.join(root, 'static', 'email', 'test-emails'));
  283. await fs.ensureDir(path.join(root, 'static', 'assets'));
  284. }
  285. /**
  286. * Copy the email templates into the app
  287. */
  288. async function copyEmailTemplates(root: string) {
  289. const templateDir = path.join(root, 'node_modules/@vendure/email-plugin/templates');
  290. try {
  291. await fs.copy(templateDir, path.join(root, 'static', 'email', 'templates'));
  292. } catch (err) {
  293. console.error(chalk.red(`Failed to copy email templates.`));
  294. }
  295. }