@gitbook/react-openapi 1.1.4 → 1.1.6

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.
@@ -1,5 +1,4 @@
1
1
  import type { OpenAPIV3 } from '@gitbook/openapi-parser';
2
- import { getExampleFromSchema } from '@scalar/oas-utils/spec-getters';
3
2
  type JSONValue = string | number | boolean | null | JSONValue[] | {
4
3
  [key: string]: JSONValue;
5
4
  };
@@ -12,5 +11,35 @@ export declare function generateSchemaExample(schema: OpenAPIV3.SchemaObject, op
12
11
  /**
13
12
  * Generate an example for a media type.
14
13
  */
15
- export declare function generateMediaTypeExample(mediaType: OpenAPIV3.MediaTypeObject, options?: GenerateSchemaExampleOptions): JSONValue | undefined;
14
+ export declare function generateMediaTypeExamples(mediaType: OpenAPIV3.MediaTypeObject, options?: GenerateSchemaExampleOptions): OpenAPIV3.ExampleObject[];
15
+ /**
16
+ * This function takes an OpenAPI schema and generates an example from it
17
+ * Forked from : https://github.com/scalar/scalar/blob/main/packages/oas-utils/src/spec-getters/getExampleFromSchema.ts
18
+ */
19
+ declare const getExampleFromSchema: (schema: Record<string, any>, options?: {
20
+ /**
21
+ * The fallback string for empty string values.
22
+ * @default ''
23
+ */
24
+ emptyString?: string;
25
+ /**
26
+ * Whether to use the XML tag names as keys
27
+ * @default false
28
+ */
29
+ xml?: boolean;
30
+ /**
31
+ * Whether to show read-only/write-only properties. Otherwise all properties are shown.
32
+ * @default undefined
33
+ */
34
+ mode?: "read" | "write";
35
+ /**
36
+ * Dynamic values to add to the example.
37
+ */
38
+ variables?: Record<string, any>;
39
+ /**
40
+ * Whether to omit empty and optional properties.
41
+ * @default false
42
+ */
43
+ omitEmptyAndOptionalProperties?: boolean;
44
+ }, level?: number, parentSchema?: Record<string, any>, name?: string) => any;
16
45
  export {};
@@ -9,44 +9,327 @@ var __assign = (this && this.__assign) || function () {
9
9
  };
10
10
  return __assign.apply(this, arguments);
11
11
  };
12
- import { getExampleFromSchema } from '@scalar/oas-utils/spec-getters';
12
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
13
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
14
+ if (ar || !(i in from)) {
15
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
16
+ ar[i] = from[i];
17
+ }
18
+ }
19
+ return to.concat(ar || Array.prototype.slice.call(from));
20
+ };
21
+ var _a, _b, _c;
22
+ import { checkIsReference } from './utils';
13
23
  /**
14
24
  * Generate a JSON example from a schema
15
25
  */
