@gitbook/react-openapi 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/InteractiveSection.d.ts +33 -0
  3. package/dist/InteractiveSection.js +32 -0
  4. package/dist/Markdown.d.ts +5 -0
  5. package/dist/Markdown.js +6 -0
  6. package/dist/OpenAPICodeSample.d.ts +11 -0
  7. package/dist/OpenAPICodeSample.js +76 -0
  8. package/dist/OpenAPIOperation.d.ts +11 -0
  9. package/dist/OpenAPIOperation.js +38 -0
  10. package/dist/OpenAPIRequestBody.d.ts +10 -0
  11. package/dist/OpenAPIRequestBody.js +18 -0
  12. package/dist/OpenAPIResponse.d.ts +10 -0
  13. package/dist/OpenAPIResponse.js +32 -0
  14. package/dist/OpenAPIResponseExample.d.ts +10 -0
  15. package/dist/OpenAPIResponseExample.js +48 -0
  16. package/dist/OpenAPIResponses.d.ts +10 -0
  17. package/dist/OpenAPIResponses.js +18 -0
  18. package/dist/OpenAPISchema.d.ts +45 -0
  19. package/dist/OpenAPISchema.js +232 -0
  20. package/dist/OpenAPISchema.test.d.ts +1 -0
  21. package/dist/OpenAPISchema.test.js +91 -0
  22. package/dist/OpenAPISecurities.d.ts +10 -0
  23. package/dist/OpenAPISecurities.js +42 -0
  24. package/dist/OpenAPIServerURL.d.ts +12 -0
  25. package/dist/OpenAPIServerURL.js +51 -0
  26. package/dist/OpenAPIServerURLVariable.d.ts +9 -0
  27. package/dist/OpenAPIServerURLVariable.js +10 -0
  28. package/dist/OpenAPISpec.d.ts +12 -0
  29. package/dist/OpenAPISpec.js +70 -0
  30. package/dist/ScalarApiButton.d.ts +5 -0
  31. package/dist/ScalarApiButton.js +14 -0
  32. package/dist/code-samples.d.ts +14 -0
  33. package/dist/code-samples.js +50 -0
  34. package/dist/fetchOpenAPIOperation.d.ts +72 -0
  35. package/dist/fetchOpenAPIOperation.js +124 -0
  36. package/dist/fetchOpenAPIOperation.test.d.ts +1 -0
  37. package/dist/fetchOpenAPIOperation.test.js +152 -0
  38. package/dist/generateSchemaExample.d.ts +17 -0
  39. package/dist/generateSchemaExample.js +119 -0
  40. package/dist/index.d.ts +3 -0
  41. package/dist/index.js +2 -0
  42. package/dist/resolveOpenAPIPath.d.ts +7 -0
  43. package/dist/resolveOpenAPIPath.js +112 -0
  44. package/dist/resolveOpenAPIPath.test.d.ts +1 -0
  45. package/dist/resolveOpenAPIPath.test.js +39 -0
  46. package/dist/tsconfig.tsbuildinfo +1 -0
  47. package/dist/types.d.ts +32 -0
  48. package/dist/types.js +1 -0
  49. package/dist/utils.d.ts +2 -0
  50. package/dist/utils.js +6 -0
  51. package/package.json +9 -4
  52. package/src/InteractiveSection.tsx +14 -12
  53. package/src/OpenAPICodeSample.tsx +8 -9
  54. package/src/OpenAPIOperation.tsx +7 -3
  55. package/src/ScalarApiButton.tsx +5 -138
  56. package/src/fetchOpenAPIOperation.ts +1 -1
  57. package/src/types.ts +3 -0
  58. package/.turbo/turbo-build.log +0 -1
  59. package/tsconfig.json +0 -24
  60. package/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1,72 @@
