helpers.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. /* eslint-disable no-console */
  2. import { execSync } from 'child_process';
  3. import spawn from 'cross-spawn';
  4. import fs from 'fs-extra';
  5. import path from 'path';
  6. import pc from 'picocolors';
  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 ${pc.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. pc.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: any) {
  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: any) {
  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. pc.red(
  139. 'Could not start an npm process in the right directory.\n\n' +
  140. `The current directory is: ${pc.bold(cwd)}\n` +
  141. `However, a newly started npm process runs in: ${pc.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. pc.red('On Windows, this can usually be fixed by running:\n\n') +
  148. ` ${pc.cyan('reg')} delete "HKCU\\Software\\Microsoft\\Command Processor" /v AutoRun /f\n` +
  149. ` ${pc.cyan(
  150. 'reg',
  151. )} delete "HKLM\\Software\\Microsoft\\Command Processor" /v AutoRun /f\n\n` +
  152. pc.red('Try to run the above two lines in the terminal.\n') +
  153. pc.red(
  154. 'To learn more about this problem, read: https://blogs.msdn.microsoft.com/oldnewthing/20071121-00/?p=24433/',
  155. ),
  156. );
  157. }
  158. return false;
  159. }
  160. /**
  161. * Install packages via npm or yarn.
  162. * Based on the install function from https://github.com/facebook/create-react-app
  163. */
  164. export function installPackages(
  165. root: string,
  166. useYarn: boolean,
  167. dependencies: string[],
  168. isDev: boolean,
  169. logLevel: CliLogLevel,
  170. isCi: boolean = false,
  171. ): Promise<void> {
  172. return new Promise((resolve, reject) => {
  173. let command: string;
  174. let args: string[];
  175. if (useYarn) {
  176. command = 'yarnpkg';
  177. args = ['add', '--exact', '--ignore-engines'];
  178. if (isDev) {
  179. args.push('--dev');
  180. }
  181. if (isCi) {
  182. // In CI, publish to Verdaccio
  183. // See https://github.com/yarnpkg/yarn/issues/6029
  184. args.push('--registry http://localhost:4873/');
  185. // Increase network timeout
  186. // See https://github.com/yarnpkg/yarn/issues/4890#issuecomment-358179301
  187. args.push('--network-timeout 300000');
  188. }
  189. args = args.concat(dependencies);
  190. // Explicitly set cwd() to work around issues like
  191. // https://github.com/facebook/create-react-app/issues/3326.
  192. // Unfortunately we can only do this for Yarn because npm support for
  193. // equivalent --prefix flag doesn't help with this issue.
  194. // This is why for npm, we run checkThatNpmCanReadCwd() early instead.
  195. args.push('--cwd');
  196. args.push(root);
  197. } else {
  198. command = 'npm';
  199. args = ['install', '--save', '--save-exact', '--loglevel', 'error'].concat(dependencies);
  200. if (isDev) {
  201. args.push('--save-dev');
  202. }
  203. }
  204. if (logLevel === 'verbose') {
  205. args.push('--verbose');
  206. }
  207. const child = spawn(command, args, { stdio: logLevel === 'silent' ? 'ignore' : 'inherit' });
  208. child.on('close', code => {
  209. if (code !== 0) {
  210. let message = 'An error occurred when installing dependencies.';
  211. if (logLevel === 'silent') {
  212. message += ' Try running with `--log-level info` or `--log-level verbose` to diagnose.';
  213. }
  214. reject({
  215. message,
  216. command: `${command} ${args.join(' ')}`,
  217. });
  218. return;
  219. }
  220. resolve();
  221. });
  222. });
  223. }
  224. export function getDependencies(
  225. dbType: DbType,
  226. vendurePkgVersion = '',
  227. ): { dependencies: string[]; devDependencies: string[] } {
  228. const dependencies = [
  229. `@vendure/core${vendurePkgVersion}`,
  230. `@vendure/email-plugin${vendurePkgVersion}`,
  231. `@vendure/asset-server-plugin${vendurePkgVersion}`,
  232. `@vendure/admin-ui-plugin${vendurePkgVersion}`,
  233. 'dotenv',
  234. dbDriverPackage(dbType),
  235. `typescript@${TYPESCRIPT_VERSION}`,
  236. ];
  237. const devDependencies = ['concurrently', 'ts-node'];
  238. return { dependencies, devDependencies };
  239. }
  240. /**
  241. * Returns the name of the npm driver package for the
  242. * selected database.
  243. */
  244. function dbDriverPackage(dbType: DbType): string {
  245. switch (dbType) {
  246. case 'mysql':
  247. case 'mariadb':
  248. return 'mysql';
  249. case 'postgres':
  250. return 'pg';
  251. case 'sqlite':
  252. return 'better-sqlite3';
  253. case 'sqljs':
  254. return 'sql.js';
  255. case 'mssql':
  256. return 'mssql';
  257. case 'oracle':
  258. return 'oracledb';
  259. default:
  260. const n: never = dbType;
  261. console.error(pc.red(`No driver package configured for type "${dbType as string}"`));
  262. return '';
  263. }
  264. }
  265. /**
  266. * Checks that the specified DB connection options are working (i.e. a connection can be
  267. * established) and that the named database exists.
  268. */
  269. export function checkDbConnection(options: any, root: string): Promise<true> {
  270. switch (options.type) {
  271. case 'mysql':
  272. return checkMysqlDbExists(options, root);
  273. case 'postgres':
  274. return checkPostgresDbExists(options, root);
  275. default:
  276. return Promise.resolve(true);
  277. }
  278. }
  279. async function checkMysqlDbExists(options: any, root: string): Promise<true> {
  280. const mysql = await import(path.join(root, 'node_modules/mysql'));
  281. const connectionOptions = {
  282. host: options.host,
  283. user: options.username,
  284. password: options.password,
  285. port: options.port,
  286. database: options.database,
  287. };
  288. const connection = mysql.createConnection(connectionOptions);
  289. return new Promise<boolean>((resolve, reject) => {
  290. connection.connect((err: any) => {
  291. if (err) {
  292. if (err.code === 'ER_BAD_DB_ERROR') {
  293. throwDatabaseDoesNotExist(options.database);
  294. }
  295. throwConnectionError(err);
  296. }
  297. resolve(true);
  298. });
  299. }).then(() => {
  300. return new Promise((resolve, reject) => {
  301. connection.end((err: any) => {
  302. resolve(true);
  303. });
  304. });
  305. });
  306. }
  307. async function checkPostgresDbExists(options: any, root: string): Promise<true> {
  308. const { Client } = await import(path.join(root, 'node_modules/pg'));
  309. const connectionOptions = {
  310. host: options.host,
  311. user: options.username,
  312. password: options.password,
  313. port: options.port,
  314. database: options.database,
  315. schema: options.schema,
  316. };
  317. const client = new Client(connectionOptions);
  318. try {
  319. await client.connect();
  320. const schema = await client.query(
  321. `SELECT schema_name FROM information_schema.schemata WHERE schema_name = '${
  322. options.schema as string
  323. }'`,
  324. );
  325. if (schema.rows.length === 0) {
  326. throw new Error('NO_SCHEMA');
  327. }
  328. } catch (e: any) {
  329. if (e.code === '3D000') {
  330. throwDatabaseDoesNotExist(options.database);
  331. } else if (e.message === 'NO_SCHEMA') {
  332. throwDatabaseSchemaDoesNotExist(options.database, options.schema);
  333. }
  334. throwConnectionError(e);
  335. await client.end();
  336. throw e;
  337. }
  338. await client.end();
  339. return true;
  340. }
  341. function throwConnectionError(err: any) {
  342. throw new Error(
  343. 'Could not connect to the database. ' +
  344. `Please check the connection settings in your Vendure config.\n[${
  345. (err.message || err.toString()) as string
  346. }]`,
  347. );
  348. }
  349. function throwDatabaseDoesNotExist(name: string) {
  350. throw new Error(`Database "${name}" does not exist. Please create the database and then try again.`);
  351. }
  352. function throwDatabaseSchemaDoesNotExist(dbName: string, schemaName: string) {
  353. throw new Error(
  354. `Schema "${dbName}.${schemaName}" does not exist. Please create the schema "${schemaName}" and then try again.`,
  355. );
  356. }
  357. export function isServerPortInUse(): Promise<boolean> {
  358. // eslint-disable-next-line @typescript-eslint/no-var-requires
  359. const tcpPortUsed = require('tcp-port-used');
  360. try {
  361. return tcpPortUsed.check(SERVER_PORT);
  362. } catch (e: any) {
  363. console.log(pc.yellow(`Warning: could not determine whether port ${SERVER_PORT} is available`));
  364. return Promise.resolve(false);
  365. }
  366. }