1 import { OpenAPI } from "types"
2 import OpenAPIParser from "@readme/openapi-parser"
3 import { workerCompatibleFetch } from "docs-utils"
4
5 // @readme/openapi-parser uses Node.js https.get internally, which is not
6 // available in Cloudflare Workers. Override the HTTP resolver to use
7 // the global fetch() API instead.
8 const fetchHttpResolver = {
9 order: 1,
10 canRead: /^https?:\/\//,
11 async read(file: { url: string }) {
12 const res = await workerCompatibleFetch<string>({
13 url: file.url,
14 responseTransformer: async (res) => {
15 if (!res.ok) throw new Error(`Failed to fetch ${file.url}: ${res.status}`)
16 return await res.text()
17 },
18 fallbackAction: async () => {
19 // In local development, we can read the spec directly from the filesystem
20 const { readFileSync, existsSync } = await import("fs")
21
22 if (!existsSync(file.url)) {
23 throw new Error(`Spec file not found: ${file.url}`)
24 }
25 return readFileSync(file.url, "utf-8")
26 },
27 })
28 return res
29 },
30 }
31
32 type Options = {
33 basePath: string
34 paths?: OpenAPI.ParsedPathItemObject[]
35 schemas?: OpenAPI.SchemaObject[]
36 }
37
38 export default async function dereference({
39 basePath,
40 paths,
41 schemas,
42 }: Options): Promise<OpenAPI.Document> {
43 // dereference the references in the paths
44 let document: OpenAPI.Document = {
45 paths: {},
46 // These attributes are only for validation purposes
47 openapi: "3.0.0",
48 info: {
49 title: "Medusa API",
50 version: "1.0.0",
51 },
52 components: {
53 schemas: {},
54 },
55 }
56
57 if (paths) {
58 paths.forEach((path) => {
59 const documentPath = path.operationPath || ""
60 delete path.operationPath
61 document.paths[documentPath] = path
62 })
63 }
64
65 if (schemas) {
66 schemas.forEach((schema) => {
67 if (!schema["x-schemaName"]) {
68 return
69 }
70 document.components!.schemas![schema["x-schemaName"]] = schema
71 })
72 }
73
74 // resolve references in paths
75 document = (await OpenAPIParser.dereference(`${basePath}/`, document, {
76 resolve: {
77 http: fetchHttpResolver,
78 },
79 parse: {
80 text: {
81 // This ensures that all files are parsed as expected
82 // resolving the error with incorrect new lines for
83 // example files having `undefined` extension.
84 canParse: /.*/,
85 },
86 },
87 dereference: {
88 circular: "ignore",
89 },
90 })) as unknown as OpenAPI.Document
91
92 return document
93 }