| 5 | * The one from @scalar/openapi-parser does not support recursion. |
| 6 | */ |
| 7 | export async function traverse<T extends AnyObject | AnyObject[]>( |
| 8 | specification: T, |
| 9 | transform: (specification: AnyObject, path?: string[]) => AnyObject | Promise<AnyObject>, |
| 10 | path: string[] = [], |
| 11 | seen = new WeakSet() |
| 12 | ): Promise<T> { |
| 13 | const result: AnyObject = {}; |
| 14 | |
| 15 | if (typeof specification !== 'object' || specification === null) { |
| 16 | return specification as Promise<T>; |
| 17 | } |
| 18 | |
| 19 | if (seen.has(specification)) { |
| 20 | return specification as Promise<T>; |
| 21 | } |
| 22 | |
| 23 | if (Array.isArray(specification)) { |
| 24 | return Promise.all( |
| 25 | specification.map((item, index) => |
| 26 | traverse(item, transform, [...path, index.toString()], seen) |
| 27 | ) |
| 28 | ) as Promise<T>; |
| 29 | } |
| 30 | |
| 31 | const keys = Object.keys(specification); |
| 32 | const results = await Promise.all( |
| 33 | keys.map(async (key, index) => { |
| 34 | const value = specification[key]; |
| 35 | const processed = await traverse(value, transform, [...path, key], seen); |
| 36 | return { key, value: processed, index }; |
| 37 | }) |
| 38 | ); |
| 39 | |
| 40 | // Promise.all does not guarantee the order of the results |
| 41 | // So we need to sort them to preserve the original order |
| 42 | results.sort((a, b) => a.index - b.index); |
| 43 | for (const { key, value } of results) { |
| 44 | result[key] = value; |
| 45 | } |
| 46 | |
| 47 | return transform(result, path) as Promise<T>; |
| 48 | } |