create-vendure-app.ts 13 KB

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