16
26
  export function generateSchemaExample(schema, options) {
17
- return getExampleFromSchema(schema, __assign({ emptyString: 'text', variables: {
18
- 'date-time': new Date().toISOString(),
19
- date: new Date().toISOString().split('T')[0],
20
- email: 'name@gmail.com',
21
- hostname: 'example.com',
22
- ipv4: '0.0.0.0',
23
- ipv6: '2001:0db8:85a3:0000:0000:8a2e:0370:7334',
24
- uri: 'https://example.com',
25
- uuid: '123e4567-e89b-12d3-a456-426614174000',
26
- binary: 'binary',
27
- byte: 'Ynl0ZXM=',
28
- password: 'password',
29
- } }, options), 3 // Max depth for circular references
27
+ return getExampleFromSchema(schema, __assign({ emptyString: 'text' }, options), 3 // Max depth for circular references
30
28
  );
31
29
  }
32
30
  /**
33
31
  * Generate an example for a media type.
34
32
  */
35
- export function generateMediaTypeExample(mediaType, options) {
33
+ export function generateMediaTypeExamples(mediaType, options) {
36
34
  if (mediaType.example) {
37
- return mediaType.example;
35
+ return [{ summary: 'default', value: mediaType.example }];
38
36
  }
39
37
  if (mediaType.examples) {
40
- var key = Object.keys(mediaType.examples)[0];
41
- if (key) {
42
- var example = mediaType.examples[key];
43
- if (example) {
44
- return example.value;
45
- }
38
+ var examples_1 = mediaType.examples;
39
+ var keys = Object.keys(examples_1);
40
+ if (keys.length > 0) {
41
+ return keys.reduce(function (result, key) {
42
+ var example = examples_1[key];
43
+ if (!example || checkIsReference(example)) {
44
+ return result;
45
+ }
46
+ result.push({
47
+ summary: example.summary || key,
48
+ value: example.value,
49
+ description: example.description,
50
+ externalValue: example.externalValue,
51
+ });
52
+ return result;
53
+ }, []);
46
54
  }
47
55
  }
48
56
  if (mediaType.schema) {
49
- return generateSchemaExample(mediaType.schema, options);
57
+ return [{ summary: 'default', value: generateSchemaExample(mediaType.schema, options) }];
50
58
  }
51
- return undefined;
59
+ return [];
52
60
  }
61
+ /** Hard limit for rendering circular references */
62
+ var MAX_LEVELS_DEEP = 5;
63
+ var genericExampleValues = {
64
+ 'date-time': new Date().toISOString(),
65
+ date: (_a = new Date().toISOString().split('T')[0]) !== null && _a !== void 0 ? _a : '1970-01-01',
66
+ email: 'name@gmail.com',
67
+ hostname: 'example.com',
68
+ ipv4: '0.0.0.0',
69
+ ipv6: '2001:0db8:85a3:0000:0000:8a2e:0370:7334',
70
+ uri: 'https://example.com',
71
+ uuid: '123e4567-e89b-12d3-a456-426614174000',
72
+ binary: 'binary',
73
+ byte: 'Ynl0ZXM=',
74
+ password: 'password',
75
+ 'idn-email': 'jane.doe@example.com',
76
+ 'idn-hostname': 'example.com',
77
+ 'iri-reference': '/entitiy/1',
78
+ // https://tools.ietf.org/html/rfc3987
79
+ iri: 'https://example.com/entity/123',
80
+ 'json-pointer': '/nested/objects',
81
+ regex: '/[a-z]/',
82
+ // https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01
83
+ 'relative-json-pointer': '1/nested/objects',
84
+ // full-time in https://tools.ietf.org/html/rfc3339#section-5.6
85
+ time: (_c = (_b = new Date().toISOString().split('T')[1]) === null || _b === void 0 ? void 0 : _b.split('.')[0]) !== null && _c !== void 0 ? _c : '00:00:00Z',
86
+ // either a URI or relative-reference https://tools.ietf.org/html/rfc3986#section-4.1
87
+ 'uri-reference': '../folder',
88
+ 'uri-template': 'https://example.com/{id}',
89
+ 'object-id': '6592008029c8c3e4dc76256c',
90
+ };
91
+ /**
92
+ * We can use the `format` to generate some random values.
93
+ */
94
+ function guessFromFormat(schema, fallback) {
95
+ var _a;
96
+ if (fallback === void 0) { fallback = ''; }
97
+ return (_a = genericExampleValues[schema.format]) !== null && _a !== void 0 ? _a : fallback;
98
+ }
99
+ /** Map of all the results */
100
+ var resultCache = new WeakMap();
101
+ /** Store result in the cache, and return the result */
102
+ function cache(schema, result) {
103
+ // Avoid unnecessary WeakMap operations for primitive values
104
+ if (typeof result !== 'object' || result === null) {
105
+ return result;
106
+ }
107
+ resultCache.set(schema, result);
108
+ return result;
109
+ }
110
+ /**
111
+ * This function takes an OpenAPI schema and generates an example from it
112
+ * Forked from : https://github.com/scalar/scalar/blob/main/packages/oas-utils/src/spec-getters/getExampleFromSchema.ts
113
+ */
114
+ var getExampleFromSchema = function (schema, options, level, parentSchema, name) {
115
+ var _a, _b, _c, _d;
116
+ var _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
117
+ if (level === void 0) { level = 0; }
118
+ // Check if the result is already cached
119
+ if (resultCache.has(schema)) {
120
+ return resultCache.get(schema);
121
+ }
122
+ // Check whether it’s a circular reference
123
+ if (level === MAX_LEVELS_DEEP + 1) {
124
+ try {
125
+ // Fails if it contains a circular reference
126
+ JSON.stringify(schema);
127
+ }
128
+ catch (_v) {
129
+ return '[Circular Reference]';
130
+ }
131
+ }
132
+ // Sometimes, we just want the structure and no values.
133
+ // But if `emptyString` is set, we do want to see some values.
134
+ var makeUpRandomData = !!(options === null || options === void 0 ? void 0 : options.emptyString);
135
+ // Check if the property is read-only/write-only
136
+ if (((options === null || options === void 0 ? void 0 : options.mode) === 'write' && schema.readOnly) ||
137
+ ((options === null || options === void 0 ? void 0 : options.mode) === 'read' && schema.writeOnly)) {
138
+ return undefined;
139
+ }
140
+ // Use given variables as values
141
+ if (schema['x-variable']) {
142
+ var value = (_e = options === null || options === void 0 ? void 0 : options.variables) === null || _e === void 0 ? void 0 : _e[schema['x-variable']];
143
+ // Return the value if it’s defined
144
+ if (value !== undefined) {
145
+ // Type-casting
146
+ if (schema.type === 'number' || schema.type === 'integer') {
147
+ return Number.parseInt(value, 10);
148
+ }
149
+ return cache(schema, value);
150
+ }
151
+ }
152
+ // Use the first example, if there’s an array
153
+ if (Array.isArray(schema.examples) && schema.examples.length > 0) {
154
+ return cache(schema, schema.examples[0]);
155
+ }
156
+ // Use an example, if there’s one
157
+ if (schema.example !== undefined) {
158
+ return cache(schema, schema.example);
159
+ }
160
+ // enum: [ 'available', 'pending', 'sold' ]
161
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) {
162
+ return cache(schema, schema.enum[0]);
163
+ }
164
+ // Check if the property is required
165
+ var isObjectOrArray = schema.type === 'object' ||
166
+ schema.type === 'array' ||
167
+ !!((_g = (_f = schema.allOf) === null || _f === void 0 ? void 0 : _f.at) === null || _g === void 0 ? void 0 : _g.call(_f, 0)) ||
168
+ !!((_j = (_h = schema.anyOf) === null || _h === void 0 ? void 0 : _h.at) === null || _j === void 0 ? void 0 : _j.call(_h, 0)) ||
169
+ !!((_l = (_k = schema.oneOf) === null || _k === void 0 ? void 0 : _k.at) === null || _l === void 0 ? void 0 : _l.call(_k, 0));
170
+ if (!isObjectOrArray && (options === null || options === void 0 ? void 0 : options.omitEmptyAndOptionalProperties) === true) {
171
+ var isRequired = schema.required === true ||
172
+ (parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.required) === true ||
173
+ ((_m = parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.required) === null || _m === void 0 ? void 0 : _m.includes(name !== null && name !== void 0 ? name : schema.name));
174
+ if (!isRequired) {
175
+ return undefined;
176
+ }
177
+ }
178
+ // Object
179
+ if (schema.type === 'object' || schema.properties !== undefined) {
180
+ var response = {};
181
+ // Regular properties
182
+ if (schema.properties !== undefined) {
183
+ for (var propertyName in schema.properties) {
184
+ if (Object.prototype.hasOwnProperty.call(schema.properties, propertyName)) {
185
+ var property = schema.properties[propertyName];
186
+ var propertyXmlTagName = (options === null || options === void 0 ? void 0 : options.xml) ? (_o = property.xml) === null || _o === void 0 ? void 0 : _o.name : undefined;
187
+ response[propertyXmlTagName !== null && propertyXmlTagName !== void 0 ? propertyXmlTagName : propertyName] = getExampleFromSchema(property, options, level + 1, schema, propertyName);
188
+ if (typeof response[propertyXmlTagName !== null && propertyXmlTagName !== void 0 ? propertyXmlTagName : propertyName] === 'undefined') {
189
+ delete response[propertyXmlTagName !== null && propertyXmlTagName !== void 0 ? propertyXmlTagName : propertyName];
190
+ }
191
+ }
192
+ }
193
+ }
194
+ // Pattern properties (regex)
195
+ if (schema.patternProperties !== undefined) {
196
+ for (var pattern in schema.patternProperties) {
197
+ if (Object.prototype.hasOwnProperty.call(schema.patternProperties, pattern)) {
198
+ var property = schema.patternProperties[pattern];
199
+ // Use the regex pattern as an example key
200
+ var exampleKey = pattern;
201
+ response[exampleKey] = getExampleFromSchema(property, options, level + 1, schema, exampleKey);
202
+ }
203
+ }
204
+ }
205
+ // Additional properties
206
+ if (schema.additionalProperties !== undefined) {
207
+ var anyTypeIsValid =
208
+ // true
209
+ schema.additionalProperties === true ||
210
+ // or an empty object {}
211
+ (typeof schema.additionalProperties === 'object' &&
212
+ !Object.keys(schema.additionalProperties).length);
213
+ if (anyTypeIsValid) {
214
+ response.ANY_ADDITIONAL_PROPERTY = 'anything';
215
+ }
216
+ else if (schema.additionalProperties !== false) {
217
+ response.ANY_ADDITIONAL_PROPERTY = getExampleFromSchema(schema.additionalProperties, options, level + 1);
218
+ }
219
+ }
220
+ if (schema.anyOf !== undefined) {
221
+ Object.assign(response, getExampleFromSchema(schema.anyOf[0], options, level + 1));
222
+ }
223
+ else if (schema.oneOf !== undefined) {
224
+ Object.assign(response, getExampleFromSchema(schema.oneOf[0], options, level + 1));
225
+ }
226
+ else if (schema.allOf !== undefined) {
227
+ Object.assign.apply(Object, __spreadArray([response], schema.allOf
228
+ .map(function (item) {
229
+ return getExampleFromSchema(item, options, level + 1, schema);
230
+ })
231
+ .filter(function (item) { return item !== undefined; }), false));
232
+ }
233
+ return cache(schema, response);
234
+ }
235
+ // Array
236
+ if (schema.type === 'array' || schema.items !== undefined) {
237
+ var itemsXmlTagName_1 = (_q = (_p = schema === null || schema === void 0 ? void 0 : schema.items) === null || _p === void 0 ? void 0 : _p.xml) === null || _q === void 0 ? void 0 : _q.name;
238
+ var wrapItems = !!((options === null || options === void 0 ? void 0 : options.xml) && ((_r = schema.xml) === null || _r === void 0 ? void 0 : _r.wrapped) && itemsXmlTagName_1);
239
+ if (schema.example !== undefined) {
240
+ return cache(schema, wrapItems ? (_a = {}, _a[itemsXmlTagName_1] = schema.example, _a) : schema.example);
241
+ }
242
+ // Check whether the array has a anyOf, oneOf, or allOf rule
243
+ if (schema.items) {
244
+ // First handle allOf separately since it needs special handling
245
+ if (schema.items.allOf) {
246
+ // If the first item is an object type, merge all schemas
247
+ if (schema.items.allOf[0].type === 'object') {
248
+ var mergedExample = getExampleFromSchema({ type: 'object', allOf: schema.items.allOf }, options, level + 1, schema);
249
+ return cache(schema, wrapItems ? [(_b = {}, _b[itemsXmlTagName_1] = mergedExample, _b)] : [mergedExample]);
250
+ }
251
+ // For non-objects (like strings), collect all examples
252
+ var examples = schema.items.allOf
253
+ .map(function (item) {
254
+ return getExampleFromSchema(item, options, level + 1, schema);
255
+ })
256
+ .filter(function (item) { return item !== undefined; });
257
+ return cache(schema, wrapItems
258
+ ? examples.map(function (example) {
259
+ var _a;
260
+ return (_a = {}, _a[itemsXmlTagName_1] = example, _a);
261
+ })
262
+ : examples);
263
+ }
264
+ // Handle other rules (anyOf, oneOf)
265
+ var rules = ['anyOf', 'oneOf'];
266
+ for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) {
267
+ var rule = rules_1[_i];
268
+ if (!schema.items[rule]) {
269
+ continue;
270
+ }
271
+ var schemas = schema.items[rule].slice(0, 1);
272
+ var exampleFromRule = schemas
273
+ .map(function (item) {
274
+ return getExampleFromSchema(item, options, level + 1, schema);
275
+ })
276
+ .filter(function (item) { return item !== undefined; });
277
+ return cache(schema, wrapItems ? [(_c = {}, _c[itemsXmlTagName_1] = exampleFromRule, _c)] : exampleFromRule);
278
+ }
279
+ }
280
+ if ((_s = schema.items) === null || _s === void 0 ? void 0 : _s.type) {
281
+ var exampleFromSchema = getExampleFromSchema(schema.items, options, level + 1);
282
+ return wrapItems ? [(_d = {}, _d[itemsXmlTagName_1] = exampleFromSchema, _d)] : [exampleFromSchema];
283
+ }
284
+ return [];
285
+ }
286
+ var exampleValues = {
287
+ string: makeUpRandomData ? guessFromFormat(schema, options === null || options === void 0 ? void 0 : options.emptyString) : '',
288
+ boolean: true,
289
+ integer: (_t = schema.min) !== null && _t !== void 0 ? _t : 1,
290
+ number: (_u = schema.min) !== null && _u !== void 0 ? _u : 1,
291
+ array: [],
292
+ };
293
+ if (schema.type !== undefined && exampleValues[schema.type] !== undefined) {
294
+ return cache(schema, exampleValues[schema.type]);
295
+ }
296
+ var discriminateSchema = schema.oneOf || schema.anyOf;
297
+ // Check if property has the `oneOf` | `anyOf` key
298
+ if (Array.isArray(discriminateSchema) && discriminateSchema.length > 0) {
299
+ // Get the first item from the `oneOf` | `anyOf` array
300
+ var firstOneOfItem = discriminateSchema[0];
301
+ // Return an example for the first item
302
+ return getExampleFromSchema(firstOneOfItem, options, level + 1);
303
+ }
304
+ // Check if schema has the `allOf` key
305
+ if (Array.isArray(schema.allOf)) {
306
+ var example_1 = null;
307
+ // Loop through all `allOf` schemas
308
+ schema.allOf.forEach(function (allOfItem) {
309
+ // Return an example from the schema
310
+ var newExample = getExampleFromSchema(allOfItem, options, level + 1);
311
+ // Merge or overwrite the example
312
+ example_1 =
313
+ typeof newExample === 'object' && typeof example_1 === 'object'
314
+ ? __assign(__assign({}, (example_1 !== null && example_1 !== void 0 ? example_1 : {})), newExample) : Array.isArray(newExample) && Array.isArray(example_1)
315
+ ? __spreadArray(__spreadArray([], (example_1 !== null && example_1 !== void 0 ? example_1 : {}), true), newExample, true) : newExample;
316
+ });
317
+ return cache(schema, example_1);
318
+ }
319
+ // Check if schema is a union type
320
+ if (Array.isArray(schema.type)) {
321
+ // Return null if the type is nullable
322
+ if (schema.type.includes('null')) {
323
+ return null;
324
+ }
325
+ // Return an example for the first type in the union
326
+ var exampleValue = exampleValues[schema.type[0]];
327
+ if (exampleValue !== undefined) {
328
+ return cache(schema, exampleValue);
329
+ }
330
+ }
331
+ // Warn if the type is unknown …
332
+ // console.warn(`[getExampleFromSchema] Unknown property type "${schema.type}".`)
333
+ // … and just return null for now.
334
+ return null;
335
+ };