Skip to content
This repository was archived by the owner on Aug 28, 2024. It is now read-only.

Commit c106e09

Browse files
authored
chore: render code frames for errors (wip) (#178)
1 parent 2512b07 commit c106e09

File tree

3 files changed

+112
-25
lines changed

3 files changed

+112
-25
lines changed

packages/openapi-parser/package.json

+3
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,13 @@
5050
},
5151
"devDependencies": {
5252
"@apidevtools/swagger-parser": "^10.1.0",
53+
"@babel/code-frame": "^7.24.7",
5354
"@rollup/plugin-json": "^6.1.0",
5455
"@rollup/plugin-terser": "^0.4.4",
5556
"@rollup/plugin-typescript": "^11.1.6",
5657
"glob": "^11.0.0",
58+
"@types/node": "^20.14.0",
59+
"json-to-ast": "^2.1.0",
5760
"just-diff": "^6.0.2",
5861
"rollup": "^4.19.2",
5962
"rollup-plugin-output-size": "^1.4.1",
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import { codeFrameColumns } from '@babel/code-frame'
2+
import { describe, it } from 'vitest'
3+
4+
import { toJson } from '../src'
5+
6+
// const JsonAsty = require('json-asty')
7+
const parse = require('json-to-ast')
8+
9+
const example = {
10+
openapi: '3.1.0',
11+
info: {
12+
title: 'Hello World',
13+
version: '1.0.0',
14+
},
15+
paths: {},
16+
}
17+
18+
describe('code-frame', () => {
19+
it('load object', async () => {
20+
const pointer = '#/info/title'
21+
const json = toJson(example)
22+
23+
// Generate AST from JSON string
24+
const ast = parse(json, {
25+
// with location information
26+
loc: true,
27+
})
28+
29+
// Get node from AST
30+
const segments = pointer.substring(1).split('/').slice(1)
31+
const node = segments.reduce((acc, key) => {
32+
if (acc?.type === 'Object') {
33+
return acc.children.find(
34+
(child) => child.type === 'Property' && child.key.value === key,
35+
)
36+
}
37+
38+
if (acc?.value?.type === 'Object') {
39+
return acc.value.children.find(
40+
(child) => child.type === 'Property' && child.key.value === key,
41+
)
42+
}
43+
}, ast)
44+
45+
const location = {
46+
start: { line: node.loc.start.line, column: node.loc.start.column },
47+
end: { line: node.loc.end.line, column: node.loc.end.column },
48+
}
49+
50+
console.log()
51+
console.log('JSON')
52+
console.log()
53+
console.log(json)
54+
55+
console.log()
56+
57+
console.log('ERROR')
58+
const result = codeFrameColumns(json, location, {
59+
highlightCode: true,
60+
message:
61+
'This is the location of the key "title" in the OpenAPI document.',
62+
})
63+
console.log()
64+
65+
console.log(result)
66+
})
67+
})

pnpm-lock.yaml

+42-25
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)