1 import { RemoteJoinerQuery } from "@medusajs/types"
2 import { deduplicate, isDefined } from "@medusajs/utils"
3 import { GraphCatalog } from "./catalog"
4 import {
5 consumeResiduals,
6 extractCrossModuleJoins,
7 } from "./cross-module-joins"
8 import {
9 getNestedItems,
10 resolveFieldAliasEntry,
11 ResolvedFieldAlias,
12 } from "./helpers"
13 import {
14 BASE_PATH,
15 CompileInput,
16 ComputedJoinerRelationship,
17 ExecutionStage,
18 InternalJoinerServiceConfig,
19 QueryPlan,
20 RemoteExpandProperty,
21 ShortcutSpec,
22 } from "./types"
23
24 /**
25 * Compiles a {@link RemoteJoinerQuery} into an executable {@link QueryPlan}.
26 *
27 * Field-alias shortcuts are rewritten into real relationship paths and recorded
28 * as {@link ShortcutSpec}s. Same-service consecutive hops are nested so one
29 * module fetch can load multiple levels.
30 */
31
32 /**
33 * Example walkthrough — order with fieldAlias + nested expand:
34 *
35 * alias: "order"
36 * fields: ["id"]
37 * expands: [
38 * { property: "product_user_alias", fields: ["id", "email"], args: [...] },
39 * { property: "products.variant" }
40 * ]
41 *
42 * Compile produces roughly:
43 * expands: {
44 * _root → order service, fields [id], stages [...]
45 * _root.products → still on order (same service hop toward product via nested)
46 * _root.products.product → product service (cross-service boundary)
47 * _root.products.product.user → user service
48 * _root.products.variant → product service
49 * }
50 * shortcuts: [{ location: [], property: "product_user_alias", path: ["products","product","user"] }]
51 * stages[0] = root; stages[1] = product + variant; stages[2] = user
52 */
53 export function compileQuery(
54 { query, serviceConfig, options, initialData }: CompileInput,
55 catalog: GraphCatalog
56 ): QueryPlan {
57 const { crossModuleJoins, residualCrossModuleFilters, residualOrderBy } =
58 extractCrossModuleJoins({ query, serviceConfig }, catalog)
59
60 if (crossModuleJoins.length) {
61 query.args ??= []
62 query.args.push({ name: "__internal", value: { crossModuleJoins } })
63 }
64
65 // Stage 2: residual filters/orderings are consumed here (stripped from the
66 // query, their data loaded via injected expands) and completed in memory by
67 // executePlan after the fetch.
68 const residualHiddenProperties =
69 residualCrossModuleFilters.length || residualOrderBy.length
70 ? consumeResiduals(
71 {
72 query,
73 serviceConfig,
74 residualFilters: residualCrossModuleFilters,
75 residualOrderBy,
76 },
77 catalog
78 )
79 : []
80
81 const { primaryKeyArg, otherArgs, pkName } = getPrimaryKeysAndOtherFilters({
82 serviceConfig,
83 queryObj: query,
84 })
85
86 const root: RemoteExpandProperty = {
87 property: "",
88 parent: "",
89 serviceConfig,
90 entity: serviceConfig.entity,
91 fields: query.fields,
92 args: otherArgs,
93 }
94
95 const shortcuts: ShortcutSpec[] = []
96 const { parsedExpands, aliasRealPathMap } = parseProperties(
97 {
98 root,
99 query,
100 serviceConfig,
101 expands: query.expands ?? [],
102 shortcuts,
103 },
104 catalog
105 )
106
107 if (initialData.length && options?.initialDataOnly) {
108 applySeedFilters({
109 initialData,
110 parsedExpands,
111 aliasRealPathMap,
112 catalog,
113 })
114 }
115
116 const grouped = groupSameServiceExpands(parsedExpands)
117 attachExecutionStages(parsedExpands, grouped)
118
119 return {
120 root: grouped.get(BASE_PATH)!,
121 expands: grouped,
122 shortcuts,
123 pkName,
124 primaryKeyArg,
125 otherArgs,
126 initialData,
127 initialDataOnly: options?.initialDataOnly,
128 options,
129 crossModuleJoins,
130 residualCrossModuleFilters,
131 residualHiddenProperties,
132 residualOrderBy,
133 }
134 }
135
136 function parseProperties(
137 params: {
138 root: RemoteExpandProperty
139 query: RemoteJoinerQuery
140 serviceConfig: InternalJoinerServiceConfig
141 expands: NonNullable<RemoteJoinerQuery["expands"]>
142 shortcuts: ShortcutSpec[]
143 },
144 catalog: GraphCatalog
145 ): {
146 parsedExpands: Map<string, RemoteExpandProperty>
147 aliasRealPathMap: Map<string, string[]>
148 } {
149 const { root, query, serviceConfig, expands, shortcuts } = params
150
151 const aliasRealPathMap = new Map<string, string[]>()
152 const parsedExpands = new Map<string, RemoteExpandProperty>()
153 parsedExpands.set(BASE_PATH, root)
154
155 const forwardArgumentsOnPath: string[] = []
156
157 // Intentionally iterate a mutable array: rewriteFieldAlias pushes synthetic
158 // expand entries so the same loop walks rewritten real paths.
159 for (const expand of expands) {
160 const properties = expand.property.split(".")
161 const currentPath: string[] = []
162 const currentAliasPath: string[] = []
163 let currentServiceConfig = serviceConfig
164
165 for (const prop of properties) {
166 const fieldAlias = currentServiceConfig.fieldAlias ?? {}
167 const currentPathEntity =
168 parsedExpands.get([BASE_PATH, ...currentPath].join("."))?.entity ??
169 currentServiceConfig.entity
170 const aliasEntry = resolveFieldAliasEntry(
171 fieldAlias[prop],
172 currentPathEntity
173 )
174
175 if (aliasEntry) {
176 const aliasPath = [BASE_PATH, ...currentPath, prop].join(".")
177
178 currentServiceConfig = rewriteFieldAlias(
179 {
180 aliasPath,
181 aliasRealPathMap,
182 expands,
183 expand,
184 property: prop,
185 aliasEntry,
186 parsedExpands,
187 currentServiceConfig,
188 currentPath,
189 shortcuts,
190 forwardArgumentsOnPath,
191 },
192 catalog
193 )
194
195 currentAliasPath.push(prop)
196 continue
197 }
198
199 const fullPath = [BASE_PATH, ...currentPath, prop].join(".")
200 const fullAliasPath = [BASE_PATH, ...currentAliasPath, prop].join(".")
201
202 let entity = currentServiceConfig.entity
203 if (entity) {
204 const completePath = fullPath.split(".")
205 for (let i = 1; i < completePath.length; i++) {
206 entity = catalog.getEntity(entity, completePath[i]) ?? entity
207 }
208 }
209
210 const relationship = catalog.getEntityRelationship({
211 parentServiceConfig: currentServiceConfig,
212 property: prop,
213 entity,
214 })
215
216 const isCurrentProp =
217 fullPath === BASE_PATH + "." + expand.property ||
218 fullAliasPath === BASE_PATH + "." + expand.property
219
220 let fields: string[] = isCurrentProp ? expand.fields ?? [] : []
221 const args = isCurrentProp ? expand.args : []
222
223 if (relationship) {
224 const parentExpand =
225 parsedExpands.get([BASE_PATH, ...currentPath].join(".")) ||
226 (query as any)
227
228 if (parentExpand) {
229 injectJoinKeys(parentExpand, relationship, "parent")
230 fields = fields.concat(joinKeyFields(relationship, "child"))
231 }
232
233 entity = relationship.entity ?? entity
234
235 currentServiceConfig = catalog.getServiceConfig({
236 serviceName: relationship.serviceName,
237 entity: relationship.entity,
238 })!
239
240 if (!currentServiceConfig) {
241 throw new Error(
242 `Target service not found: ${relationship.serviceName}`
243 )
244 }
245 }
246
247 const isAliasMapping = !!(expand as any).isAliasMapping
248 if (!parsedExpands.has(fullPath)) {
249 let parentPath = [BASE_PATH, ...currentPath].join(".")
250
251 if (aliasRealPathMap.has(parentPath)) {
252 parentPath = aliasRealPathMap.get(parentPath)!.slice(0, -1).join(".")
253 }
254
255 parsedExpands.set(fullPath, {
256 property: prop,
257 serviceConfig: currentServiceConfig,
258 entity,
259 fields,
260 args: isAliasMapping
261 ? forwardArgumentsOnPath.includes(fullPath)
262 ? args
263 : undefined
264 : args,
265 isAliasMapping,
266 parent: parentPath,
267 parentConfig: parsedExpands.get(parentPath)!.serviceConfig,
268 })
269 } else {
270 const exp = parsedExpands.get(fullPath)!
271
272 if (forwardArgumentsOnPath.includes(fullPath) && args) {
273 exp.args = (exp.args || []).concat(args)
274 }
275 exp.isAliasMapping ??= isAliasMapping
276
277 if (fields) {
278 exp.fields = deduplicate((exp.fields ?? []).concat(fields))
279 }
280 }
281
282 currentPath.push(prop)
283 currentAliasPath.push(prop)
284 }
285 }
286
287 return { parsedExpands, aliasRealPathMap }
288 }
289
290 /**
291 * Rewrites a fieldAlias into real relationship hops, records a ShortcutSpec
292 * for post-join collapse, and injects synthetic expand entries for the real path.
293 */
294 function rewriteFieldAlias(
295 params: {
296 aliasPath: string
297 aliasRealPathMap: Map<string, string[]>
298 expands: NonNullable<RemoteJoinerQuery["expands"]>
299 expand: any
300 property: string
301 aliasEntry: ResolvedFieldAlias
302 parsedExpands: Map<string, RemoteExpandProperty>
303 currentServiceConfig: InternalJoinerServiceConfig
304 currentPath: string[]
305 shortcuts: ShortcutSpec[]
306 forwardArgumentsOnPath: string[]
307 },
308 catalog: GraphCatalog
309 ): InternalJoinerServiceConfig {
310 const {
311 aliasPath,
312 aliasRealPathMap,
313 expands,
314 expand,
315 property,
316 aliasEntry,
317 parsedExpands,
318 currentPath,
319 shortcuts,
320 forwardArgumentsOnPath,
321 } = params
322
323 let currentServiceConfig = params.currentServiceConfig
324 const serviceConfig = currentServiceConfig
325 const alias = aliasEntry
326
327 const path = alias.path
328 const fieldAliasIsList = !!alias.isList
329 const fullPath = [...currentPath.concat(path.split("."))]
330
331 if (aliasRealPathMap.has(aliasPath)) {
332 currentPath.push(...path.split("."))
333 const existing = [BASE_PATH, ...currentPath].join(".")
334 return parsedExpands.get(existing)!.serviceConfig
335 }
336
337 const parentPath = [BASE_PATH, ...currentPath].join(".")
338 const parentExpands = parsedExpands.get(parentPath)!
339 parentExpands.fields = parentExpands.fields?.filter(
340 (field) => field !== property
341 )
342
343 forwardArgumentsOnPath.push(
344 ...(alias?.forwardArgumentsOnPath || []).map(
345 (forPath) => BASE_PATH + "." + currentPath.concat(forPath).join(".")
346 )
347 )
348
349 const parentFieldAlias = fullPath[Math.max(fullPath.length - 2, 0)]
350 const parentRel = serviceConfig.relationships?.get(parentFieldAlias)
351 // Match legacy behavior: when multiple relationships share an alias (array),
352 // `.isList` is not read off the array itself. Prefer the fieldAlias flag.
353 const parentRelIsList = Array.isArray(parentRel) ? false : !!parentRel?.isList
354 shortcuts.push({
355 location: [...currentPath],
356 property,
357 path: fullPath,
358 isList: fieldAliasIsList || parentRelIsList,
359 })
360
361 const middlePath = path.split(".")
362 let curMiddlePath = currentPath
363 for (const mid of middlePath) {
364 curMiddlePath = curMiddlePath.concat(mid)
365
366 const midProp = curMiddlePath.join(".")
367 const existingExpand = expands.find((exp) => exp.property === midProp)
368
369 const extraExtends: any = {
370 fields: existingExpand?.fields,
371 args: existingExpand?.args,
372 ...(midProp === fullPath.join(".") ? expand : {}),
373 property: midProp,
374 isAliasMapping: !existingExpand,
375 }
376
377 if (forwardArgumentsOnPath.includes(BASE_PATH + "." + midProp)) {
378 const forwarded = (existingExpand?.args ?? []).concat(expand?.args ?? [])
379 if (forwarded.length) {
380 extraExtends.args = forwarded
381 }
382 }
383
384 expands.push(extraExtends)
385 }
386
387 const partialPath: string[] = []
388 for (const partial of path.split(".")) {
389 const completePath = [
390 BASE_PATH,
391 ...currentPath.concat(partialPath),
392 partial,
393 ]
394 const parent = completePath.slice(0, -1).join(".")
395
396 let entity = serviceConfig.entity
397 if (entity) {
398 for (let i = 1; i < completePath.length; i++) {
399 entity = catalog.getEntity(entity, completePath[i]) ?? entity
400 }
401 }
402
403 const relationship = catalog.getEntityRelationship({
404 parentServiceConfig: currentServiceConfig,
405 property: partial,
406 entity,
407 })
408
409 if (relationship) {
410 entity = relationship.entity ?? entity
411
412 currentServiceConfig = catalog.getServiceConfig({
413 serviceName: relationship.serviceName,
414 entity: relationship.entity,
415 })!
416
417 if (!currentServiceConfig) {
418 throw new Error(`Target service not found: ${relationship.serviceName}`)
419 }
420 }
421
422 partialPath.push(partial)
423 parsedExpands.set(completePath.join("."), {
424 property: partial,
425 serviceConfig: currentServiceConfig,
426 entity,
427 parent,
428 parentConfig: parsedExpands.get(parent)!.serviceConfig,
429 })
430 }
431
432 currentPath.push(...path.split("."))
433 aliasRealPathMap.set(aliasPath, [BASE_PATH, ...currentPath])
434
435 return currentServiceConfig
436 }
437
438 function joinKeyFields(
439 relationship: ComputedJoinerRelationship,
440 side: "parent" | "child"
441 ): string[] {
442 if (side === "parent") {
443 const field = relationship.inverse
444 ? relationship.primaryKey
445 : relationship.foreignKey.split(".").pop()!
446 return field.split(",")
447 }
448
449 const field = relationship.inverse
450 ? relationship.foreignKey.split(".").pop()!
451 : relationship.primaryKey
452 return field.split(",")
453 }
454
455 function injectJoinKeys(
456 parentExpand: { fields?: string[] },
457 relationship: ComputedJoinerRelationship,
458 _side: "parent"
459 ) {
460 parentExpand.fields ??= []
461 parentExpand.fields = parentExpand.fields
462 .concat(joinKeyFields(relationship, "parent"))
463 .filter((field) => field !== relationship.alias)
464 parentExpand.fields = deduplicate(parentExpand.fields)
465 }
466
467 /**
468 * Collapses consecutive same-service hops into nested `expands` on the
469 * nearest cross-service (or root) ancestor.
470 */
471 function groupSameServiceExpands(
472 parsedExpands: Map<string, RemoteExpandProperty>
473 ): Map<string, RemoteExpandProperty> {
474 const mergedExpands = new Map<string, RemoteExpandProperty>(parsedExpands)
475 const mergedPaths = new Map<string, RemoteExpandProperty>()
476
477 for (const [path, expand] of mergedExpands.entries()) {
478 const currentServiceName = expand.serviceConfig.serviceName
479 let parentPath = expand.parent
480
481 while (parentPath) {
482 const parentExpand =
483 mergedExpands.get(parentPath) ?? mergedPaths.get(parentPath)
484 if (
485 !parentExpand ||
486 parentExpand.serviceConfig.serviceName !== currentServiceName
487 ) {
488 break
489 }
490
491 const nestedKeys = path.split(".").slice(parentPath.split(".").length)
492 let targetExpand = parentExpand as Omit<
493 RemoteExpandProperty,
494 "expands"
495 > & {
496 expands?: Record<string, any>
497 }
498
499 for (const key of nestedKeys) {
500 targetExpand.expands ??= {}
501 targetExpand = targetExpand.expands[key] ??= {}
502 }
503
504 targetExpand.fields = [
505 ...new Set([...(targetExpand.fields ?? []), ...(expand.fields ?? [])]),
506 ]
507 if (expand.args?.length) {
508 targetExpand.args = targetExpand.args
509 ? targetExpand.args.concat(expand.args)
510 : expand.args
511 }
512
513 mergedExpands.delete(path)
514 mergedPaths.set(path, expand)
515 parentPath = parentExpand.parent
516 }
517 }
518
519 return mergedExpands
520 }
521
522 /**
523 * Attaches depth-batched execution stages onto the root expand.
524 */
525 function attachExecutionStages(
526 fullParsedExpands: Map<string, RemoteExpandProperty>,
527 groupedExpands: Map<string, RemoteExpandProperty>
528 ): void {
529 const stages: ExecutionStage[][] = []
530
531 const rootExp = groupedExpands.get(BASE_PATH)!
532 stages.push([
533 {
534 service: rootExp.serviceConfig.serviceName,
535 entity: rootExp.entity,
536 paths: [],
537 depth: 0,
538 },
539 ])
540
541 const getServiceSequence = (path: string): string[] => {
542 const sequence: string[] = []
543 let currentPath = path
544
545 while (currentPath && currentPath !== BASE_PATH) {
546 const expand = fullParsedExpands.get(currentPath)
547 if (!expand) {
548 break
549 }
550 sequence.unshift(expand.serviceConfig.serviceName)
551 currentPath = expand.parent
552 }
553 return sequence
554 }
555
556 const pathsBySequenceDepth = new Map<number, Map<string, string[]>>()
557
558 for (const [path, expand] of groupedExpands.entries()) {
559 if (path === BASE_PATH) {
560 continue
561 }
562
563 const sequenceDepth = getServiceSequence(path).length
564 const lastService = expand.serviceConfig.serviceName
565
566 if (!pathsBySequenceDepth.has(sequenceDepth)) {
567 pathsBySequenceDepth.set(sequenceDepth, new Map())
568 }
569
570 const depthMap = pathsBySequenceDepth.get(sequenceDepth)!
571 if (!depthMap.has(lastService)) {
572 depthMap.set(lastService, [])
573 }
574 depthMap.get(lastService)!.push(path)
575 }
576
577 const depths = Array.from(pathsBySequenceDepth.keys())
578 const maxDepth = depths.length ? Math.max(...depths) : 0
579
580 for (let depth = 1; depth <= maxDepth; depth++) {
581 const serviceMap = pathsBySequenceDepth.get(depth)
582 if (!serviceMap) {
583 continue
584 }
585
586 const stageGroups: ExecutionStage[] = []
587 for (const [service, paths] of serviceMap.entries()) {
588 stageGroups.push({ service, paths, depth })
589 }
590 if (stageGroups.length) {
591 stages.push(stageGroups)
592 }
593 }
594
595 rootExp.executionStages = stages
596 }
597
598 function applySeedFilters(params: {
599 initialData: any[]
600 parsedExpands: Map<string, RemoteExpandProperty>
601 aliasRealPathMap: Map<string, string[]>
602 catalog: GraphCatalog
603 }): void {
604 const { initialData, parsedExpands, aliasRealPathMap, catalog } = params
605
606 if (!initialData.length) {
607 return
608 }
609
610 const getPkValues = ({
611 data,
612 serviceConfig,
613 relationship,
614 }: {
615 data: any[]
616 serviceConfig: InternalJoinerServiceConfig
617 relationship?: any
618 }): Record<string, any> => {
619 if (!data.length || !relationship || !serviceConfig) {
620 return {}
621 }
622
623 const primaryKeys = relationship.primaryKey
624 ? relationship.primaryKey.split(",")
625 : serviceConfig.primaryKeys
626
627 const filter: Record<string, any> = {}
628 primaryKeys.forEach((key) => {
629 filter[key] = Array.from(
630 new Set(data.map((dt) => dt[key]).filter(isDefined))
631 )
632 })
633 return filter
634 }
635
636 const parsedSegment = new Map<string, any>()
637 const aliasReversePathMap = new Map<string, string>(
638 Array.from(aliasRealPathMap).map(([path, realPath]) => [
639 realPath.join("."),
640 path,
641 ])
642 )
643
644 for (let [path, expand] of parsedExpands.entries()) {
645 const serviceConfig = expand.serviceConfig
646 const relationship =
647 catalog.getEntityRelationship({
648 parentServiceConfig: expand.parentConfig!,
649 property: expand.property,
650 }) ?? serviceConfig.relationships?.get(serviceConfig.serviceName)
651
652 if (!serviceConfig || !relationship) {
653 continue
654 }
655
656 let aliasToPath: string | null = null
657 if (aliasReversePathMap.has(path)) {
658 aliasToPath = path
659 path = aliasReversePathMap.get(path)!
660 }
661
662 const pathSegments = path.split(".")
663 let relevantInitialData = initialData
664 const fullPath: string[] = []
665
666 for (const segment of pathSegments) {
667 fullPath.push(segment)
668 if (segment === BASE_PATH) {
669 continue
670 }
671
672 const pathStr = fullPath.join(".")
673 if (parsedSegment.has(pathStr)) {
674 relevantInitialData = parsedSegment.get(pathStr)
675 continue
676 }
677
678 relevantInitialData = getNestedItems(relevantInitialData, segment) ?? []
679 parsedSegment.set(pathStr, relevantInitialData)
680
681 if (!relevantInitialData.length) {
682 break
683 }
684 }
685
686 if (!relevantInitialData.length) {
687 continue
688 }
689
690 const queryPath = expand.parent === "" ? BASE_PATH : aliasToPath ?? path
691 const filter = getPkValues({
692 data: relevantInitialData,
693 serviceConfig,
694 relationship,
695 })
696
697 if (!Object.keys(filter).length) {
698 continue
699 }
700
701 const parsed = parsedExpands.get(queryPath)!
702 parsed.args ??= []
703 parsed.args.push({ name: "filters", value: filter })
704 }
705 }
706
707 function getPrimaryKeysAndOtherFilters({
708 serviceConfig,
709 queryObj,
710 }: {
711 serviceConfig: { primaryKeys: string[]; entity?: string; serviceName: string }
712 queryObj: { args?: { name: string; value?: any }[] }
713 }): {
714 primaryKeyArg: { name: string; value?: any } | undefined
715 otherArgs: { name: string; value?: any }[] | undefined
716 pkName: string
717 } {
718 let pkName = serviceConfig.primaryKeys[0]
719 let primaryKeyArg = queryObj.args?.find((arg) => {
720 const include = serviceConfig.primaryKeys.includes(arg.name)
721 if (include) {
722 pkName = arg.name
723 }
724 return include
725 })
726
727 let otherArgs = queryObj.args?.filter(
728 (arg) => !serviceConfig.primaryKeys.includes(arg.name)
729 )
730
731 if (!primaryKeyArg) {
732 const filters =
733 queryObj.args?.find((arg) => arg.name === "filters")?.value ?? {}
734
735 const primaryKeyFilter = Object.keys(filters).find((key) =>
736 serviceConfig.primaryKeys.includes(key)
737 )
738
739 if (primaryKeyFilter) {
740 pkName = primaryKeyFilter
741 primaryKeyArg = {
742 name: primaryKeyFilter,
743 value: filters[primaryKeyFilter],
744 }
745
746 Object.defineProperty(filters, primaryKeyFilter, {
747 value: undefined,
748 enumerable: false,
749 })
750 }
751 }
752
753 otherArgs = otherArgs?.length ? otherArgs : undefined
754
755 return { primaryKeyArg, otherArgs, pkName }
756 }