1 import fs from "fs"
2 import path from "path"
3 import { randomBytes } from "crypto"
4 import { Ora } from "ora"
5 import { ExecuteResult } from "./execute.js"
6 import { EOL } from "os"
7 import { displayFactBox, FactBoxOptions } from "./facts.js"
8 import ProcessManager from "./process-manager.js"
9 import type { Client } from "@medusajs/deps/pg"
10 import PackageManager from "./package-manager.js"
11 import { updatePackageVersions } from "./update-package-versions.js"
12 import { getBackendDirectory } from "./project-paths.js"
13
14 const ADMIN_EMAIL = "admin@medusa-test.com"
15 let STORE_CORS = "http://localhost:8000"
16 let ADMIN_CORS = "http://localhost:5173,http://localhost:9000"
17 const DOCS_CORS = "https://docs.medusajs.com"
18 const AUTH_CORS = [ADMIN_CORS, STORE_CORS, DOCS_CORS].join(",")
19 STORE_CORS += `,${DOCS_CORS}`
20 ADMIN_CORS += `,${DOCS_CORS}`
21 const DEFAULT_REDIS_URL = "redis://localhost:6379"
22 const AUTH_MFA_ENCRYPTION_KEY = "AUTH_MFA_ENCRYPTION_KEY"
23
24 type PreparePluginOptions = {
25 isPlugin: true
26 directory: string
27 projectName: string
28 spinner: Ora
29 processManager: ProcessManager
30 abortController?: AbortController
31 verbose?: boolean
32 packageManager: PackageManager
33 }
34
35 type PrepareProjectOptions = {
36 isPlugin: false
37 directory: string
38 dbName?: string
39 dbConnectionString: string
40 projectName: string
41 // TODO add the option to disable seeding. For now, it's enabled by default.
42 seed?: boolean
43 spinner: Ora
44 processManager: ProcessManager
45 abortController?: AbortController
46 skipDb?: boolean
47 migrations?: boolean
48 onboardingType?: "default" | "nextjs"
49 nextjsDirectory?: string
50 client: Client | null
51 verbose?: boolean
52 packageManager: PackageManager
53 version?: string
54 }
55
56 type PrepareOptions = PreparePluginOptions | PrepareProjectOptions
57
58 export default async <
59 T extends PrepareOptions,
60 Output = T extends { isPlugin: true } ? void : string | undefined
61 >(
62 prepareOptions: T
63 ): Promise<Output> => {
64 if (prepareOptions.isPlugin) {
65 return preparePlugin(prepareOptions) as Output
66 }
67
68 return prepareProject(prepareOptions) as Output
69 }
70
71 async function preparePlugin({
72 directory,
73 projectName,
74 spinner,
75 processManager,
76 abortController,
77 verbose = false,
78 packageManager,
79 }: PreparePluginOptions) {
80 // initialize execution options
81 const execOptions = {
82 cwd: directory,
83 signal: abortController?.signal,
84 }
85
86 const factBoxOptions: FactBoxOptions = {
87 interval: null,
88 spinner,
89 processManager,
90 message: "",
91 title: "",
92 verbose,
93 }
94
95 // Update package.json
96 const packageJsonPath = path.join(directory, "package.json")
97 const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"))
98
99 // Update name
100 packageJson.name = projectName
101
102 // Add packageManager field to ensure consistent version usage
103 const packageManagerString = await packageManager.getPackageManagerString()
104 if (packageManagerString) {
105 packageJson.packageManager = packageManagerString
106 }
107
108 fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
109
110 factBoxOptions.interval = displayFactBox({
111 ...factBoxOptions,
112 spinner,
113 title: "Installing dependencies...",
114 processManager,
115 })
116
117 await packageManager.installDependencies(execOptions)
118
119 factBoxOptions.interval = displayFactBox({
120 ...factBoxOptions,
121 message: "Installed Dependencies",
122 })
123
124 displayFactBox({ ...factBoxOptions, message: "Finished Preparation" })
125 }
126
127 async function prepareProject({
128 directory,
129 projectName,
130 dbName,
131 dbConnectionString,
132 seed,
133 spinner,
134 processManager,
135 abortController,
136 skipDb,
137 migrations,
138 onboardingType = "default",
139 nextjsDirectory = "",
140 client,
141 verbose = false,
142 packageManager,
143 version,
144 }: PrepareProjectOptions) {
145 const backendDirectory = getBackendDirectory(directory)
146
147 // initialize execution options
148 const execOptions = {
149 cwd: directory,
150 signal: abortController?.signal,
151 }
152
153 const backendExecOptions = {
154 cwd: backendDirectory,
155 signal: abortController?.signal,
156 }
157
158 const npxOptions = {
159 ...backendExecOptions,
160 env: {
161 ...process.env,
162 npm_config_yes: "yes",
163 },
164 }
165
166 const factBoxOptions: FactBoxOptions = {
167 interval: null,
168 spinner,
169 processManager,
170 message: "",
171 title: "",
172 verbose,
173 }
174
175 // Add packageManager field to ensure consistent version usage
176 const packageManagerString = await packageManager.getPackageManagerString()
177
178 // Update root package.json name and packageManager
179 const packageJsonPath = path.join(directory, "package.json")
180 const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"))
181 packageJson.name = projectName
182 if (packageManagerString) {
183 packageJson.packageManager = packageManagerString
184 } else {
185 delete packageJson.packageManager
186 }
187 fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
188
189 // Update backend package.json
190 const backendPackageJsonPath = path.join(backendDirectory, "package.json")
191 const backendPackageJson = JSON.parse(
192 fs.readFileSync(backendPackageJsonPath, "utf-8")
193 )
194
195 if (packageManagerString) {
196 backendPackageJson.packageManager = packageManagerString
197 }
198
199 // Update medusa dependencies versions
200 if (version) {
201 updatePackageVersions(backendPackageJson, version)
202 }
203
204 fs.writeFileSync(
205 backendPackageJsonPath,
206 JSON.stringify(backendPackageJson, null, 2)
207 )
208
209 // initialize the invite token to return
210 let inviteToken: string | undefined = undefined
211
212 // add environment variables
213 let env = `MEDUSA_ADMIN_ONBOARDING_TYPE=${onboardingType}${EOL}STORE_CORS=${STORE_CORS}${EOL}ADMIN_CORS=${ADMIN_CORS}${EOL}AUTH_CORS=${AUTH_CORS}${EOL}REDIS_URL=${DEFAULT_REDIS_URL}${EOL}JWT_SECRET=supersecret${EOL}COOKIE_SECRET=supersecret${EOL}${AUTH_MFA_ENCRYPTION_KEY}=${randomBytes(
214 32
215 ).toString("hex")}`
216
217 if (!skipDb) {
218 if (dbName) {
219 env += `${EOL}DB_NAME=${dbName}`
220 dbConnectionString = dbConnectionString!.replace(dbName, "$DB_NAME")
221 }
222 env += `${EOL}DATABASE_URL=${dbConnectionString}`
223 }
224
225 if (nextjsDirectory) {
226 env += `${EOL}MEDUSA_ADMIN_ONBOARDING_NEXTJS_DIRECTORY=${nextjsDirectory}`
227 }
228
229 fs.appendFileSync(path.join(backendDirectory, `.env`), env)
230
231 factBoxOptions.interval = displayFactBox({
232 ...factBoxOptions,
233 spinner,
234 title: "Installing dependencies...",
235 processManager,
236 })
237
238 await packageManager.installDependencies(execOptions, {
239 installLegacyPeerDeps: true,
240 })
241
242 factBoxOptions.interval = displayFactBox({
243 ...factBoxOptions,
244 message: "Installed Dependencies",
245 })
246
247 if (!skipDb && migrations) {
248 factBoxOptions.interval = displayFactBox({
249 ...factBoxOptions,
250 title: "Running Migrations...",
251 })
252
253 // run migrations
254 const migrationExecResult = await packageManager.runMedusaCommand(
255 "db:migrate",
256 npxOptions,
257 {
258 verbose,
259 needOutput: true,
260 }
261 )
262
263 if (client) {
264 // check the migrations table is in the database
265 // to ensure that migrations ran
266 let errorOccurred = false
267 try {
268 const migrations = await client.query(
269 `SELECT count(tablename) from pg_tables WHERE tablename = 'mikro_orm_migrations'`
270 )
271 errorOccurred = migrations.rowCount == 0
272 } catch (e) {
273 // avoid error thrown if the migrations table
274 // doesn't exist
275 errorOccurred = true
276 }
277
278 // ensure that migrations actually ran in case of an uncaught error
279 if (
280 errorOccurred &&
281 (migrationExecResult.stderr || migrationExecResult.stdout)
282 ) {
283 throw new Error(
284 `An error occurred while running migrations: ${
285 migrationExecResult.stderr || migrationExecResult.stdout
286 }`
287 )
288 }
289 }
290
291 factBoxOptions.interval = displayFactBox({
292 ...factBoxOptions,
293 message: "Ran Migrations",
294 })
295
296 const userExecResult = (await packageManager.runMedusaCommand(
297 `user -e ${ADMIN_EMAIL} --invite`,
298 npxOptions,
299 { verbose, needOutput: true }
300 )) as ExecuteResult
301
302 // get invite token from stdout
303 const match = (userExecResult.stdout as string).match(
304 /Invite token: (?<token>.+)/
305 )
306 inviteToken = match?.groups?.token
307 }
308
309 // if installation includes Next.js, retrieve the publishable API key
310 // from the backend and add it as an enviornment variable
311 if (nextjsDirectory && client) {
312 const apiKeys = await client.query(
313 `SELECT * FROM "api_key" WHERE type = 'publishable'`
314 )
315
316 if (apiKeys.rowCount) {
317 const nextjsEnvPath = path.join(
318 nextjsDirectory,
319 fs.existsSync(path.join(nextjsDirectory, ".env.local"))
320 ? ".env.local"
321 : ".env.template"
322 )
323
324 const originalContent = fs.readFileSync(nextjsEnvPath, "utf-8")
325
326 fs.writeFileSync(
327 nextjsEnvPath,
328 originalContent.replace(
329 "NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=",
330 `NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=${apiKeys.rows[0].token}`
331 )
332 )
333 }
334 }
335
336 displayFactBox({ ...factBoxOptions, message: "Finished Preparation" })
337
338 return inviteToken
339 }