fork of hey-api/openapi-ts because I need some additional things
1import type { FileInfo, Plugin } from '../types';
2import { ParserError } from '../util/errors';
3
4export const jsonParser: Plugin = {
5 canHandle: (file: FileInfo) => file.extension === '.json',
6 async handler(file: FileInfo): Promise<object | undefined> {
7 let data = file.data;
8 if (Buffer.isBuffer(data)) {
9 data = data.toString();
10 }
11
12 if (typeof data !== 'string') {
13 // data is already a JavaScript value (object, array, number, null, NaN, etc.)
14 return data as object;
15 }
16
17 if (!data.trim().length) {
18 // this mirrors the YAML behavior
19 return;
20 }
21
22 try {
23 return JSON.parse(data);
24 // eslint-disable-next-line @typescript-eslint/no-unused-vars
25 } catch (error: any) {
26 try {
27 // find the first curly brace
28 const firstCurlyBrace = data.indexOf('{');
29 // remove any characters before the first curly brace
30 data = data.slice(firstCurlyBrace);
31 return JSON.parse(data);
32 } catch (error: any) {
33 throw new ParserError(error.message, file.url);
34 }
35 }
36 },
37 name: 'json',
38};