1 /*
2 * Adapted from https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-cli/src/init-starter.ts
3 */
4
5 import execa from "execa"
6 import { sync as existsSync } from "fs-exists-cached"
7 import fs from "fs-extra"
8 import hostedGitInfo from "hosted-git-info"
9 import isValid from "is-valid-path"
10 import sysPath from "path"
11 import prompts from "prompts"
12 import { Pool } from "@medusajs/deps/pg"
13 import url from "url"
14 import { track } from "@medusajs/telemetry"
15 // @ts-ignore
16 import inquirer from "inquirer"
17
18 import {
19 isNodeVersionSupported,
20 MIN_SUPPORTED_NODE_VERSION,
21 } from "@medusajs/utils"
22 import reporter from "../reporter"
23 import { PanicId } from "../reporter/panic-handler"
24 import { getPackageManager } from "../util/package-manager"
25
26 const STARTER_PATH = `medusajs/dtc-starter`
27
28 const removeUndefined = (obj) => {
29 return Object.fromEntries(
30 Object.entries(obj)
31 .filter(([_, v]) => v != null)
32 .map(([k, v]) => [k, v === Object(v) ? removeUndefined(v) : v])
33 )
34 }
35
36 const spawnWithArgs = async (file, args, options) =>
37 execa(file, args, { stdio: `inherit`, preferLocal: false, ...options })
38
39 const spawn = async (cmd, options) => {
40 const [file, ...args] = cmd.split(/\s+/)
41 return spawnWithArgs(file, args, options)
42 }
43
44 // Executes `pnpm install`, `yarn install`, or `npm install` in rootPath.
45 const install = async (rootPath: string) => {
46 const prevDir = process.cwd()
47
48 reporter.info(`Installing packages...`)
49 console.log() // Add some space
50
51 process.chdir(rootPath)
52
53 try {
54 await spawn(`pnpm install`, {})
55 } finally {
56 process.chdir(prevDir)
57 }
58 }
59
60 // Clones starter from URI.
61 const clone = async (rootPath: string, inputBranch?: string) => {
62 const hostedInfo = hostedGitInfo.fromUrl(STARTER_PATH)
63 let url
64 // Let people use private repos accessed over SSH.
65 if (hostedInfo.getDefaultRepresentation() === `sshurl`) {
66 url = hostedInfo.ssh({ noCommittish: true })
67 // Otherwise default to normal git syntax.
68 } else {
69 url = hostedInfo.https({ noCommittish: true, noGitPlus: true })
70 }
71
72 const branch = [`-b`, inputBranch || "main"]
73
74 const createAct = reporter.activity(`Creating new project from git: ${url}`)
75
76 const args = [
77 `clone`,
78 ...branch,
79 url,
80 rootPath,
81 `--recursive`,
82 `--depth=1`,
83 ].filter((arg) => Boolean(arg))
84
85 await execa(`git`, args, {})
86 .then(() => {
87 reporter.success(createAct, `Created starter directory layout`)
88 })
89 .catch((err) => {
90 reporter.failure(createAct, `Failed to clone repository`)
91 throw err
92 })
93
94 await fs.remove(sysPath.join(rootPath, `.git`))
95 await fs.remove(sysPath.join(rootPath, `.github`))
96
97 // remove storefront from monorepo
98 await fs.remove(sysPath.join(rootPath, `apps`, `storefront`))
99
100 await install(rootPath)
101 }
102
103 const getPaths = async (rootPath?: string) => {
104 // if no args are passed, prompt user for path and starter
105 if (!rootPath) {
106 const response = await prompts.prompt([
107 {
108 type: `text`,
109 name: `path`,
110 message: `What is your project called?`,
111 initial: `my-medusa-store`,
112 },
113 ])
114
115 // exit gracefully if responses aren't provided
116 if (!response.path.trim()) {
117 throw new Error(
118 `Please mention both starter package and project name along with path(if its not in the root)`
119 )
120 }
121
122 rootPath = response.path
123 }
124
125 // set defaults if no root or starter has been set yet
126 rootPath = rootPath || process.cwd()
127
128 return { rootPath }
129 }
130
131 const successMessage = (path) => {
132 reporter.info(`Your new Medusa project is ready for you! To start developing run:
133
134 cd ${path}
135 pnpm dev
136 `)
137 }
138
139 const defaultDBCreds = {
140 user: process.env.USER || "postgres",
141 database: "postgres",
142 password: "",
143 port: 5432,
144 host: "localhost",
145 }
146
147 const verifyPgCreds = async (creds) => {
148 const pool = new Pool(creds)
149 return new Promise((resolve, reject) => {
150 pool.query("SELECT NOW()", async (err, res) => {
151 await pool.end()
152 if (err) {
153 reject(err)
154 } else {
155 resolve(res)
156 }
157 })
158 })
159 }
160
161 const interactiveDbCreds = async (dbName, dbCreds = {}) => {
162 const credentials = Object.assign({}, defaultDBCreds, dbCreds)
163
164 const collecting = true
165
166 while (collecting) {
167 const result = await inquirer
168 .prompt([
169 {
170 type: "list",
171 name: "continueWithDefault",
172 message: `
173
174 Will attempt to setup Postgres database "${dbName}" with credentials:
175 user: ${credentials.user}
176 password: ***
177 port: ${credentials.port}
178 host: ${credentials.host}
179 Do you wish to continue with these credentials?
180
181 `,
182 choices: [`Continue`, `Change credentials`, `Skip database setup`],
183 },
184 {
185 type: "input",
186 when: ({ continueWithDefault }) =>
187 continueWithDefault === `Change credentials`,
188 name: "user",
189 default: credentials.user,
190 message: `DB user`,
191 },
192 {
193 type: "password",
194 when: ({ continueWithDefault }) =>
195 continueWithDefault === `Change credentials`,
196 name: "password",
197 default: credentials.password,
198 message: `DB password`,
199 },
200 {
201 type: "number",
202 when: ({ continueWithDefault }) =>
203 continueWithDefault === `Change credentials`,
204 name: "port",
205 default: credentials.port,
206 message: `DB port`,
207 },
208 {
209 type: "input",
210 when: ({ continueWithDefault }) =>
211 continueWithDefault === `Change credentials`,
212 name: "host",
213 default: credentials.host,
214 message: `DB host`,
215 },
216 ])
217 .then(async (answers) => {
218 const collectedCreds = Object.assign({}, credentials, {
219 user: answers.user,
220 password: answers.password,
221 host: answers.host,
222 port: answers.port,
223 })
224
225 switch (answers.continueWithDefault) {
226 case "Continue": {
227 const done = await verifyPgCreds(credentials).catch((_) => false)
228 if (done) {
229 return credentials
230 }
231 return false
232 }
233 case "Change credentials": {
234 const done = await verifyPgCreds(collectedCreds).catch((_) => false)
235 if (done) {
236 return collectedCreds
237 }
238 return false
239 }
240 default:
241 return null
242 }
243 })
244
245 if (result !== false) {
246 return result
247 }
248
249 console.log("\n\nCould not verify DB credentials - please try again\n\n")
250 }
251
252 return
253 }
254
255 export const createDatabase = async (dbName, credentials) => {
256 const pool = new Pool(credentials)
257 try {
258 // `dbName` is always internally generated (`medusa-db-<base36>`) and is never
259 // user-supplied, so interpolating it here is safe. CREATE DATABASE also cannot
260 // use a parameterized identifier, so interpolation is the only option.
261 await pool.query(`CREATE DATABASE "${dbName}"`)
262 } finally {
263 await pool.end()
264 }
265 }
266
267 export const setupDB = async (dbName, dbCreds = {}) => {
268 const credentials = Object.assign({}, defaultDBCreds, dbCreds)
269
270 const dbActivity = reporter.activity(`Setting up database "${dbName}"...`)
271 await createDatabase(dbName, credentials)
272 .then(() => {
273 reporter.success(dbActivity, `Created database "${dbName}"`)
274 })
275 .catch((err) => {
276 // Postgres raises 42P04 (duplicate_database) when the database already exists
277 if (err.code === "42P04") {
278 reporter.success(
279 dbActivity,
280 `Database ${dbName} already exists; skipping setup`
281 )
282 } else {
283 reporter.failure(dbActivity, `Skipping database setup.`)
284 reporter.warn(
285 `Failed to setup database; install PostgresQL or make sure to manage your database connection manually`
286 )
287 console.error(err)
288 }
289 })
290 }
291
292 const setupEnvVars = async (rootPath, dbName, dbCreds = {}) => {
293 const templatePath = sysPath.join(rootPath, ".env.template")
294 const destination = sysPath.join(rootPath, ".env")
295 if (existsSync(templatePath)) {
296 fs.renameSync(templatePath, destination)
297 }
298
299 const credentials = Object.assign({}, defaultDBCreds, dbCreds)
300 let dbUrl = ""
301 if (
302 credentials.user !== defaultDBCreds.user ||
303 credentials.password !== defaultDBCreds.password
304 ) {
305 dbUrl = `postgres://${credentials.user}:${credentials.password}@${credentials.host}:${credentials.port}/${dbName}`
306 } else {
307 dbUrl = `postgres://${credentials.host}:${credentials.port}/${dbName}`
308 }
309
310 fs.appendFileSync(destination, `DATABASE_URL=${dbUrl}\n`)
311 }
312
313 const runMigrations = async (rootPath) => {
314 const migrationActivity = reporter.activity("Applying database migrations...")
315
316 const cliPath = sysPath.join(
317 `node_modules`,
318 `@medusajs`,
319 `medusa-cli`,
320 `cli.js`
321 )
322
323 return await execa(cliPath, [`migrations`, `run`], {
324 cwd: rootPath,
325 })
326 .then(() => {
327 reporter.success(migrationActivity, "Database migrations completed.")
328 })
329 .catch((err) => {
330 reporter.failure(
331 migrationActivity,
332 "Failed to migrate database you must complete migration manually before starting your server."
333 )
334 console.error(err)
335 })
336 }
337
338 const attemptSeed = async (rootPath) => {
339 const seedActivity = reporter.activity("Seeding database")
340
341 const pkgPath = sysPath.resolve(rootPath, "package.json")
342 if (existsSync(pkgPath)) {
343 const pkg = require(pkgPath)
344 if (pkg.scripts && pkg.scripts.seed) {
345 const proc = execa(getPackageManager(), [`run`, `seed`], {
346 cwd: rootPath,
347 })
348
349 // Useful for development
350 // proc.stdout.pipe(process.stdout)
351
352 await proc
353 .then(() => {
354 reporter.success(seedActivity, "Seed completed")
355 })
356 .catch((err) => {
357 reporter.failure(seedActivity, "Failed to complete seed; skipping")
358 console.error(err)
359 })
360 } else {
361 reporter.failure(
362 seedActivity,
363 "Starter doesn't provide a seed command; skipping."
364 )
365 }
366 } else {
367 reporter.failure(seedActivity, "Could not find package.json")
368 }
369 }
370
371 type NewCommandArgs = {
372 root?: string
373 skipDb?: boolean
374 skipMigrations?: boolean
375 skipEnv?: boolean
376 seed?: boolean
377 useDefaults?: boolean
378 dbUser?: string
379 dbDatabase?: string
380 dbPass?: string
381 dbPort?: number
382 dbHost?: string
383 branch?: string
384 }
385
386 /**
387 * Main function that clones or copies the starter.
388 */
389 export const newStarter = async (args: NewCommandArgs) => {
390 if (!isNodeVersionSupported()) {
391 reporter.error(
392 `Medusa requires at least v${MIN_SUPPORTED_NODE_VERSION} of Node.js. You're using v${process.versions.node}. Please install v${MIN_SUPPORTED_NODE_VERSION} or later and try again: https://nodejs.org/en/download`
393 )
394 process.exit(1)
395 }
396 track("CLI_NEW")
397
398 const {
399 root,
400 skipDb,
401 skipMigrations,
402 skipEnv,
403 seed,
404 useDefaults,
405 dbUser,
406 dbDatabase,
407 dbPass,
408 dbPort,
409 dbHost,
410 branch,
411 } = args
412
413 const dbCredentials = removeUndefined({
414 user: dbUser,
415 database: dbDatabase,
416 password: dbPass,
417 port: dbPort,
418 host: dbHost,
419 })
420
421 const { rootPath } = await getPaths(root)
422
423 const urlObject = url.parse(rootPath)
424
425 if (urlObject.protocol && urlObject.host) {
426 if (/medusa-starter/gi.test(rootPath)) {
427 reporter.panic({
428 id: PanicId.InvalidProjectName,
429 context: {
430 starter: STARTER_PATH,
431 rootPath,
432 },
433 })
434 return
435 }
436
437 reporter.panic({
438 id: PanicId.InvalidProjectName,
439 context: {
440 rootPath,
441 },
442 })
443 return
444 }
445
446 if (!isValid(rootPath)) {
447 reporter.panic({
448 id: PanicId.InvalidPath,
449 context: {
450 path: sysPath.resolve(rootPath),
451 },
452 })
453 return
454 }
455
456 if (existsSync(sysPath.join(rootPath, `package.json`))) {
457 reporter.panic({
458 id: PanicId.AlreadyNodeProject,
459 context: {
460 rootPath,
461 },
462 })
463 return
464 }
465
466 await clone(rootPath, branch)
467
468 track("CLI_NEW_LAYOUT_COMPLETED")
469
470 let creds = dbCredentials
471
472 const dbName = `medusa-db-${Math.random().toString(36).substring(2, 7)}` // generate random 5 character string
473
474 if (!useDefaults && !skipDb && !skipEnv) {
475 creds = await interactiveDbCreds(dbName, dbCredentials)
476 }
477
478 if (creds === null) {
479 reporter.info(
480 "Skipping automatic database setup. Please note that you need to create a database and run migrations before you can run your Medusa backend"
481 )
482 } else {
483 if (!skipDb) {
484 track("CLI_NEW_SETUP_DB")
485 await setupDB(dbName, creds)
486 }
487
488 if (!skipEnv) {
489 track("CLI_NEW_SETUP_ENV")
490 await setupEnvVars(rootPath, dbName, creds)
491 }
492
493 if (!skipMigrations) {
494 track("CLI_NEW_RUN_MIGRATIONS")
495 await runMigrations(rootPath)
496 }
497
498 if (seed) {
499 track("CLI_NEW_SEED_DB")
500 await attemptSeed(rootPath)
501 }
502 }
503
504 successMessage(rootPath)
505 track("CLI_NEW_SUCCEEDED")
506 }