1 import { deepCopy, isDefined, isProduction } from "@medusajs/utils"
2 import { logger } from "../logger"
3 import { ConfigModule } from "./types"
4
5 export class ConfigManager {
6 /**
7 * Root dir from where to start
8 * @private
9 */
10 #baseDir: string
11
12 /**
13 * A flag to specify if we are in production or not, determine whether an error would be critical and thrown or just logged as a warning in developement
14 * @private
15 */
16 get #isProduction(): boolean {
17 return isProduction()
18 }
19
20 /**
21 * The worker mode
22 * @private
23 */
24 get #envWorkMode(): ConfigModule["projectConfig"]["workerMode"] {
25 return process.env
26 .MEDUSA_WORKER_MODE as ConfigModule["projectConfig"]["workerMode"]
27 }
28
29 /**
30 * The config object after loading it
31 * @private
32 */
33 #config!: ConfigModule
34
35 get config(): ConfigModule {
36 if (!this.#config) {
37 this.rejectErrors(
38 `Config not loaded. Make sure the config have been loaded first using the 'configLoader' or 'configManager.loadConfig'.`
39 )
40 }
41 return this.#config
42 }
43
44 get baseDir(): string {
45 return this.#baseDir
46 }
47
48 get isProduction(): boolean {
49 return this.#isProduction
50 }
51
52 constructor() {}
53
54 /**
55 * Rejects an error either by throwing when in production or by logging the error as a warning
56 * @param error
57 * @protected
58 */
59 protected rejectErrors(error: string): never | void {
60 if (this.#isProduction) {
61 throw new Error(`[config] ⚠️ ${error}`)
62 }
63
64 logger.warn(error)
65 }
66
67 /**
68 * Builds the http config object and assign the defaults if needed
69 * @param projectConfig
70 * @protected
71 */
72 protected buildHttpConfig(
73 projectConfig: Partial<ConfigModule["projectConfig"]>,
74 options?: {
75 throwOnValidationError?: boolean
76 }
77 ): ConfigModule["projectConfig"]["http"] {
78 const { throwOnValidationError = true } = options ?? {}
79 const http = (projectConfig.http ??
80 {}) as ConfigModule["projectConfig"]["http"]
81
82 http.jwtExpiresIn = http?.jwtExpiresIn ?? "1d"
83 http.authCors = http.authCors ?? ""
84 http.storeCors = http.storeCors ?? ""
85 http.adminCors = http.adminCors ?? ""
86 http.storeRelationsLimit = http.storeRelationsLimit ?? 3
87
88 http.jwtOptions ??= {}
89 http.jwtOptions.expiresIn = http.jwtExpiresIn
90
91 http.jwtSecret = http?.jwtSecret ?? process.env.JWT_SECRET
92 http.jwtPublicKey = http?.jwtPublicKey ?? process.env.JWT_PUBLIC_KEY
93
94 if (
95 throwOnValidationError &&
96 http?.jwtPublicKey &&
97 ((http.jwtVerifyOptions && !http.jwtVerifyOptions.algorithms?.length) ||
98 (http.jwtOptions && !http.jwtOptions.algorithm))
99 ) {
100 this.rejectErrors(
101 `JWT public key is provided but no algorithm is set in the 'jwtVerifyOptions' or 'jwtOptions' if 'jwtVerifyOptions' is not provided. It means that the algorithm will be inferred from the public key which can lead to missmatch and invalid algorithm errors.`
102 )
103 }
104
105 if (!http.jwtSecret) {
106 if (throwOnValidationError) {
107 this.rejectErrors(
108 `http.jwtSecret not found.${
109 this.#isProduction ? "" : "Using default 'supersecret'."
110 }`
111 )
112 }
113
114 http.jwtSecret = "supersecret"
115 }
116
117 http.cookieSecret = (projectConfig.http?.cookieSecret ??
118 process.env.COOKIE_SECRET)!
119
120 if (!http.cookieSecret) {
121 if (throwOnValidationError) {
122 this.rejectErrors(
123 `http.cookieSecret not found.${
124 this.#isProduction ? "" : " Using default 'supersecret'."
125 }`
126 )
127 }
128
129 http.cookieSecret = "supersecret"
130 }
131
132 return http
133 }
134
135 /**
136 * Normalizes the project config object and assign the defaults if needed
137 * @param config
138 * @protected
139 */
140 protected normalizeProjectConfig(
141 config: Partial<ConfigModule>,
142 options?: {
143 throwOnValidationError?: boolean
144 }
145 ): ConfigModule["projectConfig"] {
146 const projConfig = config?.projectConfig ?? {}
147 const outputConfig = deepCopy(projConfig) as ConfigModule["projectConfig"]
148
149 if (!outputConfig?.redisUrl) {
150 const customLogger = config?.logger ?? logger
151 customLogger.log(
152 `redisUrl not found. A fake redis instance will be used.`
153 )
154 }
155
156 outputConfig.http = this.buildHttpConfig(projConfig, {
157 throwOnValidationError: options?.throwOnValidationError,
158 })
159
160 let workerMode = outputConfig?.workerMode!
161
162 if (!isDefined(workerMode)) {
163 const env = this.#envWorkMode
164 if (isDefined(env)) {
165 const workerModes = ["shared", "worker", "server"]
166 if (workerModes.includes(env)) {
167 workerMode = env
168 }
169 } else {
170 workerMode = "shared"
171 }
172 }
173
174 return {
175 ...outputConfig,
176 workerMode,
177 }
178 }
179
180 /**
181 * Prepare the full configuration after validation and normalization
182 */
183 loadConfig({
184 projectConfig = {},
185 baseDir,
186 throwOnValidationError = true,
187 }: {
188 projectConfig: Partial<ConfigModule>
189 baseDir: string
190 throwOnValidationError?: boolean
191 }): ConfigModule {
192 this.#baseDir = baseDir
193
194 const normalizedProjectConfig = this.normalizeProjectConfig(projectConfig, {
195 throwOnValidationError,
196 })
197
198 this.#config = {
199 projectConfig: normalizedProjectConfig,
200 admin: projectConfig.admin ?? {
201 path: "/app",
202 },
203 modules: projectConfig.modules ?? {},
204 featureFlags: projectConfig.featureFlags ?? {},
205 plugins: projectConfig.plugins ?? [],
206 logger: projectConfig.logger ?? logger,
207 }
208
209 return this.#config
210 }
211 }