create-vendure-app.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. import { intro, note, outro, select, spinner } from '@clack/prompts';
  2. import { program } from 'commander';
  3. import fs from 'fs-extra';
  4. import { ChildProcess, spawn } from 'node:child_process';
  5. import { setTimeout as sleep } from 'node:timers/promises';
  6. import open from 'open';
  7. import os from 'os';
  8. import path from 'path';
  9. import pc from 'picocolors';
  10. import { REQUIRED_NODE_VERSION, SERVER_PORT } from './constants';
  11. import {
  12. getCiConfiguration,
  13. getManualConfiguration,
  14. getQuickStartConfiguration,
  15. } from './gather-user-responses';
  16. import {
  17. checkCancel,
  18. checkDbConnection,
  19. checkNodeVersion,
  20. checkThatNpmCanReadCwd,
  21. cleanUpDockerResources,
  22. getDependencies,
  23. installPackages,
  24. isSafeToCreateProjectIn,
  25. isServerPortInUse,
  26. resolvePackageRootDir,
  27. scaffoldAlreadyExists,
  28. startPostgresDatabase,
  29. } from './helpers';
  30. import { log, setLogLevel } from './logger';
  31. import { CliLogLevel, PackageManager } from './types';
  32. // eslint-disable-next-line @typescript-eslint/no-var-requires
  33. const packageJson = require('../package.json');
  34. checkNodeVersion(REQUIRED_NODE_VERSION);
  35. let projectName: string | undefined;
  36. // Set the environment variable which can then be used to
  37. // conditionally modify behaviour of core or plugins.
  38. const createEnvVar: import('@vendure/common/lib/shared-constants').CREATING_VENDURE_APP =
  39. 'CREATING_VENDURE_APP';
  40. process.env[createEnvVar] = 'true';
  41. program
  42. .version(packageJson.version)
  43. .arguments('<project-directory>')
  44. .usage(`${pc.green('<project-directory>')} [options]`)
  45. .action(name => {
  46. projectName = name;
  47. })
  48. .option(
  49. '--log-level <logLevel>',
  50. "Log level, either 'silent', 'info', or 'verbose'",
  51. /^(silent|info|verbose)$/i,
  52. 'info',
  53. )
  54. .option('--verbose', 'Alias for --log-level verbose', false)
  55. .option(
  56. '--use-npm',
  57. 'Uses npm rather than as the default package manager. DEPRECATED: Npm is now the default',
  58. )
  59. .option('--ci', 'Runs without prompts for use in CI scenarios', false)
  60. .parse(process.argv);
  61. const options = program.opts();
  62. void createVendureApp(
  63. projectName,
  64. options.useNpm,
  65. options.verbose ? 'verbose' : options.logLevel || 'info',
  66. options.ci,
  67. ).catch(err => {
  68. log(err);
  69. process.exit(1);
  70. });
  71. export async function createVendureApp(
  72. name: string | undefined,
  73. useNpm: boolean,
  74. logLevel: CliLogLevel,
  75. isCi: boolean = false,
  76. ) {
  77. setLogLevel(logLevel);
  78. if (!runPreChecks(name, useNpm)) {
  79. return;
  80. }
  81. intro(
  82. `Let's create a ${pc.blue(pc.bold('Vendure App'))} ✨ ${pc.dim(`v${packageJson.version as string}`)}`,
  83. );
  84. const mode = isCi
  85. ? 'ci'
  86. : ((await select({
  87. message: 'How should we proceed?',
  88. options: [
  89. { label: 'Quick Start', value: 'quick', hint: 'Get up an running in a single step' },
  90. {
  91. label: 'Manual Configuration',
  92. value: 'manual',
  93. hint: 'Customize your Vendure project with more advanced settings',
  94. },
  95. ],
  96. initialValue: 'quick' as 'quick' | 'manual',
  97. })) as 'quick' | 'manual');
  98. checkCancel(mode);
  99. const portSpinner = spinner();
  100. let port = SERVER_PORT;
  101. const attemptedPortRange = 20;
  102. portSpinner.start(`Establishing port...`);
  103. while (await isServerPortInUse(port)) {
  104. const nextPort = port + 1;
  105. portSpinner.message(pc.yellow(`Port ${port} is in use. Attempting to use ${nextPort}`));
  106. port = nextPort;
  107. if (port > SERVER_PORT + attemptedPortRange) {
  108. portSpinner.stop(pc.red('Could not find an available port'));
  109. outro(
  110. `Please ensure there is a port available between ${SERVER_PORT} and ${SERVER_PORT + attemptedPortRange}`,
  111. );
  112. process.exit(1);
  113. }
  114. }
  115. portSpinner.stop(`Using port ${port}`);
  116. process.env.PORT = port.toString();
  117. const root = path.resolve(name);
  118. const appName = path.basename(root);
  119. const scaffoldExists = scaffoldAlreadyExists(root, name);
  120. const packageManager: PackageManager = 'npm';
  121. if (scaffoldExists) {
  122. log(
  123. pc.yellow(
  124. 'It appears that a new Vendure project scaffold already exists. Re-using the existing files...',
  125. ),
  126. { newline: 'after' },
  127. );
  128. }
  129. const {
  130. dbType,
  131. configSource,
  132. envSource,
  133. envDtsSource,
  134. indexSource,
  135. indexWorkerSource,
  136. readmeSource,
  137. dockerfileSource,
  138. dockerComposeSource,
  139. populateProducts,
  140. } =
  141. mode === 'ci'
  142. ? await getCiConfiguration(root, packageManager)
  143. : mode === 'manual'
  144. ? await getManualConfiguration(root, packageManager)
  145. : await getQuickStartConfiguration(root, packageManager);
  146. process.chdir(root);
  147. if (packageManager !== 'npm' && !checkThatNpmCanReadCwd()) {
  148. process.exit(1);
  149. }
  150. const packageJsonContents = {
  151. name: appName,
  152. version: '0.1.0',
  153. private: true,
  154. scripts: {
  155. 'dev:server': 'ts-node ./src/index.ts',
  156. 'dev:worker': 'ts-node ./src/index-worker.ts',
  157. dev: 'concurrently npm:dev:*',
  158. build: 'tsc',
  159. 'start:server': 'node ./dist/index.js',
  160. 'start:worker': 'node ./dist/index-worker.js',
  161. start: 'concurrently npm:start:*',
  162. },
  163. };
  164. const setupSpinner = spinner();
  165. setupSpinner.start(
  166. `Setting up your new Vendure project in ${pc.green(root)}\nThis may take a few minutes...`,
  167. );
  168. const srcPathScript = (fileName: string): string => path.join(root, 'src', `${fileName}.ts`);
  169. fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify(packageJsonContents, null, 2) + os.EOL);
  170. const { dependencies, devDependencies } = getDependencies(dbType, `@${packageJson.version as string}`);
  171. setupSpinner.stop(`Created ${pc.green('package.json')}`);
  172. const installSpinner = spinner();
  173. installSpinner.start(`Installing ${dependencies[0]} + ${dependencies.length - 1} more dependencies`);
  174. try {
  175. await installPackages({ dependencies, logLevel });
  176. } catch (e) {
  177. outro(pc.red(`Failed to inst all dependencies. Please try again.`));
  178. process.exit(1);
  179. }
  180. installSpinner.stop(`Successfully installed ${dependencies.length} dependencies`);
  181. if (devDependencies.length) {
  182. const installDevSpinner = spinner();
  183. installDevSpinner.start(
  184. `Installing ${devDependencies[0]} + ${devDependencies.length - 1} more dev dependencies`,
  185. );
  186. try {
  187. await installPackages({ dependencies: devDependencies, isDevDependencies: true, logLevel });
  188. } catch (e) {
  189. outro(pc.red(`Failed to install dev dependencies. Please try again.`));
  190. process.exit(1);
  191. }
  192. installDevSpinner.stop(`Successfully installed ${devDependencies.length} dev dependencies`);
  193. }
  194. const scaffoldSpinner = spinner();
  195. scaffoldSpinner.start(`Generating app scaffold`);
  196. // We add this pause so that the above output is displayed before the
  197. // potentially lengthy file operations begin, which can prevent that
  198. // from displaying and thus make the user think that the process has hung.
  199. await sleep(500);
  200. fs.ensureDirSync(path.join(root, 'src'));
  201. const assetPath = (fileName: string) => path.join(__dirname, '../assets', fileName);
  202. const configFile = srcPathScript('vendure-config');
  203. try {
  204. await fs
  205. .writeFile(configFile, configSource)
  206. .then(() => fs.writeFile(path.join(root, '.env'), envSource))
  207. .then(() => fs.writeFile(srcPathScript('environment.d'), envDtsSource))
  208. .then(() => fs.writeFile(srcPathScript('index'), indexSource))
  209. .then(() => fs.writeFile(srcPathScript('index-worker'), indexWorkerSource))
  210. .then(() => fs.writeFile(path.join(root, 'README.md'), readmeSource))
  211. .then(() => fs.writeFile(path.join(root, 'Dockerfile'), dockerfileSource))
  212. .then(() => fs.writeFile(path.join(root, 'docker-compose.yml'), dockerComposeSource))
  213. .then(() => fs.ensureDir(path.join(root, 'src/plugins')))
  214. .then(() => fs.copyFile(assetPath('gitignore.template'), path.join(root, '.gitignore')))
  215. .then(() => fs.copyFile(assetPath('tsconfig.template.json'), path.join(root, 'tsconfig.json')))
  216. .then(() => createDirectoryStructure(root))
  217. .then(() => copyEmailTemplates(root));
  218. } catch (e: any) {
  219. outro(pc.red(`Failed to create app scaffold: ${e.message as string}`));
  220. process.exit(1);
  221. }
  222. scaffoldSpinner.stop(`Generated app scaffold`);
  223. if (mode === 'quick' && dbType === 'postgres') {
  224. cleanUpDockerResources(name);
  225. await startPostgresDatabase(root);
  226. }
  227. const populateSpinner = spinner();
  228. populateSpinner.start(`Initializing your new Vendure server`);
  229. // We want to display a set of tips and instructions to the user
  230. // as the initialization process is running because it can take
  231. // a few minutes to complete.
  232. const tips = [
  233. populateProducts
  234. ? 'We are populating sample data so that you can start testing right away'
  235. : 'We are setting up your Vendure server',
  236. '☕ This can take a minute or two, so grab a coffee',
  237. `✨ We'd love it if you drop us a star on GitHub: https://github.com/vendure-ecommerce/vendure`,
  238. `📖 Check out the Vendure documentation at https://docs.vendure.io`,
  239. `💬 Join our Discord community to chat with other Vendure developers: https://vendure.io/community`,
  240. '💡 In the mean time, here are some tips to get you started',
  241. `Vendure provides dedicated GraphQL APIs for both the Admin and Shop`,
  242. `Almost every aspect of Vendure is customizable via plugins`,
  243. `You can run 'vendure add' from the command line to add new plugins & features`,
  244. `Use the EventBus in your plugins to react to events in the system`,
  245. `Vendure supports multiple languages & currencies out of the box`,
  246. `☕ Did we mention this can take a while?`,
  247. `Our custom fields feature allows you to add any kind of data to your entities`,
  248. `Vendure is built with TypeScript, so you get full type safety`,
  249. `Combined with GraphQL's static schema, your type safety is end-to-end`,
  250. `☕ Almost there now... thanks for your patience!`,
  251. `Collections allow you to group products together`,
  252. `Our AssetServerPlugin allows you to dynamically resize & optimize images`,
  253. `Order flows are fully customizable to suit your business requirements`,
  254. `Role-based permissions allow you to control access to every part of the system`,
  255. `Customers can be grouped for targeted promotions & custom pricing`,
  256. `You can find integrations in the Vendure Hub: https://vendure.io/hub`,
  257. ];
  258. let tipIndex = 0;
  259. let timer: any;
  260. const tipInterval = 10_000;
  261. function displayTip() {
  262. populateSpinner.message(tips[tipIndex]);
  263. tipIndex++;
  264. if (tipIndex >= tips.length) {
  265. // skip the intro tips if looping
  266. tipIndex = 3;
  267. }
  268. timer = setTimeout(displayTip, tipInterval);
  269. }
  270. timer = setTimeout(displayTip, tipInterval);
  271. // register ts-node so that the config file can be loaded
  272. // eslint-disable-next-line @typescript-eslint/no-var-requires
  273. require(resolvePackageRootDir('ts-node')).register();
  274. let superAdminCredentials: { identifier: string; password: string } | undefined;
  275. try {
  276. const { populate } = await import(
  277. path.join(resolvePackageRootDir('@vendure/core'), 'cli', 'populate')
  278. );
  279. const { bootstrap, DefaultLogger, LogLevel, JobQueueService, ConfigModule } = await import(
  280. path.join(resolvePackageRootDir('@vendure/core'), 'dist', 'index')
  281. );
  282. const { config } = await import(configFile);
  283. const assetsDir = path.join(__dirname, '../assets');
  284. superAdminCredentials = config.authOptions.superadminCredentials;
  285. const initialDataPath = path.join(assetsDir, 'initial-data.json');
  286. const vendureLogLevel =
  287. logLevel === 'info' || logLevel === 'silent'
  288. ? LogLevel.Error
  289. : logLevel === 'verbose'
  290. ? LogLevel.Verbose
  291. : LogLevel.Info;
  292. const bootstrapFn = async () => {
  293. await checkDbConnection(config.dbConnectionOptions, root);
  294. const _app = await bootstrap({
  295. ...config,
  296. apiOptions: {
  297. ...(config.apiOptions ?? {}),
  298. port,
  299. },
  300. dbConnectionOptions: {
  301. ...config.dbConnectionOptions,
  302. synchronize: true,
  303. },
  304. logger: new DefaultLogger({ level: vendureLogLevel }),
  305. importExportOptions: {
  306. importAssetsDir: path.join(assetsDir, 'images'),
  307. },
  308. });
  309. await _app.get(JobQueueService).start();
  310. return _app;
  311. };
  312. const app = await populate(
  313. bootstrapFn,
  314. initialDataPath,
  315. populateProducts ? path.join(assetsDir, 'products.csv') : undefined,
  316. );
  317. // Pause to ensure the worker jobs have time to complete.
  318. if (isCi) {
  319. log('[CI] Pausing before close...');
  320. }
  321. await sleep(isCi ? 30000 : 2000);
  322. await app.close();
  323. if (isCi) {
  324. log('[CI] Pausing after close...');
  325. await sleep(10000);
  326. }
  327. populateSpinner.stop(`Server successfully initialized${populateProducts ? ' and populated' : ''}`);
  328. clearTimeout(timer);
  329. /**
  330. * This is currently disabled because I am running into issues actually getting the server
  331. * to quite properly in response to a SIGINT.
  332. * This means that the server runs, but cannot be ended, without forcefully
  333. * killing the process.
  334. *
  335. * Once this has been resolved, the following code can be re-enabled by
  336. * setting `autoRunServer` to `true`.
  337. */
  338. const autoRunServer = false;
  339. if (mode === 'quick' && autoRunServer) {
  340. // In quick-start mode, we want to now run the server and open up
  341. // a browser window to the Admin UI.
  342. try {
  343. const adminUiUrl = `http://localhost:${port}/admin`;
  344. const quickStartInstructions = [
  345. 'Use the following credentials to log in to the Admin UI:',
  346. `Username: ${pc.green(config.authOptions.superadminCredentials?.identifier)}`,
  347. `Password: ${pc.green(config.authOptions.superadminCredentials?.password)}`,
  348. `Open your browser and navigate to: ${pc.green(adminUiUrl)}`,
  349. '',
  350. ];
  351. note(quickStartInstructions.join('\n'));
  352. const npmCommand = os.platform() === 'win32' ? 'npm.cmd' : 'npm';
  353. let quickStartProcess: ChildProcess | undefined;
  354. try {
  355. quickStartProcess = spawn(npmCommand, ['run', 'dev'], {
  356. cwd: root,
  357. stdio: 'inherit',
  358. });
  359. } catch (e: any) {
  360. /* empty */
  361. }
  362. // process.stdin.resume();
  363. process.on('SIGINT', function () {
  364. displayOutro(root, name, superAdminCredentials);
  365. quickStartProcess?.kill('SIGINT');
  366. process.exit(0);
  367. });
  368. // Give enough time for the server to get up and running
  369. // before opening the window.
  370. await sleep(10_000);
  371. try {
  372. await open(adminUiUrl, {
  373. newInstance: true,
  374. });
  375. } catch (e: any) {
  376. /* empty */
  377. }
  378. } catch (e: any) {
  379. log(pc.red(`Failed to start the server: ${e.message as string}`), {
  380. newline: 'after',
  381. level: 'verbose',
  382. });
  383. }
  384. } else {
  385. clearTimeout(timer);
  386. displayOutro(root, name, superAdminCredentials);
  387. process.exit(0);
  388. }
  389. } catch (e: any) {
  390. log(e.toString());
  391. outro(pc.red(`Failed to initialize server. Please try again.`));
  392. process.exit(1);
  393. }
  394. }
  395. function displayOutro(
  396. root: string,
  397. name: string,
  398. superAdminCredentials?: { identifier: string; password: string },
  399. ) {
  400. const startCommand = 'npm run dev';
  401. const nextSteps = [
  402. `Your new Vendure server was created!`,
  403. pc.gray(root),
  404. `\n`,
  405. `Next, run:`,
  406. pc.gray('$ ') + pc.blue(pc.bold(`cd ${name}`)),
  407. pc.gray('$ ') + pc.blue(pc.bold(`${startCommand}`)),
  408. `\n`,
  409. `This will start the server in development mode.`,
  410. `To access the Admin UI, open your browser and navigate to:`,
  411. `\n`,
  412. pc.green(`http://localhost:3000/admin`),
  413. `\n`,
  414. `Use the following credentials to log in:`,
  415. `Username: ${pc.green(superAdminCredentials?.identifier ?? 'superadmin')}`,
  416. `Password: ${pc.green(superAdminCredentials?.password ?? 'superadmin')}`,
  417. '\n',
  418. '➡️ Docs: https://docs.vendure.io',
  419. '➡️ Discord community: https://vendure.io/community',
  420. '➡️ Star us on GitHub:',
  421. ' https://github.com/vendure-ecommerce/vendure',
  422. ];
  423. note(nextSteps.join('\n'), pc.green('Setup complete!'));
  424. outro(`Happy hacking!`);
  425. }
  426. /**
  427. * Run some initial checks to ensure that it is okay to proceed with creating
  428. * a new Vendure project in the given location.
  429. */
  430. function runPreChecks(name: string | undefined, useNpm: boolean): name is string {
  431. if (typeof name === 'undefined') {
  432. log(pc.red(`Please specify the project directory:`));
  433. log(` ${pc.cyan(program.name())} ${pc.green('<project-directory>')}`, { newline: 'after' });
  434. log('For example:');
  435. log(` ${pc.cyan(program.name())} ${pc.green('my-vendure-app')}`);
  436. process.exit(1);
  437. return false;
  438. }
  439. const root = path.resolve(name);
  440. try {
  441. fs.ensureDirSync(name);
  442. } catch (e: any) {
  443. log(pc.red(`Could not create project directory ${name}: ${e.message as string}`));
  444. return false;
  445. }
  446. if (!isSafeToCreateProjectIn(root, name)) {
  447. process.exit(1);
  448. }
  449. return true;
  450. }
  451. /**
  452. * Generate the default directory structure for a new Vendure project
  453. */
  454. async function createDirectoryStructure(root: string) {
  455. await fs.ensureDir(path.join(root, 'static', 'email', 'test-emails'));
  456. await fs.ensureDir(path.join(root, 'static', 'assets'));
  457. }
  458. /**
  459. * Copy the email templates into the app
  460. */
  461. async function copyEmailTemplates(root: string) {
  462. const emailPackageDirname = resolvePackageRootDir('@vendure/email-plugin');
  463. const templateDir = path.join(emailPackageDirname, 'templates');
  464. try {
  465. await fs.copy(templateDir, path.join(root, 'static', 'email', 'templates'));
  466. } catch (err: any) {
  467. log(pc.red('Failed to copy email templates.'));
  468. log(err);
  469. process.exit(0);
  470. }
  471. }