1 import {
2 MedusaApp,
3 MedusaAppGetLinksExecutionPlanner,
4 MedusaAppMigrateDown,
5 MedusaAppMigrateGenerate,
6 MedusaAppMigrateUp,
7 MedusaAppOutput,
8 MedusaModule,
9 ModulesDefinition,
10 RegisterModuleJoinerConfig,
11 } from "@medusajs/modules-sdk"
12 import {
13 CommonTypes,
14 ConfigModule,
15 ILinkMigrationsPlanner,
16 IModuleService,
17 InternalModuleDeclaration,
18 LoadedModule,
19 ModuleDefinition,
20 ModuleServiceInitializeOptions,
21 } from "@medusajs/types"
22 import {
23 ContainerRegistrationKeys,
24 isBoolean,
25 isObject,
26 isPresent,
27 upperCaseFirst,
28 } from "@medusajs/utils"
29
30 import type { Knex } from "@medusajs/framework/mikro-orm/knex"
31 import { aliasTo, asValue } from "./deps/awilix"
32 import { configManager } from "./config"
33 import {
34 container,
35 container as mainContainer,
36 MedusaContainer,
37 } from "./container"
38
39 export class MedusaAppLoader {
40 /**
41 * Container from where to resolve resources
42 * @private
43 */
44 readonly #container: MedusaContainer
45
46 /**
47 * Extra links modules config which should be added manually to the links to be loaded
48 * @private
49 */
50 readonly #customLinksModules:
51 | RegisterModuleJoinerConfig
52 | RegisterModuleJoinerConfig[]
53
54 readonly #medusaConfigPath?: string
55 readonly #cwd?: string
56
57 // TODO: Adjust all loaders to accept an optional container such that in test env it is possible if needed to provide a specific container otherwise use the main container
58 // Maybe also adjust the different places to resolve the config from the container instead of the configManager for the same reason
59 // To be discussed
60 constructor({
61 container,
62 customLinksModules,
63 medusaConfigPath,
64 cwd,
65 }: {
66 container?: MedusaContainer
67 customLinksModules?:
68 | RegisterModuleJoinerConfig
69 | RegisterModuleJoinerConfig[]
70 medusaConfigPath?: string
71 cwd?: string
72 } = {}) {
73 this.#container = container ?? mainContainer
74 this.#customLinksModules = customLinksModules ?? []
75 this.#medusaConfigPath = medusaConfigPath
76 this.#cwd = cwd
77 }
78
79 protected mergeDefaultModules(
80 modulesConfig: CommonTypes.ConfigModule["modules"]
81 ) {
82 const defaultModules = Object.values(ModulesDefinition).filter(
83 (definition: ModuleDefinition) => {
84 return !!definition.defaultPackage
85 }
86 )
87
88 const configModules = { ...modulesConfig }
89
90 for (const defaultModule of defaultModules as ModuleDefinition[]) {
91 configModules[defaultModule.key] ??=
92 defaultModule.defaultModuleDeclaration
93 }
94
95 for (const [key, value] of Object.entries(
96 configModules as Record<string, InternalModuleDeclaration>
97 )) {
98 const def = {} as ModuleDefinition
99 def.key ??= key
100 def.label ??= ModulesDefinition[key]?.label ?? upperCaseFirst(key)
101 def.dependencies ??= ModulesDefinition[key]?.dependencies
102 def.isQueryable = ModulesDefinition[key]?.isQueryable ?? true
103
104 const orignalDef = value?.definition ?? ModulesDefinition[key]
105 if (
106 !isBoolean(value) &&
107 (isObject(orignalDef) || !isPresent(value.definition))
108 ) {
109 value.definition = {
110 ...def,
111 ...orignalDef,
112 }
113 }
114 }
115
116 return configModules
117 }
118
119 protected prepareSharedResourcesAndDeps() {
120 const injectedDependencies = {
121 [ContainerRegistrationKeys.PG_CONNECTION]: this.#container.resolve<
122 Knex<any>
123 >(ContainerRegistrationKeys.PG_CONNECTION),
124 [ContainerRegistrationKeys.LOGGER]: this.#container.resolve(
125 ContainerRegistrationKeys.LOGGER
126 ),
127 }
128
129 const driverOptions = {
130 ...(configManager.config.projectConfig.databaseDriverOptions ?? {}),
131 }
132 const pool = (driverOptions.pool as Record<string, unknown>) ?? {}
133 delete driverOptions.pool
134
135 const sharedResourcesConfig: ModuleServiceInitializeOptions = {
136 database: {
137 clientUrl:
138 injectedDependencies[ContainerRegistrationKeys.PG_CONNECTION]?.client
139 ?.config?.connection?.connectionString ??
140 configManager.config.projectConfig.databaseUrl,
141 driverOptions: configManager.config.projectConfig.databaseDriverOptions,
142 pool: pool,
143 debug: configManager.config.projectConfig.databaseLogging ?? false,
144 schema: configManager.config.projectConfig.databaseSchema,
145 database: configManager.config.projectConfig.databaseName,
146 },
147 }
148
149 return { sharedResourcesConfig, injectedDependencies }
150 }
151
152 /**
153 * Run, Revert or Generate the migrations for the medusa app.
154 *
155 * @param moduleNames
156 * @param linkModules
157 * @param action
158 */
159 async runModulesMigrations(
160 options:
161 | {
162 action: "run"
163 allOrNothing?: boolean
164 }
165 | {
166 action: "revert" | "generate"
167 moduleNames: string[]
168 allOrNothing?: never
169 } = {
170 action: "run",
171 }
172 ): Promise<void> {
173 const configModules = this.mergeDefaultModules(configManager.config.modules)
174
175 const { sharedResourcesConfig, injectedDependencies } =
176 this.prepareSharedResourcesAndDeps()
177
178 const migrationOptions = {
179 modulesConfig: configModules,
180 sharedContainer: this.#container,
181 linkModules: this.#customLinksModules,
182 sharedResourcesConfig,
183 injectedDependencies,
184 medusaConfigPath: this.#medusaConfigPath,
185 cwd: this.#cwd,
186 allOrNothing: options.allOrNothing,
187 }
188
189 if (options.action === "revert") {
190 await MedusaAppMigrateDown(options.moduleNames!, migrationOptions)
191 } else if (options.action === "run") {
192 await MedusaAppMigrateUp(migrationOptions)
193 } else if (options.action === "generate") {
194 await MedusaAppMigrateGenerate(options.moduleNames!, migrationOptions)
195 }
196 }
197
198 /**
199 * Return an instance of the link module migration planner.
200 */
201 async getLinksExecutionPlanner(): Promise<ILinkMigrationsPlanner> {
202 const configModules = this.mergeDefaultModules(configManager.config.modules)
203 const { sharedResourcesConfig, injectedDependencies } =
204 this.prepareSharedResourcesAndDeps()
205
206 const migrationOptions = {
207 modulesConfig: configModules,
208 sharedContainer: this.#container,
209 linkModules: this.#customLinksModules,
210 sharedResourcesConfig,
211 injectedDependencies,
212 medusaConfigPath: this.#medusaConfigPath,
213 cwd: this.#cwd,
214 }
215
216 return await MedusaAppGetLinksExecutionPlanner(migrationOptions)
217 }
218
219 /**
220 * Run the modules loader without taking care of anything else. This is useful for running the loader as a separate action or to re run all modules loaders.
221 */
222 async runModulesLoader(): Promise<void> {
223 const { sharedResourcesConfig, injectedDependencies } =
224 this.prepareSharedResourcesAndDeps()
225 const configModules = this.mergeDefaultModules(configManager.config.modules)
226
227 await MedusaApp({
228 modulesConfig: configModules,
229 sharedContainer: this.#container,
230 linkModules: this.#customLinksModules,
231 sharedResourcesConfig,
232 injectedDependencies,
233 loaderOnly: true,
234 medusaConfigPath: this.#medusaConfigPath,
235 cwd: this.#cwd,
236 })
237 }
238
239 /**
240 * Reload a single module by its key
241 * @param moduleKey - The key of the module to reload (e.g., 'contactUsModuleService')
242 */
243 async reloadSingleModule({
244 moduleKey,
245 serviceName,
246 }: {
247 /**
248 * the key of the module to reload in the medusa config (either infered or specified)
249 */
250 moduleKey: string
251 /**
252 * Registration name of the service to reload in the container
253 */
254 serviceName: string
255 }): Promise<LoadedModule | null> {
256 const configModule: ConfigModule = this.#container.resolve(
257 ContainerRegistrationKeys.CONFIG_MODULE
258 )
259 MedusaModule.unregisterModuleResolution(moduleKey)
260 if (serviceName) {
261 this.#container.cache.delete(serviceName)
262 }
263
264 const moduleConfig = configModule.modules?.[moduleKey]
265 if (!moduleConfig) {
266 return null
267 }
268
269 const { sharedResourcesConfig, injectedDependencies } =
270 this.prepareSharedResourcesAndDeps()
271
272 const mergedModules = this.mergeDefaultModules({
273 [moduleKey]: moduleConfig,
274 })
275 const moduleDefinition = mergedModules[moduleKey]
276
277 const result = await MedusaApp({
278 modulesConfig: { [moduleKey]: moduleDefinition },
279 sharedContainer: this.#container,
280 linkModules: this.#customLinksModules,
281 sharedResourcesConfig,
282 injectedDependencies,
283 workerMode: configModule.projectConfig?.workerMode,
284 medusaConfigPath: this.#medusaConfigPath,
285 cwd: this.#cwd,
286 })
287
288 const loadedModule = result.modules[moduleKey] as LoadedModule &
289 IModuleService
290 if (loadedModule) {
291 this.#container.register({
292 [loadedModule.__definition.key]: asValue(loadedModule),
293 })
294 }
295
296 if (loadedModule?.__hooks?.onApplicationStart) {
297 await loadedModule.__hooks.onApplicationStart
298 .bind(loadedModule)()
299 .catch((error: any) => {
300 injectedDependencies[ContainerRegistrationKeys.LOGGER].error(
301 `Error starting module "${loadedModule.__definition.key}": ${error.message}`
302 )
303 })
304 }
305
306 return loadedModule
307 }
308
309 /**
310 * Load all modules and bootstrap all the modules and links to be ready to be consumed
311 * @param config
312 */
313 async load(
314 config: {
315 registerInContainer?: boolean
316 schemaOnly?: boolean
317 migrationOnly?: boolean
318 } = {
319 registerInContainer: true,
320 schemaOnly: false,
321 migrationOnly: false,
322 }
323 ): Promise<MedusaAppOutput> {
324 const configModule: ConfigModule = this.#container.resolve(
325 ContainerRegistrationKeys.CONFIG_MODULE
326 )
327
328 const { sharedResourcesConfig, injectedDependencies } =
329 !config.migrationOnly && !config.schemaOnly
330 ? this.prepareSharedResourcesAndDeps()
331 : {}
332
333 this.#container.register(
334 ContainerRegistrationKeys.REMOTE_QUERY,
335 asValue(undefined)
336 )
337 this.#container.register(
338 ContainerRegistrationKeys.QUERY,
339 asValue(undefined)
340 )
341 this.#container.register(ContainerRegistrationKeys.LINK, asValue(undefined))
342 this.#container.register(
343 ContainerRegistrationKeys.REMOTE_LINK,
344 aliasTo(ContainerRegistrationKeys.LINK)
345 )
346
347 const configModules = this.mergeDefaultModules(configModule.modules)
348
349 const medusaApp = await MedusaApp({
350 workerMode: configModule.projectConfig.workerMode,
351 modulesConfig: configModules,
352 sharedContainer: this.#container,
353 linkModules: this.#customLinksModules,
354 sharedResourcesConfig,
355 injectedDependencies,
356 medusaConfigPath: this.#medusaConfigPath,
357 cwd: this.#cwd,
358 migrationOnly: config.migrationOnly,
359 schemaOnly: config.schemaOnly,
360 })
361
362 if (!config.registerInContainer) {
363 return medusaApp
364 }
365
366 this.#container.register(
367 ContainerRegistrationKeys.LINK,
368 asValue(medusaApp.link)
369 )
370 this.#container.register(
371 ContainerRegistrationKeys.REMOTE_LINK,
372 aliasTo(ContainerRegistrationKeys.LINK)
373 )
374 this.#container.register(
375 ContainerRegistrationKeys.REMOTE_QUERY,
376 asValue(medusaApp.query)
377 )
378 this.#container.register(
379 ContainerRegistrationKeys.QUERY,
380 asValue(medusaApp.query)
381 )
382
383 for (const moduleService of Object.values(medusaApp.modules)) {
384 const loadedModule = moduleService as LoadedModule
385 container.register(loadedModule.__definition.key, asValue(moduleService))
386 }
387
388 // Register all unresolved modules as undefined to be present in the container with undefined value by default
389 // but still resolvable
390 for (const moduleDefinition of Object.values(ModulesDefinition)) {
391 if (!container.hasRegistration(moduleDefinition.key)) {
392 container.register(moduleDefinition.key, asValue(undefined))
393 }
394 }
395
396 return medusaApp
397 }
398 }