1 import { asValue } from "@medusajs/deps/awilix"
2 import {
3 ConfigModule,
4 ExternalModuleDeclaration,
5 FlagSettings,
6 IIndexService,
7 ISearchModuleService,
8 ILinkMigrationsPlanner,
9 InternalModuleDeclaration,
10 LoadedModule,
11 Logger,
12 MedusaContainer,
13 ModuleBootstrapDeclaration,
14 ModuleDefinition,
15 ModuleExports,
16 ModuleServiceInitializeOptions,
17 RemoteQueryFunction,
18 SearchTypes,
19 } from "@medusajs/types"
20 import {
21 ContainerRegistrationKeys,
22 createMedusaContainer,
23 discoverFeatureFlagsFromDir,
24 dynamicImport,
25 executeWithConcurrency,
26 FeatureFlag,
27 GraphQLUtils,
28 isObject,
29 isSharedConnectionSymbol,
30 isString,
31 MedusaError,
32 MODULE_PACKAGE_NAMES,
33 Modules,
34 ModulesSdkUtils,
35 promiseAll,
36 registerFeatureFlag,
37 withDbTroubleshootingLink,
38 DBTroubleshootingSection,
39 } from "@medusajs/utils"
40 import { Link } from "./link"
41 import {
42 MedusaModule,
43 MigrationOptions,
44 ModuleBootstrapOptions,
45 RegisterModuleJoinerConfig,
46 } from "./medusa-module"
47 import { createQuery } from "./remote-query"
48 import { MODULE_SCOPE } from "./types"
49
50 const LinkModulePackage = MODULE_PACKAGE_NAMES[Modules.LINK]
51
52 function getMigrationConnectionTimeout(): number {
53 return process.env.MEDUSA_DB_MIGRATION_CONNECTION_TIMEOUT
54 ? parseInt(process.env.MEDUSA_DB_MIGRATION_CONNECTION_TIMEOUT)
55 : 10000
56 }
57
58 /**
59 * Verify that a database connection can be established before running
60 * migrations. Without this check, a stalled connection (for example, a wrong
61 * database URL or an SSL handshake that never completes) hangs the migrator
62 * indefinitely with no error. This fails fast with an actionable message
63 * instead.
64 */
65 export async function verifyMigrationConnection(
66 knex: ReturnType<typeof ModulesSdkUtils.createPgConnection>
67 ): Promise<void> {
68 const connectionTimeout = getMigrationConnectionTimeout()
69 let timeoutHandle: ReturnType<typeof setTimeout> | undefined
70
71 const timeout = new Promise<never>((_, reject) => {
72 timeoutHandle = setTimeout(() => {
73 reject(
74 new MedusaError(
75 MedusaError.Types.DB_ERROR,
76 withDbTroubleshootingLink(
77 `Could not connect to the database while running migrations. The connection timed out after ${
78 connectionTimeout / 1000
79 } seconds, which usually indicates an incorrect database URL or an SSL configuration issue.`,
80 DBTroubleshootingSection.MIGRATIONS
81 )
82 )
83 )
84 }, connectionTimeout)
85 })
86
87 try {
88 await Promise.race([knex.raw("SELECT 1"), timeout])
89 } catch (error) {
90 if (error instanceof MedusaError) {
91 throw error
92 }
93
94 throw new MedusaError(
95 MedusaError.Types.DB_ERROR,
96 withDbTroubleshootingLink(
97 `Could not connect to the database while running migrations: ${
98 error?.message ?? error
99 }. This usually indicates an incorrect database URL or an SSL configuration issue.`,
100 DBTroubleshootingSection.MIGRATIONS
101 )
102 )
103 } finally {
104 if (timeoutHandle) {
105 clearTimeout(timeoutHandle)
106 }
107 }
108 }
109
110 export type RunMigrationFn = (options?: {
111 allOrNothing?: boolean
112 }) => Promise<void>
113 export type RevertMigrationFn = (moduleNames: string[]) => Promise<void>
114 export type GenerateMigrations = (moduleNames: string[]) => Promise<void>
115 export type GetLinkExecutionPlanner = () => ILinkMigrationsPlanner
116
117 export type MedusaModuleConfig = {
118 [key: string | Modules]:
119 | string
120 | boolean
121 | Partial<InternalModuleDeclaration | ExternalModuleDeclaration>
122 }
123
124 export type SharedResources = {
125 database?: ModuleServiceInitializeOptions["database"] & {
126 /**
127 * {
128 * name?: string
129 * afterCreate?: Function
130 * min?: number
131 * max?: number
132 * refreshIdle?: boolean
133 * idleTimeoutMillis?: number
134 * reapIntervalMillis?: number
135 * returnToHead?: boolean
136 * priorityRange?: number
137 * log?: (message: string, logLevel: string) => void
138 * }
139 */
140 pool?: Record<string, unknown>
141 }
142 }
143
144 export async function loadModules(args: {
145 modulesConfig: MedusaModuleConfig
146 sharedContainer: MedusaContainer
147 sharedResourcesConfig?: SharedResources
148 migrationOnly?: boolean
149 schemaOnly?: boolean
150 loaderOnly?: boolean
151 workerMode?: "shared" | "worker" | "server"
152 cwd?: string
153 }) {
154 const {
155 modulesConfig,
156 sharedContainer,
157 sharedResourcesConfig,
158 migrationOnly = false,
159 schemaOnly = false,
160 loaderOnly = false,
161 workerMode = "shared" as ModuleBootstrapOptions["workerMode"],
162 cwd,
163 } = args
164
165 const allModules = {} as any
166
167 const modulesToLoad: {
168 moduleKey: string
169 defaultPath: string
170 declaration: InternalModuleDeclaration | ExternalModuleDeclaration
171 sharedContainer: MedusaContainer
172 moduleDefinition: ModuleDefinition
173 moduleExports?: ModuleExports
174 }[] = []
175
176 for (const moduleName of Object.keys(modulesConfig)) {
177 const mod = modulesConfig[moduleName]
178 let path: string
179 let moduleExports: ModuleExports | undefined = undefined
180 let declaration: any = {}
181 let definition: Partial<ModuleDefinition> | undefined = undefined
182
183 // TODO: We are keeping mod === false for backward compatibility for now
184 if (mod === false || (isObject(mod) && "disable" in mod && mod.disable)) {
185 continue
186 }
187
188 if (isObject(mod)) {
189 const mod_ = mod as unknown as InternalModuleDeclaration
190 path = mod_.resolve ?? MODULE_PACKAGE_NAMES[moduleName]
191 definition = mod_.definition
192 moduleExports = !isString(mod_.resolve)
193 ? (mod_.resolve as ModuleExports)
194 : undefined
195 declaration = { ...mod }
196 delete declaration.definition
197 } else {
198 path = MODULE_PACKAGE_NAMES[moduleName]
199 }
200
201 declaration.scope ??= MODULE_SCOPE.INTERNAL
202
203 if (declaration.scope === MODULE_SCOPE.INTERNAL) {
204 declaration.options ??= {}
205
206 if (!declaration.options.database) {
207 declaration.options[isSharedConnectionSymbol] = true
208 }
209
210 declaration.options.database ??= {
211 ...sharedResourcesConfig?.database,
212 }
213 declaration.options.database.debug ??=
214 sharedResourcesConfig?.database?.debug
215 }
216
217 /**
218 * The Search Module does not discover its own definitions; the app loads them
219 * off the file system (`search/`) and passes them in, like links.
220 *
221 * Inline ones go through the registry too, so the registry holds everything indexed and
222 * not just what came off disk. The ingestion subscriber uses the registry to know what
223 * events to listen to.
224 */
225 if (moduleName === Modules.SEARCH) {
226 const configured = (declaration.options?.indexes ??
227 []) as SearchTypes.SearchIndexDefinition[]
228
229 for (const definition of configured) {
230 MedusaModule.setSearchIndex(definition)
231 }
232
233 const registered = MedusaModule.getSearchIndexes()
234
235 if (registered.length) {
236 declaration.options = { ...declaration.options, indexes: registered }
237 }
238 }
239
240 modulesToLoad.push({
241 moduleKey: moduleName,
242 defaultPath: path,
243 declaration,
244 sharedContainer,
245 moduleDefinition: definition as ModuleDefinition,
246 moduleExports,
247 })
248 }
249
250 const loaded = (await MedusaModule.bootstrapAll(modulesToLoad, {
251 migrationOnly,
252 schemaOnly,
253 loaderOnly,
254 workerMode,
255 cwd,
256 })) as LoadedModule[]
257
258 if (loaderOnly) {
259 return allModules
260 }
261
262 for (const { moduleKey } of modulesToLoad) {
263 const service = loaded.find((loadedModule) => loadedModule[moduleKey])?.[
264 moduleKey
265 ]
266 if (!service) {
267 throw new Error(`Module ${moduleKey} could not be loaded.`)
268 }
269
270 sharedContainer.register({
271 [service.__definition.key]: asValue(service),
272 })
273
274 if (allModules[moduleKey] && !Array.isArray(allModules[moduleKey])) {
275 allModules[moduleKey] = []
276 }
277
278 if (allModules[moduleKey]) {
279 ;(allModules[moduleKey] as LoadedModule[]).push(service)
280 } else {
281 allModules[moduleKey] = service
282 }
283 }
284
285 return allModules
286 }
287
288 async function initializeLinks({
289 config,
290 linkModules,
291 injectedDependencies,
292 moduleExports,
293 migrationOnly = false,
294 schemaOnly = false,
295 }) {
296 try {
297 let resources = moduleExports
298 if (!resources) {
299 const module = await dynamicImport(LinkModulePackage)
300 if ("discoveryPath" in module) {
301 const reExportedLoadedModule = await dynamicImport(module.discoveryPath)
302 resources = reExportedLoadedModule.default ?? reExportedLoadedModule
303 }
304 }
305
306 const { initialize, getMigrationPlanner } = resources
307
308 const linkResolution = await initialize(
309 config,
310 linkModules,
311 injectedDependencies,
312 undefined,
313 migrationOnly,
314 schemaOnly
315 )
316
317 return {
318 remoteLink: new Link(),
319 linkResolution,
320 getMigrationPlanner,
321 }
322 } catch (err) {
323 console.warn("Error initializing link modules.", err)
324 return {
325 remoteLink: undefined,
326 linkResolution: undefined,
327 getMigrationPlanner: () => void 0,
328 }
329 }
330 }
331
332 function isMedusaModule(mod) {
333 return typeof mod?.initialize === "function"
334 }
335
336 function cleanAndMergeSchema(loadedSchema) {
337 const defaultMedusaSchema = `
338 scalar DateTime
339 scalar JSON
340 directive @enumValue(value: String) on ENUM_VALUE
341 `
342 const { schema: cleanedSchema, notFound } = GraphQLUtils.cleanGraphQLSchema(
343 defaultMedusaSchema + loadedSchema
344 )
345 const mergedSchema = GraphQLUtils.mergeTypeDefs(cleanedSchema)
346 return {
347 schema: GraphQLUtils.makeExecutableSchema({ typeDefs: mergedSchema }),
348 notFound,
349 }
350 }
351
352 function getLoadedSchema(): string {
353 return MedusaModule.getAllJoinerConfigs()
354 .map((joinerConfig) => joinerConfig?.schema ?? "")
355 .join("\n")
356 }
357
358 export type MedusaAppOutput = {
359 modules: Record<string, LoadedModule | LoadedModule[]>
360 link: Link | undefined
361 query: RemoteQueryFunction
362 entitiesMap?: Record<string, any>
363 gqlSchema?: GraphQLUtils.GraphQLSchema
364 notFound?: Record<string, Record<string, string>>
365 runMigrations: RunMigrationFn
366 revertMigrations: RevertMigrationFn
367 generateMigrations: GenerateMigrations
368 linkMigrationExecutionPlanner: GetLinkExecutionPlanner
369 onApplicationShutdown: () => Promise<void>
370 onApplicationPrepareShutdown: () => Promise<void>
371 onApplicationStart: () => Promise<void>
372 sharedContainer?: MedusaContainer
373 }
374
375 export type MedusaAppOptions = {
376 workerMode?: "shared" | "worker" | "server"
377 sharedContainer?: MedusaContainer
378 sharedResourcesConfig?: SharedResources
379 loadedModules?: LoadedModule[]
380 medusaConfigPath?: string
381 modulesConfigFileName?: string
382 modulesConfig?: MedusaModuleConfig
383 linkModules?: RegisterModuleJoinerConfig | RegisterModuleJoinerConfig[]
384 injectedDependencies?: any
385 onApplicationStartCb?: () => void
386 /**
387 * Forces the modules bootstrapper to only run the modules loaders and return prematurely
388 */
389 loaderOnly?: boolean
390 /**
391 * Only partially load modules to retrieve their module joiner configs and run their loaders.
392 * Useful for migrations.
393 */
394 migrationOnly?: boolean
395 /**
396 * Only partially load modules to retrieve their module joiner configs without running loaders.
397 * Useful for type generation.
398 */
399 schemaOnly?: boolean
400 cwd?: string
401 }
402
403 async function MedusaApp_({
404 sharedContainer,
405 sharedResourcesConfig,
406 medusaConfigPath,
407 modulesConfigFileName,
408 modulesConfig,
409 linkModules,
410 injectedDependencies = {},
411 migrationOnly = false,
412 schemaOnly = false,
413 loaderOnly = false,
414 workerMode = "shared",
415 cwd = process.cwd(),
416 }: MedusaAppOptions = {}): Promise<MedusaAppOutput> {
417 const sharedContainer_ = createMedusaContainer({}, sharedContainer)
418
419 const config = sharedContainer_.resolve(
420 ContainerRegistrationKeys.CONFIG_MODULE,
421 {
422 allowUnregistered: true,
423 }
424 ) as ConfigModule
425 const logger = sharedContainer_.resolve(ContainerRegistrationKeys.LOGGER, {
426 allowUnregistered: true,
427 }) as Logger
428
429 const discovered = await discoverFeatureFlagsFromDir(cwd)
430 for (const def of discovered) {
431 registerFeatureFlag({
432 flag: def as FlagSettings,
433 projectConfigFlags: config?.featureFlags ?? {},
434 router: FeatureFlag,
435 logger,
436 })
437 }
438
439 const onApplicationShutdown = async () => {
440 await promiseAll([
441 MedusaModule.onApplicationShutdown(),
442 sharedContainer_.dispose(),
443 ])
444 }
445
446 const onApplicationPrepareShutdown = async () => {
447 await promiseAll([MedusaModule.onApplicationPrepareShutdown()])
448 }
449
450 const onApplicationStart = async () => {
451 await MedusaModule.onApplicationStart()
452 }
453
454 const modules: MedusaModuleConfig =
455 modulesConfig ??
456 (
457 await dynamicImport(
458 medusaConfigPath ?? cwd + (modulesConfigFileName ?? "/modules-config")
459 )
460 ).default
461
462 const dbData = ModulesSdkUtils.loadDatabaseConfig(
463 "medusa",
464 sharedResourcesConfig as ModuleServiceInitializeOptions,
465 true
466 )!
467
468 if (
469 sharedResourcesConfig?.database?.connection &&
470 !injectedDependencies[ContainerRegistrationKeys.PG_CONNECTION]
471 ) {
472 injectedDependencies[ContainerRegistrationKeys.PG_CONNECTION] =
473 sharedResourcesConfig.database.connection
474 } else if (
475 dbData.clientUrl &&
476 !injectedDependencies[ContainerRegistrationKeys.PG_CONNECTION]
477 ) {
478 injectedDependencies[ContainerRegistrationKeys.PG_CONNECTION] =
479 ModulesSdkUtils.createPgConnection({
480 ...(sharedResourcesConfig?.database ?? {}),
481 ...dbData,
482 })
483 }
484
485 // remove the link module from the modules
486 const linkModule = modules[LinkModulePackage] ?? modules[Modules.LINK]
487 delete modules[LinkModulePackage]
488 delete modules[Modules.LINK]
489
490 let linkModuleOrOptions:
491 | Partial<ModuleServiceInitializeOptions>
492 | Partial<ModuleBootstrapDeclaration> = {}
493
494 if (isObject(linkModule)) {
495 linkModuleOrOptions = linkModule
496 }
497
498 for (const injectedDependency of Object.keys(injectedDependencies)) {
499 sharedContainer_.register({
500 [injectedDependency]: asValue(injectedDependencies[injectedDependency]),
501 })
502 }
503
504 const allModules = await loadModules({
505 modulesConfig: modules,
506 sharedContainer: sharedContainer_,
507 sharedResourcesConfig: { database: dbData },
508 migrationOnly,
509 schemaOnly,
510 loaderOnly,
511 workerMode,
512 cwd,
513 })
514
515 if (loaderOnly) {
516 async function query(...args: any[]) {
517 throw new Error("Querying not allowed in loaderOnly mode")
518 }
519 query.graph = query
520 query.gql = query
521
522 return {
523 onApplicationShutdown,
524 onApplicationPrepareShutdown,
525 onApplicationStart,
526 modules: allModules,
527 link: undefined,
528 query: query as unknown as RemoteQueryFunction,
529 runMigrations: async () => {
530 throw new Error("Migrations not allowed in loaderOnly mode")
531 },
532 revertMigrations: async () => {
533 throw new Error("Revert migrations not allowed in loaderOnly mode")
534 },
535 generateMigrations: async () => {
536 throw new Error("Generate migrations not allowed in loaderOnly mode")
537 },
538 linkMigrationExecutionPlanner: () => {
539 throw new Error(
540 "Migrations planner is not avaibable in loaderOnly mode"
541 )
542 },
543 }
544 }
545
546 // Share Event bus with link modules
547 injectedDependencies[Modules.EVENT_BUS] = sharedContainer_.resolve(
548 Modules.EVENT_BUS,
549 {
550 allowUnregistered: true,
551 }
552 )
553
554 linkModules ??= []
555 if (!Array.isArray(linkModules)) {
556 linkModules = [linkModules]
557 }
558 linkModules.push(...MedusaModule.getCustomLinks())
559
560 const allLoadedJoinerConfigs = MedusaModule.getAllJoinerConfigs()
561 for (let linkIdx = 0; linkIdx < linkModules.length; linkIdx++) {
562 const customLink: any = linkModules[linkIdx]
563 if (typeof customLink === "function") {
564 linkModules[linkIdx] = customLink(allLoadedJoinerConfigs)
565 }
566 }
567
568 const { remoteLink, getMigrationPlanner } = await initializeLinks({
569 config: linkModuleOrOptions,
570 linkModules,
571 injectedDependencies,
572 moduleExports: isMedusaModule(linkModule) ? linkModule : undefined,
573 migrationOnly,
574 schemaOnly,
575 })
576
577 const loadedSchema = getLoadedSchema()
578 const { schema, notFound } = cleanAndMergeSchema(loadedSchema)
579 const entitiesMap = schema.getTypeMap() as unknown as Map<string, any>
580 const relationMap = GraphQLUtils.extractRelationsFromGQL(entitiesMap)
581
582 const modulesLoaded = MedusaModule.getLoadedModules().map(
583 (mod) => Object.values(mod)[0]
584 )
585
586 const applyMigration = async ({
587 modulesNames,
588 action = "run",
589 allOrNothing = false,
590 }: {
591 modulesNames: string[]
592 action?: "run" | "revert" | "generate"
593 allOrNothing?: boolean
594 }): Promise<{ name: string; path: string }[] | void> => {
595 const moduleResolutions = Array.from(new Set(modulesNames)).map(
596 (moduleName) => {
597 return {
598 moduleName,
599 resolution: MedusaModule.getModuleResolutions(moduleName),
600 }
601 }
602 )
603
604 const missingModules = moduleResolutions
605 .filter(({ resolution }) => !resolution)
606 .map(({ moduleName }) => moduleName)
607
608 if (missingModules.length) {
609 const error = new MedusaError(
610 MedusaError.Types.UNKNOWN_MODULES,
611 `Cannot ${action} migrations for unknown module(s) ${missingModules.join(
612 ","
613 )}`,
614 MedusaError.Codes.UNKNOWN_MODULES
615 )
616 error["allModules"] = Object.keys(allModules)
617 throw error
618 }
619
620 let executedResolutions: [any, string[]][] = [] // [moduleResolution, migration names[]]
621
622 const lockKnex = ModulesSdkUtils.createPgConnection({
623 ...dbData,
624 pool: { min: 1, max: 1 },
625 })
626
627 const run = async (
628 { resolution: moduleResolution },
629 migrationNames?: string[]
630 ) => {
631 if (
632 !moduleResolution.options?.database &&
633 moduleResolution.moduleDeclaration?.scope === MODULE_SCOPE.INTERNAL
634 ) {
635 moduleResolution.options ??= {}
636 moduleResolution.options.database = {
637 ...(sharedResourcesConfig?.database ?? {}),
638 }
639 ;(moduleResolution as any).options.database.debug ??=
640 sharedResourcesConfig?.database?.debug
641 }
642
643 const migrationOptions: MigrationOptions = {
644 moduleKey: moduleResolution.definition.key,
645 modulePath: moduleResolution.resolutionPath as string,
646 container: sharedContainer,
647 options: moduleResolution.options,
648 moduleExports: moduleResolution.moduleExports as ModuleExports,
649 cwd,
650 }
651
652 const lockKey = `db-module-migration:${migrationOptions.moduleKey}`
653
654 await lockKnex.transaction(async (trx) => {
655 await trx.raw(`SELECT pg_advisory_xact_lock(hashtext(?))`, [lockKey])
656
657 if (action === "revert") {
658 await MedusaModule.migrateDown(migrationOptions, migrationNames)
659 } else if (action === "run") {
660 const ranMigrationsResult = await MedusaModule.migrateUp(
661 migrationOptions
662 )
663
664 // Store for revert if anything goes wrong later
665 executedResolutions.push([
666 moduleResolution,
667 ranMigrationsResult?.map((r) => r.name) ?? [],
668 ])
669 } else {
670 await MedusaModule.migrateGenerate(migrationOptions)
671 }
672 })
673 }
674
675 const concurrency = parseInt(process.env.DB_MIGRATION_CONCURRENCY ?? "1")
676 try {
677 await verifyMigrationConnection(lockKnex)
678
679 const results = await executeWithConcurrency(
680 moduleResolutions.map((a) => () => run(a)),
681 concurrency
682 )
683 const rejections = results.filter(
684 (result) => result.status === "rejected"
685 )
686 if (rejections.length) {
687 throw new Error(
688 `Some migrations failed to ${action}: ${rejections
689 .map((r) => r.reason)
690 .join(", ")}`
691 )
692 }
693 } catch (error) {
694 if (allOrNothing) {
695 action = "revert"
696 await executeWithConcurrency(
697 executedResolutions.map(
698 ([resolution, migrationNames]) =>
699 () =>
700 run({ resolution }, migrationNames)
701 ),
702 concurrency
703 )
704 }
705 throw error
706 } finally {
707 await lockKnex.destroy()
708 }
709 }
710
711 const runMigrations: RunMigrationFn = async (
712 { allOrNothing = false }: { allOrNothing?: boolean } = {
713 allOrNothing: false,
714 }
715 ): Promise<void> => {
716 await applyMigration({
717 modulesNames: Object.keys(allModules),
718 allOrNothing,
719 })
720 }
721
722 const revertMigrations: RevertMigrationFn = async (
723 modulesNames
724 ): Promise<void> => {
725 await applyMigration({
726 modulesNames,
727 action: "revert",
728 })
729 }
730
731 const generateMigrations: GenerateMigrations = async (
732 modulesNames
733 ): Promise<void> => {
734 await applyMigration({
735 modulesNames,
736 action: "generate",
737 })
738 }
739
740 const getMigrationPlannerFn = () => {
741 const options: Partial<ModuleServiceInitializeOptions> =
742 "scope" in linkModuleOrOptions
743 ? { ...linkModuleOrOptions.options }
744 : {
745 ...(linkModuleOrOptions as Partial<ModuleServiceInitializeOptions>),
746 }
747
748 options.database ??= {
749 ...sharedResourcesConfig?.database,
750 }
751 options.database.debug ??= sharedResourcesConfig?.database?.debug
752
753 return getMigrationPlanner(options, linkModules)
754 }
755
756 const indexModule = sharedContainer_.resolve(Modules.INDEX, {
757 allowUnregistered: true,
758 }) as IIndexService
759
760 const searchModule = sharedContainer_.resolve(Modules.SEARCH, {
761 allowUnregistered: true,
762 }) as ISearchModuleService
763
764 return {
765 onApplicationShutdown,
766 onApplicationPrepareShutdown,
767 onApplicationStart,
768 modules: allModules,
769 link: remoteLink,
770 query: createQuery({
771 modulesLoaded,
772 relationMap,
773 indexModule,
774 searchModule,
775 container: sharedContainer_,
776 }) as any, // TODO: rm any once we remove the old RemoteQueryFunction and rely on the Query object instead,
777 entitiesMap,
778 gqlSchema: schema,
779 notFound,
780 runMigrations,
781 revertMigrations,
782 generateMigrations,
783 linkMigrationExecutionPlanner: getMigrationPlannerFn,
784 sharedContainer: sharedContainer_,
785 }
786 }
787
788 export async function MedusaApp(
789 options: MedusaAppOptions = {}
790 ): Promise<MedusaAppOutput> {
791 return await MedusaApp_(options)
792 }
793
794 export async function MedusaAppMigrateUp(
795 options: MedusaAppOptions & { allOrNothing?: boolean } = {}
796 ): Promise<void> {
797 const migrationOnly = true
798
799 const { runMigrations } = await MedusaApp_({
800 ...options,
801 migrationOnly,
802 })
803
804 await runMigrations({ allOrNothing: options.allOrNothing }).finally(
805 MedusaModule.clearInstances
806 )
807 }
808
809 export async function MedusaAppMigrateDown(
810 moduleNames: string[],
811 options: MedusaAppOptions = {}
812 ): Promise<void> {
813 const migrationOnly = true
814
815 const { revertMigrations } = await MedusaApp_({
816 ...options,
817 migrationOnly,
818 })
819
820 await revertMigrations(moduleNames).finally(MedusaModule.clearInstances)
821 }
822
823 export async function MedusaAppMigrateGenerate(
824 moduleNames: string[],
825 options: MedusaAppOptions = {}
826 ): Promise<void> {
827 const migrationOnly = true
828
829 const { generateMigrations } = await MedusaApp_({
830 ...options,
831 migrationOnly,
832 })
833
834 await generateMigrations(moduleNames).finally(MedusaModule.clearInstances)
835 }
836
837 export async function MedusaAppGetLinksExecutionPlanner(
838 options: MedusaAppOptions = {}
839 ): Promise<ILinkMigrationsPlanner> {
840 const migrationOnly = true
841
842 const { linkMigrationExecutionPlanner } = await MedusaApp_({
843 ...options,
844 migrationOnly,
845 })
846
847 return linkMigrationExecutionPlanner()
848 }