1 import {
2 cleanGraphQLSchema,
3 GraphQLObjectType,
4 graphqlSchemaToFields,
5 isListType,
6 isNonNullType,
7 kebabCase,
8 makeExecutableSchema,
9 mergeTypeDefs,
10 pluralize,
11 print,
12 singularize,
13 } from "@medusajs/framework/utils"
14
15 /**
16 * Joiner config interface (subset of what we need).
17 */
18 export interface JoinerConfig {
19 serviceName?: string
20 schema?: string
21 primaryKeys?: string[]
22 linkableKeys?: Record<string, string>
23 isLink?: boolean
24 }
25
26 /**
27 * Convert PascalCase to kebab-case with pluralization.
28 */
29 export function toKebabCasePlural(name: string): string {
30 const kebab = kebabCase(name)
31
32 return pluralize(kebab)
33 }
34
35 /**
36 * Normalize entity name to PascalCase.
37 */
38 function normalizeEntityName(name: string): string {
39 // Handle kebab-case (e.g., "sales-channels" -> "SalesChannel")
40 if (name.includes("-")) {
41 return singularize(
42 name
43 .split("-")
44 .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
45 .join("")
46 )
47 }
48
49 // Handle snake_case (e.g., "sales_channel" -> "SalesChannel")
50 if (name.includes("_")) {
51 return singularize(
52 name
53 .split("_")
54 .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
55 .join("")
56 )
57 }
58
59 // Already PascalCase or camelCase
60 return singularize(name.charAt(0).toUpperCase() + name.slice(1))
61 }
62
63 /**
64 * Discovered entity metadata.
65 */
66 export interface DiscoveredEntity {
67 name: string
68 pluralName: string
69 module: string
70 graphqlType: string
71 schema: string
72 primaryKeys: string[]
73 linkableKeys: Record<string, string>
74 }
75
76 /**
77 * Schema type map from merged GraphQL schemas.
78 */
79 export interface SchemaTypeMap {
80 [key: string]: GraphQLObjectType | any
81 }
82
83 /**
84 * Entity info as returned by the API.
85 */
86 export interface EntityInfo {
87 name: string
88 pluralName: string
89 module: string
90 propertyCount: number
91 hasOverrides: boolean
92 }
93
94 /**
95 * Service for discovering entities from joiner configs.
96 * Unlike the API version, this service requires explicit initialization
97 * with joiner configs (typically in onApplicationStart hook).
98 */
99 export class EntityDiscoveryService {
100 private schemaTypeMap: SchemaTypeMap | null = null
101 private discoveredEntities: DiscoveredEntity[] | null = null
102 private joinerConfigs: JoinerConfig[] = []
103 private initialized: boolean = false
104
105 /**
106 * Initialize the service with joiner configs.
107 * Should be called from onApplicationStart hook.
108 */
109 initialize(joinerConfigs: JoinerConfig[]): void {
110 this.joinerConfigs = joinerConfigs
111 this.initialized = true
112 // Clear cache when reinitializing
113 this.schemaTypeMap = null
114 this.discoveredEntities = null
115 }
116
117 /**
118 * Check if the service has been initialized.
119 */
120 isInitialized(): boolean {
121 return this.initialized
122 }
123
124 /**
125 * Build and cache the merged schema type map.
126 */
127 getSchemaTypeMap(): SchemaTypeMap {
128 if (!this.initialized) {
129 return {}
130 }
131
132 if (this.schemaTypeMap) {
133 return this.schemaTypeMap
134 }
135
136 const schemaFragments: string[] = []
137
138 for (const config of this.joinerConfigs) {
139 if (config.schema) {
140 schemaFragments.push(config.schema)
141 }
142 }
143
144 if (schemaFragments.length === 0) {
145 return {}
146 }
147
148 const scalarDefinitions = `
149 scalar DateTime
150 scalar JSON
151 `
152
153 const allSchemas = [scalarDefinitions, ...schemaFragments]
154 const mergedSchemaAST = mergeTypeDefs(allSchemas)
155 const mergedSchemaString = print(mergedSchemaAST)
156 const { schema: cleanedSchemaString } =
157 cleanGraphQLSchema(mergedSchemaString)
158
159 const schema = makeExecutableSchema({
160 typeDefs: cleanedSchemaString,
161 resolvers: {},
162 })
163
164 this.schemaTypeMap = schema.getTypeMap()
165 return this.schemaTypeMap
166 }
167
168 /**
169 * Discover all entities from joiner configs.
170 * Filters out link configs and returns metadata about each entity.
171 */
172 discoverEntities(): DiscoveredEntity[] {
173 if (!this.initialized) {
174 return []
175 }
176
177 if (this.discoveredEntities) {
178 return this.discoveredEntities
179 }
180
181 const entities: DiscoveredEntity[] = []
182 const seenTypes = new Set<string>()
183
184 for (const config of this.joinerConfigs) {
185 // Skip link configs
186 if (config.isLink) {
187 continue
188 }
189
190 // Skip if no schema
191 if (!config.schema) {
192 continue
193 }
194
195 const serviceName = config.serviceName || ""
196
197 // Extract type name from schema by finding "type <Name> {"
198 const typeMatches = config.schema.matchAll(/type\s+(\w+)\s*\{/g)
199
200 for (const match of typeMatches) {
201 const typeName = match[1]
202
203 // Skip if we've already seen this type
204 if (seenTypes.has(typeName)) {
205 continue
206 }
207
208 // Skip utility types
209 if (
210 typeName.endsWith("Link") ||
211 typeName.startsWith("_") ||
212 typeName === "Query" ||
213 typeName === "Mutation"
214 ) {
215 continue
216 }
217
218 seenTypes.add(typeName)
219
220 entities.push({
221 name: typeName,
222 pluralName: toKebabCasePlural(typeName),
223 module: serviceName,
224 graphqlType: typeName,
225 schema: config.schema,
226 primaryKeys: config.primaryKeys || ["id"],
227 linkableKeys: config.linkableKeys || {},
228 })
229 }
230 }
231
232 this.discoveredEntities = entities
233 return entities
234 }
235
236 /**
237 * Get an entity by name.
238 * Supports PascalCase, kebab-case, snake_case, and plural forms.
239 */
240 getEntity(name: string): DiscoveredEntity | null {
241 const entities = this.discoverEntities()
242
243 // Try direct match on name
244 let entity = entities.find(
245 (e) => e.name.toLowerCase() === name.toLowerCase()
246 )
247 if (entity) {
248 return entity
249 }
250
251 // Try plural name match
252 entity = entities.find(
253 (e) => e.pluralName.toLowerCase() === name.toLowerCase()
254 )
255 if (entity) {
256 return entity
257 }
258
259 // Try normalizing the input name
260 const normalized = normalizeEntityName(name)
261 entity = entities.find(
262 (e) => e.name.toLowerCase() === normalized.toLowerCase()
263 )
264 if (entity) {
265 return entity
266 }
267
268 return null
269 }
270
271 /**
272 * Check if an entity exists by name.
273 */
274 hasEntity(name: string): boolean {
275 return this.getEntity(name) !== null
276 }
277
278 /**
279 * Get the GraphQL type for an entity.
280 */
281 getEntityType(entityName: string): GraphQLObjectType | null {
282 const entity = this.getEntity(entityName)
283 if (!entity) {
284 return null
285 }
286
287 const schemaTypeMap = this.getSchemaTypeMap()
288 return schemaTypeMap[entity.graphqlType] as GraphQLObjectType | null
289 }
290
291 /**
292 * Get fields for an entity type.
293 */
294 getEntityFields(entityName: string): string[] {
295 const entity = this.getEntity(entityName)
296 if (!entity) {
297 return []
298 }
299
300 const schemaTypeMap = this.getSchemaTypeMap()
301 return graphqlSchemaToFields(schemaTypeMap, entity.graphqlType, [])
302 }
303
304 /**
305 * Get entity info for the API response.
306 */
307 getEntityInfo(entity: DiscoveredEntity, hasOverrides: boolean): EntityInfo {
308 const schemaTypeMap = this.getSchemaTypeMap()
309 const entityType = schemaTypeMap[entity.graphqlType] as
310 | GraphQLObjectType
311 | undefined
312 const fieldCount = entityType?.getFields
313 ? Object.keys(entityType.getFields()).length
314 : 0
315
316 return {
317 name: entity.name,
318 pluralName: entity.pluralName,
319 module: entity.module,
320 propertyCount: fieldCount,
321 hasOverrides,
322 }
323 }
324
325 /**
326 * Clear the cache (useful for testing).
327 */
328 clearCache(): void {
329 this.schemaTypeMap = null
330 this.discoveredEntities = null
331 }
332 }
333
334 /**
335 * Helper to get the underlying type from wrapped types (NonNull, List).
336 */
337 export function getUnderlyingType(type: any): any {
338 if (type.ofType) {
339 return getUnderlyingType(type.ofType)
340 }
341 return type
342 }
343
344 /**
345 * Helper to check if a field type is an array/list.
346 */
347 export function isArrayField(type: any): boolean {
348 if (isListType(type)) {
349 return true
350 }
351 if (isNonNullType(type)) {
352 return isArrayField(type.ofType)
353 }
354 return false
355 }
356
357 /**
358 * Helper to check if a field is a single relationship (many-to-one, one-to-one).
359 */
360 export function isSingleRelationship(type: any): boolean {
361 if (isArrayField(type)) {
362 return false
363 }
364
365 const underlyingType = getUnderlyingType(type)
366 return underlyingType instanceof GraphQLObjectType
367 }
368
369 export { isListType, isNonNullType }