create-vendure-app.ts 12 KB

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