1 import { existsSync, promises as fs } from "fs"
2 import { fdir } from "fdir"
3 import { OpenAPIV3 } from "openapi-types"
4 import path from "path"
5 import ts from "typescript"
6 import { parse, stringify } from "yaml"
7 import GeneratorEventManager from "../classes/helpers/generator-event-manager.js"
8 import OasSchemaHelper from "../classes/helpers/oas-schema.js"
9 import OasKindGenerator, { OasArea } from "../classes/kinds/oas.js"
10 import { DEFAULT_OAS_RESPONSES } from "../constants.js"
11 import { OpenApiDocument, OpenApiSchema } from "../types/index.js"
12 import getMonorepoRoot from "../utils/get-monorepo-root.js"
13 import { getOasOutputBasePath } from "../utils/get-output-base-paths.js"
14 import parseOas from "../utils/parse-oas.js"
15
16 const OAS_PREFIX_REGEX = /@oas \[(?<method>(get|post|delete))\] (?<path>.+)/
17
18 const ignoreSchemas = [
19 "AuthResponse",
20 "AuthCallbackResponse",
21 "AuthAdminSessionResponse",
22 "AuthStoreSessionResponse",
23 ]
24
25 const ignoreTags = {
26 admin: ["Auth"],
27 store: ["Auth"],
28 }
29
30 type OasFileInfo = {
31 file: string
32 area: OasArea
33 oas: ReturnType<typeof parseOas>
34 normalizedPath: string
35 sourceFilePath: string
36 method: string
37 }
38
39 export default async function () {
40 const oasOutputBasePath = getOasOutputBasePath()
41 const oasOperationsPath = path.join(oasOutputBasePath, "operations")
42 const monorepoRoot = getMonorepoRoot()
43 const apiRoutesPaths = [
44 path.join(
45 monorepoRoot,
46 "packages",
47 "medusa",
48 "src",
49 "api"
50 ),
51 path.join(
52 monorepoRoot,
53 "packages",
54 "plugins",
55 "loyalty",
56 "src",
57 "api"
58 ),
59 ]
60 const areas: OasArea[] = ["admin", "store"]
61 const tags: Map<OasArea, Set<string>> = new Map()
62 const oasSchemaHelper = new OasSchemaHelper()
63 const referencedSchemas: Set<string> = new Set()
64 const allSchemas: Set<string> = new Set()
65 areas.forEach((area) => {
66 tags.set(area, new Set<string>())
67 })
68
69 const testAndFindReferenceSchema = (
70 nestedSchema: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject
71 ) => {
72 if (oasSchemaHelper.isRefObject(nestedSchema)) {
73 referencedSchemas.add(
74 oasSchemaHelper.normalizeSchemaName(nestedSchema.$ref)
75 )
76 } else {
77 findReferencedSchemas(nestedSchema)
78 }
79 }
80
81 const findReferencedSchemas = (schema: OpenApiSchema) => {
82 if (schema.properties) {
83 Object.values(schema.properties).forEach(testAndFindReferenceSchema)
84 }
85 if (schema.oneOf || schema.allOf || schema.anyOf) {
86 Object.values((schema.oneOf || schema.allOf || schema.anyOf)!).forEach(
87 testAndFindReferenceSchema
88 )
89 }
90 if (schema.type === "array" && schema.items) {
91 testAndFindReferenceSchema(schema.items)
92 }
93 if (
94 schema.additionalProperties &&
95 typeof schema.additionalProperties === "object"
96 ) {
97 testAndFindReferenceSchema(schema.additionalProperties)
98 }
99 }
100
101 console.log("Cleaning OAS files...")
102
103 // Step 1: Crawl all directories in parallel
104 const [operationFilesByArea, baseFiles, schemaFiles] = await Promise.all([
105 Promise.all(
106 areas.map(async (area) => {
107 const areaPath = path.join(oasOperationsPath, area)
108 if (!existsSync(areaPath)) {
109 return { area, files: [] as string[] }
110 }
111 const files = await new fdir()
112 .withFullPaths()
113 .crawl(areaPath)
114 .withPromise()
115 return { area, files: files as string[] }
116 })
117 ),
118 (async () => {
119 const oasBasePath = path.join(oasOutputBasePath, "base")
120 return (await new fdir()
121 .withFullPaths()
122 .crawl(oasBasePath)
123 .withPromise()) as string[]
124 })(),
125 (async () => {
126 const oasSchemasPath = path.join(oasOutputBasePath, "schemas")
127 return (await new fdir()
128 .withFullPaths()
129 .crawl(oasSchemasPath)
130 .withPromise()) as string[]
131 })(),
132 ])
133
134 // Step 2: Parse all OAS files in parallel and collect valid ones
135 const oasFileInfos: OasFileInfo[] = []
136 const filesToDelete: string[] = []
137 // Keep track of all valid OAS files for tag/schema collection (including auth files)
138 const allValidOasFiles: Array<{
139 file: string
140 area: OasArea
141 oas: ReturnType<typeof parseOas>
142 }> = []
143
144 await Promise.all(
145 operationFilesByArea.flatMap(({ area, files }) =>
146 files.map(async (oasFile) => {
147 try {
148 const content = await fs.readFile(oasFile, "utf-8")
149 const parsed = parseOas(content)
150
151 if (!parsed?.oas || !parsed.oasPrefix) {
152 filesToDelete.push(oasFile)
153 return
154 }
155
156 // Add to all valid OAS files for tag/schema collection
157 allValidOasFiles.push({ file: oasFile, area, oas: parsed })
158
159 const matchOasPrefix = OAS_PREFIX_REGEX.exec(parsed.oasPrefix)
160 if (
161 !matchOasPrefix?.groups?.method ||
162 !matchOasPrefix.groups.path ||
163 matchOasPrefix.groups.path.startsWith("/auth/")
164 ) {
165 // Skip route validation for auth files, but keep them for tag/schema collection
166 return
167 }
168
169 const splitPath = matchOasPrefix.groups.path.substring(1).split("/")
170 const normalizedOasPrefix = splitPath
171 .map((item) => item.replace(/^\{(.+)\}$/, "[$1]"))
172 .join("/")
173 let sourceFilePath = ""
174
175 // Try to find the source file in both API paths
176 for (const apiPath of apiRoutesPaths) {
177 const potentialSourceFile = path.join(
178 apiPath,
179 normalizedOasPrefix,
180 "route.ts"
181 )
182 if (existsSync(potentialSourceFile)) {
183 sourceFilePath = potentialSourceFile
184 break
185 }
186 }
187
188 oasFileInfos.push({
189 file: oasFile,
190 area,
191 oas: parsed,
192 normalizedPath: normalizedOasPrefix,
193 sourceFilePath,
194 method: matchOasPrefix.groups.method.toLowerCase(),
195 })
196 } catch (error) {
197 // If file can't be read or parsed, mark for deletion
198 filesToDelete.push(oasFile)
199 }
200 })
201 )
202 )
203
204 // Step 3: Create a single TypeScript program for all route files
205 const sourceFilePaths = Array.from(
206 new Set(
207 oasFileInfos
208 .filter((info) => !info.oas?.oas?.["x-ignoreCleanup"])
209 .map((info) => info.sourceFilePath)
210 .filter((filePath) => existsSync(filePath))
211 )
212 )
213
214 // Create a single program and cache source files and generators
215 let program: ts.Program | null = null
216 let checker: ts.TypeChecker | null = null
217 let oasKindGenerator: OasKindGenerator | null = null
218 const sourceFileCache = new Map<string, ts.SourceFile | null>()
219 const fileValidationCache = new Map<
220 string,
221 { sourceFile: ts.SourceFile; generator: OasKindGenerator } | null
222 >()
223
224 if (sourceFilePaths.length > 0) {
225 try {
226 program = ts.createProgram(sourceFilePaths, {})
227 checker = program.getTypeChecker()
228 oasKindGenerator = new OasKindGenerator({
229 checker,
230 generatorEventManager: new GeneratorEventManager(),
231 additionalOptions: {},
232 })
233
234 // Cache all source files that are successfully loaded
235 sourceFilePaths.forEach((filePath) => {
236 const sourceFile = program!.getSourceFile(filePath) ?? null
237 sourceFileCache.set(filePath, sourceFile)
238 if (sourceFile && oasKindGenerator) {
239 fileValidationCache.set(filePath, {
240 sourceFile,
241 generator: oasKindGenerator,
242 })
243 } else {
244 fileValidationCache.set(filePath, null)
245 }
246 })
247 } catch (error) {
248 // If batch program creation fails, we'll fall back to individual programs
249 console.warn(
250 "Batch program creation failed, falling back to individual programs"
251 )
252 }
253 }
254
255 // Helper function to check if method exists in a source file
256 const checkMethodExists = (
257 sourceFile: ts.SourceFile,
258 method: string,
259 kindGenerator: OasKindGenerator
260 ): boolean => {
261 let exists = false
262 const visitChildren = (node: ts.Node) => {
263 if (
264 !exists &&
265 kindGenerator.isAllowed(node) &&
266 kindGenerator.canDocumentNode(node) &&
267 kindGenerator.getHTTPMethodName(node) === method
268 ) {
269 exists = true
270 } else if (!exists) {
271 ts.forEachChild(node, visitChildren)
272 }
273 }
274 ts.forEachChild(sourceFile, visitChildren)
275 return exists
276 }
277
278 // Step 4: Check which OAS files should be kept (parallel processing)
279 const BATCH_SIZE = 100
280 const validOasFiles: OasFileInfo[] = []
281
282 for (let i = 0; i < oasFileInfos.length; i += BATCH_SIZE) {
283 const batch = oasFileInfos.slice(i, i + BATCH_SIZE)
284 await Promise.all(
285 batch.map(async (info) => {
286 const { file, oas, sourceFilePath, method } = info
287
288 if (!oas?.oas) {
289 return
290 }
291
292 if (oas.oas["x-ignoreCleanup"]) {
293 validOasFiles.push(info)
294 return
295 }
296
297 // Check if route file exists
298 if (!existsSync(sourceFilePath)) {
299 filesToDelete.push(file)
300 return
301 }
302
303 // Try to use cached validation data first (fast path)
304 const cached = fileValidationCache.get(sourceFilePath)
305 if (cached) {
306 const exists = checkMethodExists(
307 cached.sourceFile,
308 method,
309 cached.generator
310 )
311 if (exists) {
312 validOasFiles.push(info)
313 } else {
314 filesToDelete.push(file)
315 }
316 return
317 }
318 })
319 )
320 }
321
322 // Step 5: Collect tags and schemas from ALL valid OAS files (parallel)
323 // This includes files that passed route validation AND files that were skipped (like auth files)
324 await Promise.all(
325 allValidOasFiles.map(async ({ oas, area }) => {
326 if (!oas?.oas) {
327 return
328 }
329
330 const oasObj = oas.oas
331
332 // collect tags
333 oasObj.tags?.forEach((tag) => {
334 const areaTags = tags.get(area)
335 areaTags?.add(tag)
336 })
337
338 // collect schemas
339 oasObj.parameters?.forEach((parameter) => {
340 if (oasSchemaHelper.isRefObject(parameter)) {
341 referencedSchemas.add(
342 oasSchemaHelper.normalizeSchemaName(parameter.$ref)
343 )
344 return
345 }
346
347 if (!parameter.schema) {
348 return
349 }
350
351 if (oasSchemaHelper.isRefObject(parameter.schema)) {
352 referencedSchemas.add(
353 oasSchemaHelper.normalizeSchemaName(parameter.schema.$ref)
354 )
355 return
356 }
357
358 testAndFindReferenceSchema(parameter.schema)
359 })
360
361 if (oasObj.requestBody) {
362 if (oasSchemaHelper.isRefObject(oasObj.requestBody)) {
363 referencedSchemas.add(
364 oasSchemaHelper.normalizeSchemaName(oasObj.requestBody.$ref)
365 )
366 } else {
367 const requestBodySchema =
368 oasObj.requestBody.content[
369 Object.keys(oasObj.requestBody.content)[0]
370 ].schema
371 if (requestBodySchema) {
372 testAndFindReferenceSchema(requestBodySchema)
373 }
374 }
375 }
376
377 if (oasObj.responses) {
378 const successResponseKey = Object.keys(oasObj.responses)[0]
379 if (!Object.keys(DEFAULT_OAS_RESPONSES).includes(successResponseKey)) {
380 const responseObj = oasObj.responses[successResponseKey]
381 if (oasSchemaHelper.isRefObject(responseObj)) {
382 referencedSchemas.add(
383 oasSchemaHelper.normalizeSchemaName(responseObj.$ref)
384 )
385 } else if (responseObj.content) {
386 const responseBodySchema =
387 responseObj.content[Object.keys(responseObj.content)[0]].schema
388 if (responseBodySchema) {
389 testAndFindReferenceSchema(responseBodySchema)
390 }
391 }
392 }
393 }
394 })
395 )
396
397 // Step 6: Delete invalid OAS files in parallel batches
398 for (let i = 0; i < filesToDelete.length; i += BATCH_SIZE) {
399 const batch = filesToDelete.slice(i, i + BATCH_SIZE)
400 await Promise.all(
401 batch.map(async (file) => {
402 await fs.unlink(file).catch(() => {})
403 })
404 )
405 }
406
407 console.log("Clean tags...")
408
409 // Step 7: Process base files in parallel
410 await Promise.all(
411 baseFiles.map(async (baseYaml) => {
412 try {
413 const content = await fs.readFile(baseYaml, "utf-8")
414 const parsedBaseYaml = parse(content) as OpenApiDocument
415
416 const area = path.basename(baseYaml).split(".")[0] as OasArea
417 const areaTags = tags.get(area)
418 if (!areaTags) {
419 return
420 }
421 const lengthBefore = parsedBaseYaml.tags?.length || 0
422
423 parsedBaseYaml.tags = parsedBaseYaml.tags?.filter(
424 (tag) => areaTags.has(tag.name) || ignoreTags[area].includes(tag.name)
425 )
426
427 if (lengthBefore !== (parsedBaseYaml.tags?.length || 0)) {
428 // sort alphabetically
429 parsedBaseYaml.tags?.sort((tagA, tagB) => {
430 return tagA.name.localeCompare(tagB.name)
431 })
432 // write to the file
433 await fs.writeFile(baseYaml, stringify(parsedBaseYaml))
434 }
435
436 // collect referenced schemas
437 parsedBaseYaml.tags?.forEach((tag) => {
438 if (tag["x-associatedSchema"]) {
439 referencedSchemas.add(
440 oasSchemaHelper.normalizeSchemaName(
441 tag["x-associatedSchema"].$ref
442 )
443 )
444 }
445 })
446 } catch (error) {
447 // Skip files that can't be read/parsed
448 }
449 })
450 )
451
452 console.log("Clean schemas...")
453
454 // Step 8: Process schema files in parallel
455 const schemasToDelete: string[] = []
456
457 await Promise.all(
458 schemaFiles.map(async (schemaYaml) => {
459 try {
460 const content = await fs.readFile(schemaYaml, "utf-8")
461 const parsedSchema = oasSchemaHelper.parseSchema(content)
462
463 if (!parsedSchema) {
464 schemasToDelete.push(schemaYaml)
465 return
466 }
467
468 // add schema to all schemas
469 if (parsedSchema.schema["x-schemaName"]) {
470 allSchemas.add(parsedSchema.schema["x-schemaName"])
471 }
472
473 // collect referenced schemas
474 findReferencedSchemas(parsedSchema.schema)
475 } catch (error) {
476 schemasToDelete.push(schemaYaml)
477 }
478 })
479 )
480
481 // Step 9: Clean up unused schemas
482 const unusedSchemas = Array.from(allSchemas).filter(
483 (schemaName) =>
484 !referencedSchemas.has(schemaName) && !ignoreSchemas.includes(schemaName)
485 )
486
487 const oasSchemasPath = path.join(oasOutputBasePath, "schemas")
488 await Promise.all(
489 [
490 ...schemasToDelete,
491 ...unusedSchemas.map((s) => path.join(oasSchemasPath, `${s}.ts`)),
492 ].map(async (filePath) => {
493 await fs.unlink(filePath).catch(() => {})
494 })
495 )
496
497 console.log("Finished clean up")
498 }