-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathparser.js
More file actions
246 lines (188 loc) · 5.62 KB
/
Copy pathparser.js
File metadata and controls
246 lines (188 loc) · 5.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
const cheerio = require('cheerio')
/*:: import type { Cheerio, CheerioStatic, CheerioElement } from 'cheerio'*/
const { default: fetch } = require('node-fetch')
const debug = require('debug')('tt:parser')
// eslint-disable-next-line no-unused-vars
const { Interface, Method, Field, Store } = require('./store')
/* eslint-disable no-console, no-magic-numbers */
const API_URL = 'https://core.telegram.org/bots/api'
/**
* Find previous special typed element in siblings
*/
function findPrev(type/*: string*/, element/*: Cheerio*/) {
let tries = 5
let prev = element
do {
if (prev.is(type)) {
return prev
}
prev = prev.prev()
}
while (--tries)
return prev
}
/**
* Find next special typed element in siblings
* @param {string} type
* @param {Cheerio} element
*/
function findNext(type, element) {
let tries = 5
let next = element
do {
if (next.is(type)) {
return next
}
next = next.next()
}
while (--tries)
return next
}
/**
* Convert list with `.each()` and `.length` to classic array
*/
function toArray(target/*: Cheerio*/)/*: Promise<Cheerio[]>*/ {
return new Promise((resolve) => {
const arr/*: Cheerio[]*/ = []
target.each((index, element/*: CheerioElement*/) => {
arr.push(cheerio(element))
if (target.length - 1 === index) {
resolve(arr)
}
})
})
}
async function parseFields(table) { // eslint-disable-line no-unused-vars
return undefined
}
/**
* @param {Cheerio} description
* @return {Promise<Array<Cheerio>>}
*/
function parseLinks(description/*: Cheerio*/) {
const links = description.find('a').toArray()
.map((element) => cheerio(element).attr('href'))
.map((linkStr) => (
linkStr.startsWith('http')
? linkStr
: `https://core.telegram.org/bots/api${linkStr}`
))
return [...new Set(links)]
}
async function handleInterface({ name, description, rows }) {
const fields = {}
for (const row of rows) {
const [flName, flType, flDescr] = await toArray(row.find('td'))
let fieldDescription
let optional = false
fieldDescription = flDescr.text().trim()
if (fieldDescription.includes('Optional.')) {
optional = true
fieldDescription = fieldDescription.replace('Optional.', '').trim()
}
const links = parseLinks(flDescr)
const fieldName = flName.text().trim()
let fieldType = flType.text().trim()
if (['Field', 'Parameter'].includes(fieldName)) {
continue // eslint-disable-line no-continue
}
if (fieldType.includes(' or ')) {
fieldType = fieldType.split(' or ')
}
debug(`${name.text().trim()}.${fieldName}: ${Array.isArray(fieldType) ? fieldType.join(' | ') : fieldType} ::: ${fieldDescription}`)
const field = new Field(
fieldName,
fieldType,
{
description: fieldDescription,
links,
optional,
}
)
fields[field.name] = field
}
const typeClass = new Interface(
name.text().trim(),
{ description: description.text().trim(), links: parseLinks(description) },
fields
)
debug(name.text(), ':::', description.text())
return typeClass
}
async function handleMethod({ name, description, rows }) {
const fields = {}
for (const row of rows) {
const [flName, flType, flRequired, flDescr] = await toArray(row.find('td'))
const fieldDescription = flDescr.text().trim()
const optional = flRequired.text().trim() === 'Optional'
const links = parseLinks(flDescr)
const fieldName = flName.text().trim()
let fieldType = flType.text().trim()
// fieldName = fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
if (['Field', 'Parameter'].includes(fieldName)) {
continue // eslint-disable-line no-continue
}
if (fieldType.includes(' or ')) {
fieldType = fieldType.split(' or ')
}
debug(`${name.text().trim()}.${fieldName}: ${Array.isArray(fieldType) ? fieldType.join(' | ') : fieldType} ::: ${fieldDescription}`)
const field = new Field(
fieldName,
fieldType,
{
description: fieldDescription,
links,
optional,
}
)
fields[field.name] = field
}
const trimmedName = name.text().trim()
const startCasedName = trimmedName.charAt(0).toUpperCase() + trimmedName.slice(1)
const typeClass = new Method(
startCasedName,
{ description: description.text().trim(), links: parseLinks(description) },
fields
)
debug(name.text(), ':::', description.text())
return typeClass
}
/**
*
* @param {Store} store
*/
async function requestAndParse(store/*: Store*/) {
const result = await (await fetch(API_URL)).text()
const body = cheerio.load(result)
const tables/*: Cheerio*/ = body('body').find('table')
/** @type {Array<Cheerio>} */
const list = await toArray(tables)
for (const table of list) {
const type = table.find('thead tr:first-child th:first-child').text()
let typeClass
if (!['Field', 'Parameter'].includes(type)) {
continue // eslint-disable-line no-continue
}
const name = findPrev('h4', table)
const description = findNext('p', name)
if (name.text().includes(' ')) {
console.warn('WRONG NAME:', name.text())
continue // eslint-disable-line no-continue
}
const rows = await toArray(table.find('tbody tr'))
if (type === 'Field') {
typeClass = await handleInterface({ name, description, rows })
}
else if (type === 'Parameter') {
typeClass = await handleMethod({ name, description, rows })
}
if (!typeClass) {
continue // eslint-disable-line no-continue
}
store.add(typeClass)
}
return store
}
module.exports = {
requestAndParse,
}