1 import { isDefined, isString } from "@medusajs/utils"
2
3 export type ResolvedFieldAlias = {
4 path: string
5 isList?: boolean
6 forwardArgumentsOnPath?: string[]
7 entity?: string
8 }
9
10 /**
11 * Resolves a fieldAlias config entry (string, object, or entity-scoped array)
12 * to the entry applicable for the current path's entity.
13 */
14 export function resolveFieldAliasEntry(
15 alias: unknown,
16 currentPathEntity?: string
17 ): ResolvedFieldAlias | undefined {
18 if (!alias) {
19 return undefined
20 }
21
22 if (Array.isArray(alias)) {
23 if (!currentPathEntity) {
24 return alias[0] as ResolvedFieldAlias
25 }
26
27 return (
28 (alias.find((entry) => entry.entity == currentPathEntity) as
29 | ResolvedFieldAlias
30 | undefined) ?? (alias[0] as ResolvedFieldAlias)
31 )
32 }
33
34 if (isString(alias)) {
35 return { path: alias }
36 }
37
38 // Match legacy RemoteJoiner behavior: a singular entity-scoped alias object
39 // is always applied when the property name hits. Entity filtering only
40 // applies when multiple aliases share the same property (array form above).
41 return alias as ResolvedFieldAlias
42 }
43
44 /**
45 * Collects all defined values of `property` across items (flattens arrays).
46 */
47 export function getNestedItems(items: any[], property: string): any[] {
48 const result: unknown[] = []
49 for (const item of items) {
50 const allValues = item?.[property] ?? []
51 const values = Array.isArray(allValues) ? allValues : [allValues]
52 for (const value of values) {
53 if (isDefined(value)) {
54 result.push(value)
55 }
56 }
57 }
58 return result
59 }