1 import { SearchTypes } from "@medusajs/types"
2
3 /**
4 * Document projection helpers shared by search providers, so that path
5 * flattening, value coercion and primary-key handling behave identically no
6 * matter which engine an index definition runs on.
7 */
8
9 /**
10 * Walks a dotted path, flattening through arrays encountered on the way —
11 * arrays of objects collapse to per-leaf arrays, which keeps index
12 * definitions portable across providers.
13 */
14 export function readDocumentPath(
15 source: unknown,
16 segments: string[]
17 ): unknown[] {
18 let current: unknown[] = [source]
19
20 for (const segment of segments) {
21 const next: unknown[] = []
22
23 for (const value of current) {
24 if (value === null || value === undefined) {
25 continue
26 }
27 if (Array.isArray(value)) {
28 for (const entry of value) {
29 const resolved = (entry as Record<string, unknown>)?.[segment]
30 if (resolved !== undefined) {
31 next.push(resolved)
32 }
33 }
34 continue
35 }
36 const resolved = (value as Record<string, unknown>)?.[segment]
37 if (resolved !== undefined) {
38 next.push(resolved)
39 }
40 }
41
42 current = next
43 }
44
45 return current.flat(Infinity).filter((v) => v !== null && v !== undefined)
46 }
47
48 /** Writes a value at a dotted path, creating intermediate objects. */
49 export function setDocumentPath(
50 target: Record<string, any>,
51 path: string,
52 value: unknown
53 ): void {
54 const segments = path.split(".")
55 let cursor = target
56
57 for (const segment of segments.slice(0, -1)) {
58 cursor[segment] ??= {}
59 cursor = cursor[segment]
60 }
61
62 cursor[segments[segments.length - 1]] = value
63 }
64
65 export function searchValueToNumber(
66 value: unknown,
67 isDate: boolean
68 ): number | undefined {
69 const num = isDate
70 ? value instanceof Date
71 ? value.getTime()
72 : Date.parse(String(value))
73 : typeof value === "number"
74 ? value
75 : Number(value)
76
77 return Number.isNaN(num) ? undefined : num
78 }
79
80 export function searchValueToBoolean(value: unknown): boolean {
81 if (typeof value === "boolean") {
82 return value
83 }
84 // `Boolean("false")` is `true`, so string forms are read by content.
85 if (value === "true" || value === "false") {
86 return value === "true"
87 }
88 return Boolean(value)
89 }
90
91 /**
92 * Narrows a source document to the requested dotted paths, keeping the shape
93 * of intermediate objects and arrays.
94 */
95 export function projectDocument(
96 source: Record<string, unknown>,
97 paths: string[]
98 ): Record<string, unknown> {
99 const picked: Record<string, any> = {}
100
101 for (const path of paths) {
102 const segments = path.split(".")
103 const [head, ...rest] = segments
104 const value = source?.[head]
105
106 if (value === undefined) {
107 continue
108 }
109
110 if (!rest.length) {
111 picked[head] = value
112 continue
113 }
114
115 // Recurse so that `variants.title` keeps the shape of `variants`.
116 if (Array.isArray(value)) {
117 const existing = Array.isArray(picked[head]) ? picked[head] : []
118 picked[head] = value.map((entry, i) =>
119 Object.assign(
120 existing[i] ?? {},
121 projectDocument(entry as Record<string, unknown>, [rest.join(".")])
122 )
123 )
124 } else if (value && typeof value === "object") {
125 picked[head] = Object.assign(
126 picked[head] ?? {},
127 projectDocument(value as Record<string, unknown>, [rest.join(".")])
128 )
129 }
130 }
131
132 return picked
133 }
134
135 /**
136 * Recognises a filter that is nothing but primary-key membership, so a delete
137 * can go straight to the id lookup instead of compiling the filter tree.
138 */
139 export function extractPrimaryKeyFilter(
140 filters: SearchTypes.SearchFilters,
141 plan: { primary_key: string }
142 ): string[] | undefined {
143 const keys = Object.keys(filters)
144
145 if (keys.length !== 1 || keys[0] !== plan.primary_key) {
146 return undefined
147 }
148
149 const predicate = filters[plan.primary_key]
150
151 const asIds = (value: unknown): string[] | undefined => {
152 const values = Array.isArray(value) ? value : [value]
153 return values.every((v) => typeof v === "string")
154 ? (values as string[])
155 : undefined
156 }
157
158 if (predicate === null || typeof predicate !== "object") {
159 return asIds(predicate)
160 }
161
162 if (Array.isArray(predicate)) {
163 return asIds(predicate)
164 }
165
166 const operators = Object.keys(predicate)
167
168 if (operators.length !== 1) {
169 return undefined
170 }
171
172 if (operators[0] === "$eq" || operators[0] === "$in") {
173 return asIds((predicate as Record<string, unknown>)[operators[0]])
174 }
175
176 return undefined
177 }