helpers.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /* tslint:disable:no-console */
  2. import chalk from 'chalk';
  3. import { execSync } from 'child_process';
  4. import spawn from 'cross-spawn';
  5. import fs from 'fs-extra';
  6. import path from 'path';
  7. import semver from 'semver';
  8. import { SERVER_PORT, TYPESCRIPT_VERSION } from './constants';
  9. import { CliLogLevel, DbType } from './types';
  10. /**
  11. * If project only contains files generated by GH, it’s safe.
  12. * Also, if project contains remnant error logs from a previous
  13. * installation, lets remove them now.
  14. * We also special case IJ-based products .idea because it integrates with CRA:
  15. * https://github.com/facebook/create-react-app/pull/368#issuecomment-243446094
  16. */
  17. export function isSafeToCreateProjectIn(root: string, name: string) {
  18. // These files should be allowed to remain on a failed install,
  19. // but then silently removed during the next create.
  20. const errorLogFilePatterns = ['npm-debug.log', 'yarn-error.log', 'yarn-debug.log'];
  21. const validFiles = [
  22. '.DS_Store',
  23. 'Thumbs.db',
  24. '.git',
  25. '.gitignore',
  26. '.idea',
  27. 'README.md',
  28. 'LICENSE',
  29. '.hg',
  30. '.hgignore',
  31. '.hgcheck',
  32. '.npmignore',
  33. 'mkdocs.yml',
  34. 'docs',
  35. '.travis.yml',
  36. '.gitlab-ci.yml',
  37. '.gitattributes',
  38. 'migration.ts',
  39. 'node_modules',
  40. 'package.json',
  41. 'package-lock.json',
  42. 'src',
  43. 'static',
  44. 'tsconfig.json',
  45. 'yarn.lock',
  46. ];
  47. console.log();
  48. const conflicts = fs
  49. .readdirSync(root)
  50. .filter(file => !validFiles.includes(file))
  51. // IntelliJ IDEA creates module files before CRA is launched
  52. .filter(file => !/\.iml$/.test(file))
  53. // Don't treat log files from previous installation as conflicts
  54. .filter(file => !errorLogFilePatterns.some(pattern => file.indexOf(pattern) === 0));
  55. if (conflicts.length > 0) {
  56. console.log(`The directory ${chalk.green(name)} contains files that could conflict:`);
  57. console.log();
  58. for (const file of conflicts) {
  59. console.log(` ${file}`);
  60. }
  61. console.log();
  62. console.log('Either try using a new directory name, or remove the files listed above.');
  63. return false;
  64. }
  65. // Remove any remnant files from a previous installation
  66. const currentFiles = fs.readdirSync(path.join(root));
  67. currentFiles.forEach(file => {
  68. errorLogFilePatterns.forEach(errorLogFilePattern => {
  69. // This will catch `(npm-debug|yarn-error|yarn-debug).log*` files
  70. if (file.indexOf(errorLogFilePattern) === 0) {
  71. fs.removeSync(path.join(root, file));
  72. }
  73. });
  74. });
  75. return true;
  76. }
  77. export function scaffoldAlreadyExists(root: string, name: string): boolean {
  78. const scaffoldFiles = ['migration.ts', 'package.json', 'tsconfig.json', 'README.md'];
  79. const files = fs.readdirSync(root);
  80. return scaffoldFiles.every(scaffoldFile => files.includes(scaffoldFile));
  81. }
  82. export function checkNodeVersion(requiredVersion: string) {
  83. if (!semver.satisfies(process.version, requiredVersion)) {
  84. console.error(
  85. chalk.red(
  86. 'You are running Node %s.\n' +
  87. 'Vendure requires Node %s or higher. \n' +
  88. 'Please update your version of Node.',
  89. ),
  90. process.version,
  91. requiredVersion,
  92. );
  93. process.exit(1);
  94. }
  95. }
  96. export function shouldUseYarn() {
  97. try {
  98. execSync('yarnpkg --version', { stdio: 'ignore' });
  99. return true;
  100. } catch (e) {
  101. return false;
  102. }
  103. }
  104. export function checkThatNpmCanReadCwd() {
  105. const cwd = process.cwd();
  106. let childOutput = null;
  107. try {
  108. // Note: intentionally using spawn over exec since
  109. // the problem doesn't reproduce otherwise.
  110. // `npm config list` is the only reliable way I could find
  111. // to reproduce the wrong path. Just printing process.cwd()
  112. // in a Node process was not enough.
  113. childOutput = spawn.sync('npm', ['config', 'list']).output.join('');
  114. } catch (err) {
  115. // Something went wrong spawning node.
  116. // Not great, but it means we can't do this check.
  117. // We might fail later on, but let's continue.
  118. return true;
  119. }
  120. if (typeof childOutput !== 'string') {
  121. return true;
  122. }
  123. const lines = childOutput.split('\n');
  124. // `npm config list` output includes the following line:
  125. // "; cwd = C:\path\to\current\dir" (unquoted)
  126. // I couldn't find an easier way to get it.
  127. const prefix = '; cwd = ';
  128. const line = lines.find(l => l.indexOf(prefix) === 0);
  129. if (typeof line !== 'string') {
  130. // Fail gracefully. They could remove it.
  131. return true;
  132. }
  133. const npmCWD = line.substring(prefix.length);
  134. if (npmCWD === cwd) {
  135. return true;
  136. }
  137. console.error(
  138. chalk.red(
  139. `Could not start an npm process in the right directory.\n\n` +
  140. `The current directory is: ${chalk.bold(cwd)}\n` +
  141. `However, a newly started npm process runs in: ${chalk.bold(npmCWD)}\n\n` +
  142. `This is probably caused by a misconfigured system terminal shell.`,
  143. ),
  144. );
  145. if (process.platform === 'win32') {
  146. console.error(
  147. chalk.red(`On Windows, this can usually be fixed by running:\n\n`) +
  148. ` ${chalk.cyan(
  149. 'reg',
  150. )} delete "HKCU\\Software\\Microsoft\\Command Processor" /v AutoRun /f\n` +
  151. ` ${chalk.cyan(
  152. 'reg',
  153. )} delete "HKLM\\Software\\Microsoft\\Command Processor" /v AutoRun /f\n\n` +
  154. chalk.red(`Try to run the above two lines in the terminal.\n`) +
  155. chalk.red(
  156. `To learn more about this problem, read: https://blogs.msdn.microsoft.com/oldnewthing/20071121-00/?p=24433/`,
  157. ),
  158. );
  159. }
  160. return false;
  161. }
  162. /**
  163. * Install packages via npm or yarn.
  164. * Based on the install function from https://github.com/facebook/create-react-app
  165. */
  166. export function installPackages(
  167. root: string,
  168. useYarn: boolean,
  169. dependencies: string[],
  170. isDev: boolean,
  171. logLevel: CliLogLevel,
  172. isCi: boolean = false,
  173. ): Promise<void> {
  174. return new Promise((resolve, reject) => {
  175. let command: string;
  176. let args: string[];
  177. if (useYarn) {
  178. command = 'yarnpkg';
  179. args = ['add', '--exact', '--ignore-engines'];
  180. if (isDev) {
  181. args.push('--dev');
  182. }
  183. if (isCi) {
  184. // In CI, publish to Verdaccio
  185. // See https://github.com/yarnpkg/yarn/issues/6029
  186. args.push('--registry http://localhost:4873/');
  187. // Increase network timeout
  188. // See https://github.com/yarnpkg/yarn/issues/4890#issuecomment-358179301
  189. args.push('--network-timeout 300000');
  190. }
  191. args = args.concat(dependencies);
  192. // Explicitly set cwd() to work around issues like
  193. // https://github.com/facebook/create-react-app/issues/3326.
  194. // Unfortunately we can only do this for Yarn because npm support for
  195. // equivalent --prefix flag doesn't help with this issue.
  196. // This is why for npm, we run checkThatNpmCanReadCwd() early instead.
  197. args.push('--cwd');
  198. args.push(root);
  199. } else {
  200. command = 'npm';
  201. args = ['install', '--save', '--save-exact', '--loglevel', 'error'].concat(dependencies);
  202. if (isDev) {
  203. args.push('--save-dev');
  204. }
  205. }
  206. if (logLevel === 'verbose') {
  207. args.push('--verbose');
  208. }
  209. const child = spawn(command, args, { stdio: logLevel === 'silent' ? 'ignore' : 'inherit' });
  210. child.on('close', code => {
  211. if (code !== 0) {
  212. let message = 'An error occurred when installing dependencies.';
  213. if (logLevel === 'silent') {
  214. message += ' Try running with `--log-level info` or `--log-level verbose` to diagnose.';
  215. }
  216. reject({
  217. message,
  218. command: `${command} ${args.join(' ')}`,
  219. });
  220. return;
  221. }
  222. resolve();
  223. });
  224. });
  225. }
  226. export function getDependencies(
  227. usingTs: boolean,
  228. dbType: DbType,
  229. vendurePkgVersion = '',
  230. ): { dependencies: string[]; devDependencies: string[] } {
  231. const dependencies = [
  232. `@vendure/core${vendurePkgVersion}`,
  233. `@vendure/email-plugin${vendurePkgVersion}`,
  234. `@vendure/asset-server-plugin${vendurePkgVersion}`,
  235. `@vendure/admin-ui-plugin${vendurePkgVersion}`,
  236. dbDriverPackage(dbType),
  237. ];
  238. const devDependencies = ['concurrently'];
  239. if (usingTs) {
  240. devDependencies.push('ts-node');
  241. dependencies.push(`typescript@${TYPESCRIPT_VERSION}`);
  242. }
  243. return { dependencies, devDependencies };
  244. }
  245. /**
  246. * Returns the name of the npm driver package for the
  247. * selected database.
  248. */
  249. function dbDriverPackage(dbType: DbType): string {
  250. switch (dbType) {
  251. case 'mysql':
  252. case 'mariadb':
  253. return 'mysql';
  254. case 'postgres':
  255. return 'pg';
  256. case 'sqlite':
  257. return 'better-sqlite3';
  258. case 'sqljs':
  259. return 'sql.js';
  260. case 'mssql':
  261. return 'mssql';
  262. case 'oracle':
  263. return 'oracledb';
  264. default:
  265. const n: never = dbType;
  266. console.error(chalk.red(`No driver package configured for type "${dbType}"`));
  267. return '';
  268. }
  269. }
  270. /**
  271. * Checks that the specified DB connection options are working (i.e. a connection can be
  272. * established) and that the named database exists.
  273. */
  274. export function checkDbConnection(options: any, root: string): Promise<true> {
  275. switch (options.type) {
  276. case 'mysql':
  277. return checkMysqlDbExists(options, root);
  278. case 'postgres':
  279. return checkPostgresDbExists(options, root);
  280. default:
  281. return Promise.resolve(true);
  282. }
  283. }
  284. async function checkMysqlDbExists(options: any, root: string): Promise<true> {
  285. const mysql = await import(path.join(root, 'node_modules/mysql'));
  286. const connectionOptions = {
  287. host: options.host,
  288. user: options.username,
  289. password: options.password,
  290. port: options.port,
  291. database: options.database,
  292. };
  293. const connection = mysql.createConnection(connectionOptions);
  294. return new Promise<boolean>((resolve, reject) => {
  295. connection.connect((err: any) => {
  296. if (err) {
  297. if (err.code === 'ER_BAD_DB_ERROR') {
  298. throwDatabaseDoesNotExist(options.database);
  299. }
  300. throwConnectionError(err);
  301. }
  302. resolve(true);
  303. });
  304. }).then(() => {
  305. return new Promise((resolve, reject) => {
  306. connection.end((err: any) => {
  307. resolve(true);
  308. });
  309. });
  310. });
  311. }
  312. async function checkPostgresDbExists(options: any, root: string): Promise<true> {
  313. const { Client } = await import(path.join(root, 'node_modules/pg'));
  314. const connectionOptions = {
  315. host: options.host,
  316. user: options.username,
  317. password: options.password,
  318. port: options.port,
  319. database: options.database,
  320. schema: options.schema,
  321. };
  322. const client = new Client(connectionOptions);
  323. try {
  324. await client.connect();
  325. const schema = await client.query(
  326. `SELECT schema_name FROM information_schema.schemata WHERE schema_name = '${options.schema}'`,
  327. );
  328. if (schema.rows.length === 0) {
  329. throw new Error('NO_SCHEMA');
  330. }
  331. } catch (e) {
  332. if (e.code === '3D000') {
  333. throwDatabaseDoesNotExist(options.database);
  334. } else if (e.message === 'NO_SCHEMA') {
  335. throwDatabaseSchemaDoesNotExist(options.database, options.schema);
  336. }
  337. throwConnectionError(e);
  338. await client.end();
  339. throw e;
  340. }
  341. await client.end();
  342. return true;
  343. }
  344. function throwConnectionError(err: any) {
  345. throw new Error(
  346. `Could not connect to the database. ` +
  347. `Please check the connection settings in your Vendure config.\n[${
  348. err.message || err.toString()
  349. }]`,
  350. );
  351. }
  352. function throwDatabaseDoesNotExist(name: string) {
  353. throw new Error(`Database "${name}" does not exist. Please create the database and then try again.`);
  354. }
  355. function throwDatabaseSchemaDoesNotExist(dbName: string, schemaName: string) {
  356. throw new Error(
  357. `Schema "${dbName}.${schemaName}" does not exist. Please create the schema "${schemaName}" and then try again.`,
  358. );
  359. }
  360. export async function isServerPortInUse(): Promise<boolean> {
  361. const tcpPortUsed = require('tcp-port-used');
  362. try {
  363. return tcpPortUsed.check(SERVER_PORT);
  364. } catch (e) {
  365. console.log(chalk.yellow(`Warning: could not determine whether port ${SERVER_PORT} is available`));
  366. return false;
  367. }
  368. }