1
+ import { toJSON, fromJSON } from 'flatted';
2
+ import { OpenAPIV3 } from 'openapi-types';
3
+ import { OpenAPIFetcher } from './types';
4
+ export interface OpenAPIOperationData extends OpenAPICustomSpecProperties {
5
+ path: string;
6
+ method: string;
7
+ /** Servers to be used for this operation */
8
+ servers: OpenAPIV3.ServerObject[];
9
+ /** Spec of the operation */
10
+ operation: OpenAPIV3.OperationObject & OpenAPICustomOperationProperties;
11
+ /** Securities that should be used for this operation */
12
+ securities: [string, OpenAPIV3.SecuritySchemeObject][];
13
+ }
14
+ /**
15
+ * Custom properties that can be defined at the entire spec level.
16
+ */
17
+ export interface OpenAPICustomSpecProperties {
18
+ /**
19
+ * If `true`, code samples will not be displayed.
20
+ * This option can be used to hide code samples for the entire spec.
21
+ */
22
+ 'x-codeSamples'?: boolean;
23
+ /**
24
+ * If `true`, the "Try it" button will not be displayed.
25
+ * This option can be used to hide code samples for the entire spec.
26
+ */
27
+ 'x-hideTryItPanel'?: boolean;
28
+ }
29
+ /**
30
+ * Custom properties that can be defined at the operation level.
31
+ * These properties are not part of the OpenAPI spec.
32
+ */
33
+ export interface OpenAPICustomOperationProperties {
34
+ 'x-code-samples'?: OpenAPICustomCodeSample[];
35
+ 'x-codeSamples'?: OpenAPICustomCodeSample[] | false;
36
+ 'x-custom-examples'?: OpenAPICustomCodeSample[];
37
+ /**
38
+ * If `true`, the "Try it" button will not be displayed.
39
+ * https://redocly.com/docs/api-reference-docs/specification-extensions/x-hidetryitpanel/
40
+ */
41
+ 'x-hideTryItPanel'?: boolean;
42
+ }
43
+ /**
44
+ * Custom code samples that can be defined at the operation level.
45
+ * It follows the spec defined by Redocly.
46
+ * https://redocly.com/docs/api-reference-docs/specification-extensions/x-code-samples/
47
+ */
48
+ export interface OpenAPICustomCodeSample {
49
+ lang: string;
50
+ label: string;
51
+ source: string;
52
+ }
53
+ export { toJSON, fromJSON };
54
+ /**
55
+ * Resolve an OpenAPI operation in a file and compile it to a more usable format.
56
+ */
57
+ export declare function fetchOpenAPIOperation(input: {
58
+ url: string;
59
+ path: string;
60
+ method: string;
61
+ }, rawFetcher: OpenAPIFetcher): Promise<OpenAPIOperationData | null>;
62
+ /**
63
+ * Parse a raw string into an OpenAPI document.
64
+ * It will also convert Swagger 2.0 to OpenAPI 3.0.
65
+ * It can throw an `OpenAPIFetchError` if the document is invalid.
66
+ */
67
+ export declare function parseOpenAPIV3(url: string, text: string): Promise<OpenAPIV3.Document>;
68
+ export declare class OpenAPIFetchError extends Error {
69
+ readonly url: string;
70
+ name: string;
71
+ constructor(message: string, url: string);
72
+ }
@@ -0,0 +1,124 @@
1
+ import { toJSON, fromJSON } from 'flatted';
2
+ import YAML from 'yaml';
3
+ import swagger2openapi from 'swagger2openapi';
4
+ import { resolveOpenAPIPath } from './resolveOpenAPIPath';
5
+ export { toJSON, fromJSON };
6
+ /**
7
+ * Resolve an OpenAPI operation in a file and compile it to a more usable format.
8
+ */
9
+ export async function fetchOpenAPIOperation(input, rawFetcher) {
10
+ const fetcher = cacheFetcher(rawFetcher);
11
+ let operation = await resolveOpenAPIPath(input.url, ['paths', input.path, input.method], fetcher);
12
+ if (!operation) {
13
+ return null;
14
+ }
15
+ const specData = await fetcher.fetch(input.url);
16
+ // Resolve common parameters
17
+ const commonParameters = await resolveOpenAPIPath(input.url, ['paths', input.path, 'parameters'], fetcher);
18
+ if (commonParameters) {
19
+ operation = {
20
+ ...operation,
21
+ parameters: [...commonParameters, ...(operation.parameters ?? [])],
22
+ };
23
+ }
24
+ // Resolve servers
25
+ const servers = await resolveOpenAPIPath(input.url, ['servers'], fetcher);
26
+ // Resolve securities
27
+ const securities = [];
28
+ for (const security of operation.security ?? []) {
29
+ const securityKey = Object.keys(security)[0];
30
+ const securityScheme = await resolveOpenAPIPath(input.url, ['components', 'securitySchemes', securityKey], fetcher);
31
+ if (securityScheme) {
32
+ securities.push([securityKey, securityScheme]);
33
+ }
34
+ }
35
+ return {
36
+ servers: servers ?? [],
37
+ operation,
38
+ method: input.method,
39
+ path: input.path,
40
+ securities,
41
+ 'x-codeSamples': typeof specData['x-codeSamples'] === 'boolean' ? specData['x-codeSamples'] : undefined,
42
+ 'x-hideTryItPanel': typeof specData['x-hideTryItPanel'] === 'boolean'
43
+ ? specData['x-hideTryItPanel']
44
+ : undefined,
45
+ };
46
+ }
47
+ function cacheFetcher(fetcher) {
48
+ const cache = new Map();
49
+ return {
50
+ async fetch(url) {
51
+ if (cache.has(url)) {
52
+ return cache.get(url);
53
+ }
54
+ const promise = fetcher.fetch(url);
55
+ cache.set(url, promise);
56
+ return promise;
57
+ },
58
+ parseMarkdown: fetcher.parseMarkdown,
59
+ };
60
+ }
61
+ /**
62
+ * Parse a raw string into an OpenAPI document.
63
+ * It will also convert Swagger 2.0 to OpenAPI 3.0.
64
+ * It can throw an `OpenAPIFetchError` if the document is invalid.
65
+ */
66
+ export async function parseOpenAPIV3(url, text) {
67
+ // Parse the JSON or YAML
68
+ let data;
69
+ // Try with JSON
70
+ try {
71
+ data = JSON.parse(text);
72
+ }
73
+ catch (jsonError) {
74
+ try {
75
+ // Try with YAML
76
+ data = YAML.parse(text);
77
+ }
78
+ catch (yamlError) {
79
+ if (yamlError instanceof Error && yamlError.name.startsWith('YAML')) {
80
+ throw new OpenAPIFetchError('Failed to parse YAML: ' + yamlError.message, url);
81
+ }
82
+ else {
83
+ throw yamlError;
84
+ }
85
+ }
86
+ }
87
+ // Convert Swagger 2.0 to OpenAPI 3.0
88
+ // @ts-ignore
89
+ if (data && data.swagger) {
90
+ try {
91
+ // Convert Swagger 2.0 to OpenAPI 3.0
92
+ // @ts-ignore
93
+ const result = (await swagger2openapi.convertObj(data, {
94
+ resolve: false,
95
+ resolveInternal: false,
96
+ laxDefaults: true,
97
+ laxurls: true,
98
+ lint: false,
99
+ prevalidate: false,
100
+ anchors: true,
101
+ patch: true,
102
+ }));
103
+ data = result.openapi;
104
+ }
105
+ catch (error) {
106
+ if (error.name === 'S2OError') {
107
+ throw new OpenAPIFetchError('Failed to convert Swagger 2.0 to OpenAPI 3.0: ' + error.message, url);
108
+ }
109
+ else {
110
+ throw error;
111
+ }
112
+ }
113
+ }
114
+ // @ts-ignore
115
+ return data;
116
+ }
117
+ export class OpenAPIFetchError extends Error {
118
+ url;
119
+ name = 'OpenAPIFetchError';
120
+ constructor(message, url) {
121
+ super(message);
122
+ this.url = url;
123
+ }
124
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,152 @@
1
+ import { it, expect } from 'bun:test';
2
+ import { fetchOpenAPIOperation, parseOpenAPIV3 } from './fetchOpenAPIOperation';
3
+ const fetcher = {
4
+ fetch: async (url) => {
5
+ const response = await fetch(url);
6
+ return parseOpenAPIV3(url, await response.text());
7
+ },
8
+ };
9
+ it('should resolve refs', async () => {
10
+ const resolved = await fetchOpenAPIOperation({
11
+ url: 'https://petstore3.swagger.io/api/v3/openapi.json',
12
+ method: 'put',
13
+ path: '/pet',
14
+ }, fetcher);
15
+ expect(resolved).toMatchObject({
16
+ servers: [
17
+ {
18
+ url: '/api/v3',
19
+ },
20
+ ],
21
+ operation: {
22
+ tags: ['pet'],
23
+ summary: 'Update an existing pet',
24
+ description: 'Update an existing pet by Id',
25
+ requestBody: {
26
+ content: {
27
+ 'application/json': {
28
+ schema: {
29
+ type: 'object',
30
+ required: ['name', 'photoUrls'],
31
+ },
32
+ },
33
+ },
34
+ },
35
+ },
36
+ });
37
+ });
38
+ it('should support yaml', async () => {
39
+ const resolved = await fetchOpenAPIOperation({
40
+ url: 'https://petstore3.swagger.io/api/v3/openapi.yaml',
41
+ method: 'put',
42
+ path: '/pet',
43
+ }, fetcher);
44
+ expect(resolved).toMatchObject({
45
+ servers: [
46
+ {
47
+ url: '/api/v3',
48
+ },
49
+ ],
50
+ operation: {
51
+ tags: ['pet'],
52
+ summary: 'Update an existing pet',
53
+ description: 'Update an existing pet by Id',
54
+ requestBody: {
55
+ content: {
56
+ 'application/json': {
57
+ schema: {
58
+ type: 'object',
59
+ required: ['name', 'photoUrls'],
60
+ },
61
+ },
62
+ },
63
+ },
64
+ },
65
+ });
66
+ });
67
+ it('should resolve circular refs', async () => {
68
+ const resolved = await fetchOpenAPIOperation({
69
+ url: 'https://api.gitbook.com/openapi.json',
70
+ method: 'post',
71
+ path: '/search/ask',
72
+ }, fetcher);
73
+ expect(resolved).toMatchObject({
74
+ servers: [
75
+ {
76
+ url: '{host}/v1',
77
+ },
78
+ ],
79
+ operation: {
80
+ operationId: 'askQuery',
81
+ },
82
+ });
83
+ });
84
+ it('should resolve to null if the method is not supported', async () => {
85
+ const resolved = await fetchOpenAPIOperation({
86
+ url: 'https://petstore3.swagger.io/api/v3/openapi.json',
87
+ method: 'dontexist',
88
+ path: '/pet',
89
+ }, fetcher);
90
+ expect(resolved).toBe(null);
91
+ });
92
+ it('should parse Swagger 2.0', async () => {
93
+ const resolved = await fetchOpenAPIOperation({
94
+ url: 'https://petstore.swagger.io/v2/swagger.json',
95
+ method: 'put',
96
+ path: '/pet',
97
+ }, fetcher);
98
+ expect(resolved).toMatchObject({
99
+ servers: [
100
+ {
101
+ url: 'https://petstore.swagger.io/v2',
102
+ },
103
+ {
104
+ url: 'http://petstore.swagger.io/v2',
105
+ },
106
+ ],
107
+ operation: {
108
+ tags: ['pet'],
109
+ summary: 'Update an existing pet',
110
+ description: '',
111
+ requestBody: {
112
+ content: {
113
+ 'application/json': {
114
+ schema: {
115
+ type: 'object',
116
+ required: ['name', 'photoUrls'],
117
+ },
118
+ },
119
+ },
120
+ },
121
+ },
122
+ });
123
+ });
124
+ it('should resolve a ref with whitespace', async () => {
125
+ const resolved = await fetchOpenAPIOperation({
126
+ url: ' https://petstore3.swagger.io/api/v3/openapi.json',
127
+ method: 'put',
128
+ path: '/pet',
129
+ }, fetcher);
130
+ expect(resolved).toMatchObject({
131
+ servers: [
132
+ {
133
+ url: '/api/v3',
134
+ },
135
+ ],
136
+ operation: {
137
+ tags: ['pet'],
138
+ summary: 'Update an existing pet',
139
+ description: 'Update an existing pet by Id',
140
+ requestBody: {
141
+ content: {
142
+ 'application/json': {
143
+ schema: {
144
+ type: 'object',
145
+ required: ['name', 'photoUrls'],
146
+ },
147
+ },
148
+ },
149
+ },
150
+ },
151
+ });
152
+ });
@@ -0,0 +1,17 @@
1
+ import { OpenAPIV3 } from 'openapi-types';
2
+ type JSONValue = string | number | boolean | null | JSONValue[] | {
3
+ [key: string]: JSONValue;
4
+ };
5
+ /**
6
+ * Generate a JSON example from a schema
7
+ */
8
+ export declare function generateSchemaExample(schema: OpenAPIV3.SchemaObject, options?: {
9
+ onlyRequired?: boolean;
10
+ }, ancestors?: Set<OpenAPIV3.SchemaObject>): JSONValue | undefined;
11
+ /**
12
+ * Generate an example for a media type.
13
+ */
14
+ export declare function generateMediaTypeExample(mediaType: OpenAPIV3.MediaTypeObject, options?: {
15
+ onlyRequired?: boolean;
16
+ }): JSONValue | undefined;
17
+ export {};
@@ -0,0 +1,119 @@
1
+ import { noReference } from './utils';
2
+ /**
3
+ * Generate a JSON example from a schema
4
+ */
5
+ export function generateSchemaExample(schema, options = {}, ancestors = new Set()) {
6
+ const { onlyRequired = false } = options;
7
+ if (ancestors.has(schema)) {
8
+ return undefined;
9
+ }
10
+ if (typeof schema.example !== 'undefined') {
11
+ return schema.example;
12
+ }
13
+ if (schema.enum && schema.enum.length > 0) {
14
+ return schema.enum[0];
15
+ }
16
+ if (schema.type === 'string') {
17
+ if (schema.default) {
18
+ return schema.default;
19
+ }
20
+ if (schema.format === 'date-time') {
21
+ return new Date().toISOString();
22
+ }
23
+ if (schema.format === 'date') {
24
+ return new Date().toISOString().split('T')[0];
25
+ }
26
+ if (schema.format === 'email') {
27
+ return 'name@gmail.com';
28
+ }
29
+ if (schema.format === 'hostname') {
30
+ return 'example.com';
31
+ }
32
+ if (schema.format === 'ipv4') {
33
+ return '0.0.0.0';
34
+ }
35
+ if (schema.format === 'ipv6') {
36
+ return '2001:0db8:85a3:0000:0000:8a2e:0370:7334';
37
+ }
38
+ if (schema.format === 'uri') {
39
+ return 'https://example.com';
40
+ }
41
+ if (schema.format === 'uuid') {
42
+ return '123e4567-e89b-12d3-a456-426614174000';
43
+ }
44
+ if (schema.format === 'binary') {
45
+ return 'binary';
46
+ }
47
+ if (schema.format === 'byte') {
48
+ return 'Ynl0ZXM=';
49
+ }
50
+ if (schema.format === 'password') {
51
+ return 'password';
52
+ }
53
+ return 'text';
54
+ }
55
+ if (schema.type === 'number') {
56
+ return schema.default || 0;
57
+ }
58
+ if (schema.type === 'boolean') {
59
+ return schema.default || false;
60
+ }
61
+ if (schema.type === 'array') {
62
+ if (schema.items) {
63
+ const exampleValue = generateSchemaExample(noReference(schema.items), options, new Set(ancestors).add(schema));
64
+ if (exampleValue !== undefined) {
65
+ return [exampleValue];
66
+ }
67
+ return [];
68
+ }
69
+ return [];
70
+ }
71
+ if (schema.properties) {
72
+ const example = {};
73
+ const props = onlyRequired ? schema.required ?? [] : Object.keys(schema.properties);
74
+ for (const key of props) {
75
+ const property = noReference(schema.properties[key]);
76
+ if (property && (onlyRequired || !property.deprecated)) {
77
+ const exampleValue = generateSchemaExample(noReference(property), options, new Set(ancestors).add(schema));
78
+ if (exampleValue !== undefined) {
79
+ example[key] = exampleValue;
80
+ }
81
+ }
82
+ }
83
+ return example;
84
+ }
85
+ if (schema.oneOf && schema.oneOf.length > 0) {
86
+ return generateSchemaExample(noReference(schema.oneOf[0]), options, new Set(ancestors).add(schema));
87
+ }
88
+ if (schema.anyOf && schema.anyOf.length > 0) {
89
+ return generateSchemaExample(noReference(schema.anyOf[0]), options, new Set(ancestors).add(schema));
90
+ }
91
+ if (schema.allOf && schema.allOf.length > 0) {
92
+ return schema.allOf.reduce((acc, curr) => {
93
+ const example = generateSchemaExample(noReference(curr), options, new Set(ancestors).add(schema));
94
+ if (typeof example === 'object' && !Array.isArray(example) && example !== null) {
95
+ return { ...acc, ...example };
96
+ }
97
+ return acc;
98
+ }, {});
99
+ }
100
+ return undefined;
101
+ }
102
+ /**
103
+ * Generate an example for a media type.
104
+ */
105
+ export function generateMediaTypeExample(mediaType, options = {}) {
106
+ if (mediaType.example) {
107
+ return mediaType.example;
108
+ }
109
+ if (mediaType.examples) {
110
+ const example = mediaType.examples[Object.keys(mediaType.examples)[0]];
111
+ if (example) {
112
+ return noReference(example).value;
113
+ }
114
+ }
115
+ if (mediaType.schema) {
116
+ return generateSchemaExample(noReference(mediaType.schema), options);
117
+ }
118
+ return undefined;
119
+ }
@@ -0,0 +1,3 @@
1
+ export * from './fetchOpenAPIOperation';
2
+ export * from './OpenAPIOperation';
3
+ export type { OpenAPIFetcher } from './types';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './fetchOpenAPIOperation';
2
+ export * from './OpenAPIOperation';
@@ -0,0 +1,7 @@
1
+ import { OpenAPIFetcher } from './types';
2
+ export declare const SYMBOL_REF_RESOLVED = "__$refResolved";
3
+ /**
4
+ * Resolve a path in a OpenAPI file.
5
+ * It resolves any reference needed to resolve the path, ignoring other references outside the path.
6
+ */
7
+ export declare function resolveOpenAPIPath<T>(url: string, dataPath: string[], fetcher: OpenAPIFetcher): Promise<T | undefined>;
@@ -0,0 +1,112 @@
1
+ const SYMBOL_MARKDOWN_PARSED = '__$markdownParsed';
2
+ export const SYMBOL_REF_RESOLVED = '__$refResolved';
3
+ /**
4
+ * Resolve a path in a OpenAPI file.
5
+ * It resolves any reference needed to resolve the path, ignoring other references outside the path.
6
+ */
7
+ export async function resolveOpenAPIPath(url, dataPath, fetcher) {
8
+ const data = await fetcher.fetch(url);
9
+ let value = data;
10
+ if (!value) {
11
+ return undefined;
12
+ }
13
+ const lastKey = dataPath[dataPath.length - 1];
14
+ dataPath = dataPath.slice(0, -1);
15
+ for (const part of dataPath) {
16
+ // @ts-ignore
17
+ if (isRef(value[part])) {
18
+ await transformAll(url, value, part, fetcher);
19
+ }
20
+ // @ts-ignore
21
+ value = value[part];
22
+ // If any part along the path is undefined, return undefined.
23
+ if (typeof value !== 'object' || value === null) {
24
+ return undefined;
25
+ }
26
+ }
27
+ await transformAll(url, value, lastKey, fetcher);
28
+ // @ts-expect-error
29
+ return value[lastKey];
30
+ }
31
+ /**
32
+ * Recursively process a part of the OpenAPI spec to resolve all references.
33
+ */
34
+ async function transformAll(url, data, key, fetcher) {
35
+ const value = data[key];
36
+ if (typeof value === 'string' &&
37
+ key === 'description' &&
38
+ fetcher.parseMarkdown &&
39
+ !data[SYMBOL_MARKDOWN_PARSED]) {
40
+ // Parse markdown
41
+ data[SYMBOL_MARKDOWN_PARSED] = true;
42
+ data[key] = await fetcher.parseMarkdown(value);
43
+ }
44
+ else if (typeof value === 'string' ||
45
+ typeof value === 'number' ||
46
+ typeof value === 'boolean' ||
47
+ value === null) {
48
+ // Primitives
49
+ }
50
+ else if (typeof value === 'object' && value !== null && SYMBOL_REF_RESOLVED in value) {
51
+ // Ref was already resolved
52
+ }
53
+ else if (isRef(value)) {
54
+ const ref = value.$ref;
55
+ // Delete the ref to avoid infinite loop with circular references
56
+ // @ts-ignore
57
+ delete value.$ref;
58
+ data[key] = await resolveReference(url, ref, fetcher);
59
+ if (data[key]) {
60
+ data[key][SYMBOL_REF_RESOLVED] = extractRefName(ref);
61
+ }
62
+ }
63
+ else if (Array.isArray(value)) {
64
+ // Recursively resolve all references in the array
65
+ await Promise.all(value.map((item, index) => transformAll(url, value, index, fetcher)));
66
+ }
67
+ else if (typeof value === 'object' && value !== null) {
68
+ // Recursively resolve all references in the object
69
+ const keys = Object.keys(value);
70
+ for (const key of keys) {
71
+ await transformAll(url, value, key, fetcher);
72
+ }
73
+ }
74
+ }
75
+ async function resolveReference(origin, ref, fetcher) {
76
+ const parsed = parseReference(origin, ref);
77
+ return resolveOpenAPIPath(parsed.url, parsed.dataPath, fetcher);
78
+ }
79
+ function parseReference(origin, ref) {
80
+ if (!ref) {
81
+ return {
82
+ url: origin,
83
+ dataPath: [],
84
+ };
85
+ }
86
+ if (ref.startsWith('#')) {
87
+ // Local references
88
+ const dataPath = ref.split('/').filter(Boolean).slice(1);
89
+ return {
90
+ url: origin,
91
+ dataPath,
92
+ };
93
+ }
94
+ // Absolute references
95
+ const url = new URL(ref, origin);
96
+ if (url.hash) {
97
+ const hash = url.hash;
98
+ url.hash = '';
99
+ return parseReference(url.toString(), hash);
100
+ }
101
+ return {
102
+ url: url.toString(),
103
+ dataPath: [],
104
+ };
105
+ }
106
+ function extractRefName(ref) {
107
+ const parts = ref.split('/');
108
+ return parts[parts.length - 1];
109
+ }
110
+ function isRef(ref) {
111
+ return typeof ref === 'object' && ref !== null && '$ref' in ref && ref.$ref;
112
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,39 @@
1
+ import { it, expect } from 'bun:test';
2
+ import { resolveOpenAPIPath } from './resolveOpenAPIPath';
3
+ const createFetcherForSchema = (schema) => {
4
+ return {
5
+ fetch: async (url) => {
6
+ return schema;
7
+ },
8
+ };
9
+ };
10
+ it('should resolve a simple path through objects', async () => {
11
+ const resolved = await resolveOpenAPIPath('https://test.com', ['a', 'b', 'c'], createFetcherForSchema({
12
+ a: {
13
+ b: {
14
+ c: 'hello',
15
+ },
16
+ },
17
+ }));
18
+ expect(resolved).toBe('hello');
19
+ });
20
+ it('should return undefined if the last part of the path does not exists', async () => {
21
+ const resolved = await resolveOpenAPIPath('https://test.com', ['a', 'b', 'c'], createFetcherForSchema({
22
+ a: {
23
+ b: {
24
+ d: 'hello',
25
+ },
26
+ },
27
+ }));
28
+ expect(resolved).toBe(undefined);
29
+ });
30
+ it('should return undefined if a middle part of the path does not exists', async () => {
31
+ const resolved = await resolveOpenAPIPath('https://test.com', ['a', 'x', 'c'], createFetcherForSchema({
32
+ a: {
33
+ b: {
34
+ c: 'hello',
35
+ },
36
+ },
37
+ }));
38
+ expect(resolved).toBe(undefined);
39
+ });