generate_openapi.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. #!/bin/env python3
  2. import argparse
  3. import esprima
  4. import json
  5. import logging
  6. import os
  7. import re
  8. import sys
  9. import traceback
  10. logger = logging.getLogger(__name__)
  11. err_context = 3
  12. def get_req_body_elems(obj, elems):
  13. if obj.type in ['FunctionExpression', 'ArrowFunctionExpression']:
  14. get_req_body_elems(obj.body, elems)
  15. elif obj.type == 'BlockStatement':
  16. for s in obj.body:
  17. get_req_body_elems(s, elems)
  18. elif obj.type == 'TryStatement':
  19. get_req_body_elems(obj.block, elems)
  20. elif obj.type == 'ExpressionStatement':
  21. get_req_body_elems(obj.expression, elems)
  22. elif obj.type == 'MemberExpression':
  23. left = get_req_body_elems(obj.object, elems)
  24. right = obj.property.name
  25. if left == 'req.body' and right not in elems:
  26. elems.append(right)
  27. return '{}.{}'.format(left, right)
  28. elif obj.type == 'VariableDeclaration':
  29. for s in obj.declarations:
  30. get_req_body_elems(s, elems)
  31. elif obj.type == 'VariableDeclarator':
  32. if obj.id.type == 'ObjectPattern':
  33. # get_req_body_elems() can't be called directly here:
  34. # const {isAdmin, isNoComments, isCommentOnly} = req.body;
  35. right = get_req_body_elems(obj.init, elems)
  36. if right == 'req.body':
  37. for p in obj.id.properties:
  38. name = p.key.name
  39. if name not in elems:
  40. elems.append(name)
  41. else:
  42. get_req_body_elems(obj.init, elems)
  43. elif obj.type == 'Property':
  44. get_req_body_elems(obj.value, elems)
  45. elif obj.type == 'ObjectExpression':
  46. for s in obj.properties:
  47. get_req_body_elems(s, elems)
  48. elif obj.type == 'CallExpression':
  49. for s in obj.arguments:
  50. get_req_body_elems(s, elems)
  51. elif obj.type == 'ArrayExpression':
  52. for s in obj.elements:
  53. get_req_body_elems(s, elems)
  54. elif obj.type == 'IfStatement':
  55. get_req_body_elems(obj.test, elems)
  56. if obj.consequent is not None:
  57. get_req_body_elems(obj.consequent, elems)
  58. if obj.alternate is not None:
  59. get_req_body_elems(obj.alternate, elems)
  60. elif obj.type in ('LogicalExpression', 'BinaryExpression', 'AssignmentExpression'):
  61. get_req_body_elems(obj.left, elems)
  62. get_req_body_elems(obj.right, elems)
  63. elif obj.type in ('ReturnStatement', 'UnaryExpression'):
  64. get_req_body_elems(obj.argument, elems)
  65. elif obj.type == 'Literal':
  66. pass
  67. elif obj.type == 'Identifier':
  68. return obj.name
  69. elif obj.type == 'FunctionDeclaration':
  70. pass
  71. else:
  72. print(obj)
  73. return ''
  74. def cleanup_jsdocs(jsdoc):
  75. # remove leading spaces before the first '*'
  76. doc = [s.lstrip() for s in jsdoc.value.split('\n')]
  77. # remove leading stars
  78. doc = [s.lstrip('*') for s in doc]
  79. # remove leading empty lines
  80. while len(doc) and not doc[0].strip():
  81. doc.pop(0)
  82. # remove terminating empty lines
  83. while len(doc) and not doc[-1].strip():
  84. doc.pop(-1)
  85. return doc
  86. class JS2jsonDecoder(json.JSONDecoder):
  87. def decode(self, s):
  88. result = super().decode(s) # result = super(Decoder, self).decode(s) for Python 2.x
  89. return self._decode(result)
  90. def _decode(self, o):
  91. if isinstance(o, str) or isinstance(o, unicode):
  92. try:
  93. return int(o)
  94. except ValueError:
  95. return o
  96. elif isinstance(o, dict):
  97. return {k: self._decode(v) for k, v in o.items()}
  98. elif isinstance(o, list):
  99. return [self._decode(v) for v in o]
  100. else:
  101. return o
  102. def load_return_type_jsdoc_json(data):
  103. regex_replace = [(r'\n', r' '), # replace new lines by spaces
  104. (r'([\{\s,])(\w+)(:)', r'\1"\2"\3'), # insert double quotes in keys
  105. (r'(:)\s*([^:\},\]]+)\s*([\},\]])', r'\1"\2"\3'), # insert double quotes in values
  106. (r'(\[)\s*([^{].+)\s*(\])', r'\1"\2"\3'), # insert double quotes in array items
  107. (r'^\s*([^\[{].+)\s*', r'"\1"')] # insert double quotes in single item
  108. for r, s in regex_replace:
  109. data = re.sub(r, s, data)
  110. return json.loads(data)
  111. class EntryPoint(object):
  112. def __init__(self, schema, statements):
  113. self.schema = schema
  114. self.method, self._path, self.body = statements
  115. self._jsdoc = None
  116. self._doc = {}
  117. self._raw_doc = None
  118. self.path = self.compute_path()
  119. self.method_name = self.method.value.lower()
  120. self.body_params = []
  121. if self.method_name in ('post', 'put'):
  122. get_req_body_elems(self.body, self.body_params)
  123. # replace the :parameter in path by {parameter}
  124. self.url = re.sub(r':([^/]*)Id', r'{\1}', self.path)
  125. self.url = re.sub(r':([^/]*)', r'{\1}', self.url)
  126. # reduce the api name
  127. # get_boards_board_cards() should be get_board_cards()
  128. tokens = self.url.split('/')
  129. reduced_function_name = []
  130. for i, token in enumerate(tokens):
  131. if token in ('api'):
  132. continue
  133. if (i < len(tokens) - 1 and # not the last item
  134. tokens[i + 1].startswith('{')): # and the next token is a parameter
  135. continue
  136. reduced_function_name.append(token.strip('{}'))
  137. self.reduced_function_name = '_'.join(reduced_function_name)
  138. # mark the schema as used
  139. schema.used = True
  140. def compute_path(self):
  141. return self._path.value.rstrip('/')
  142. def log(self, message, level):
  143. if self._raw_doc is None:
  144. logger.log(level, 'in {},'.format(self.schema.name))
  145. logger.log(level, message)
  146. return
  147. logger.log(level, 'in {}, lines {}-{}'.format(self.schema.name,
  148. self._raw_doc.loc.start.line,
  149. self._raw_doc.loc.end.line))
  150. logger.log(level, self._raw_doc.value)
  151. logger.log(level, message)
  152. def error(self, message):
  153. return self.log(message, logging.ERROR)
  154. def warn(self, message):
  155. return self.log(message, logging.WARNING)
  156. def info(self, message):
  157. return self.log(message, logging.INFO)
  158. @property
  159. def doc(self):
  160. return self._doc
  161. @doc.setter
  162. def doc(self, doc):
  163. '''Parse the JSDoc attached to an entry point.
  164. `jsdoc` will not get these right as they are not attached to a method.
  165. So instead, we do our custom parsing here (yes, subject to errors).
  166. The expected format is the following (empty lines between entries
  167. are ignored):
  168. /**
  169. * @operation name_of_entry_point
  170. * @tag: a_tag_to_add
  171. * @tag: an_other_tag_to_add
  172. * @summary A nice summary, better in one line.
  173. *
  174. * @description This is a quite long description.
  175. * We can use *mardown* as the final rendering is done
  176. * by slate.
  177. *
  178. * indentation doesn't matter.
  179. *
  180. * @param param_0 description of param 0
  181. * @param {string} param_1 we can also put the type of the parameter
  182. * before its name, like in JSDoc
  183. * @param {boolean} [param_2] we can also tell if the parameter is
  184. * optional by adding square brackets around its name
  185. *
  186. * @return Documents a return value
  187. */
  188. Notes:
  189. - name_of_entry_point will be referenced in the ToC of the generated
  190. document. This is also the operationId used in the resulting openapi
  191. file. It needs to be uniq in the namesapce (the current schema.js
  192. file)
  193. - tags are appended to the current Schema attached to the file
  194. '''
  195. self._raw_doc = doc
  196. self._jsdoc = cleanup_jsdocs(doc)
  197. def store_tag(tag, data):
  198. # check that there is something to store first
  199. if not data.strip():
  200. return
  201. # remove terminating whitespaces and empty lines
  202. data = data.rstrip()
  203. # parameters are handled specially
  204. if tag == 'param':
  205. if 'params' not in self._doc:
  206. self._doc['params'] = {}
  207. params = self._doc['params']
  208. param_type = None
  209. try:
  210. name, desc = data.split(maxsplit=1)
  211. except ValueError:
  212. desc = ''
  213. if name.startswith('{'):
  214. param_type = name.strip('{}')
  215. if param_type == 'Object':
  216. # hope for the best
  217. param_type = 'object'
  218. elif param_type not in ['string', 'number', 'boolean', 'integer', 'array', 'file']:
  219. self.warn('unknown type {}\n allowed values: string, number, boolean, integer, array, file'.format(param_type))
  220. try:
  221. name, desc = desc.split(maxsplit=1)
  222. except ValueError:
  223. desc = ''
  224. optional = name.startswith('[') and name.endswith(']')
  225. if optional:
  226. name = name[1:-1]
  227. # we should not have 2 identical parameter names
  228. if tag in params:
  229. self.warn('overwriting parameter {}'.format(name))
  230. params[name] = (param_type, optional, desc)
  231. if name.endswith('Id'):
  232. # we strip out the 'Id' from the form parameters, we need
  233. # to keep the actual description around
  234. name = name[:-2]
  235. if name not in params:
  236. params[name] = (param_type, optional, desc)
  237. return
  238. # 'tag' can be set several times
  239. if tag == 'tag':
  240. if tag not in self._doc:
  241. self._doc[tag] = []
  242. self._doc[tag].append(data)
  243. return
  244. # 'return' tag is json
  245. if tag == 'return_type':
  246. try:
  247. data = load_return_type_jsdoc_json(data)
  248. except json.decoder.JSONDecodeError:
  249. pass
  250. # we should not have 2 identical tags but @param or @tag
  251. if tag in self._doc:
  252. self.warn('overwriting tag {}'.format(tag))
  253. self._doc[tag] = data
  254. # reset the current doc fields
  255. self._doc = {}
  256. # first item is supposed to be the description
  257. current_tag = 'description'
  258. current_data = ''
  259. for line in self._jsdoc:
  260. if line.lstrip().startswith('@'):
  261. tag, data = line.lstrip().split(maxsplit=1)
  262. if tag in ['@operation', '@summary', '@description', '@param', '@return_type', '@tag']:
  263. # store the current data
  264. store_tag(current_tag, current_data)
  265. current_tag = tag.lstrip('@')
  266. current_data = ''
  267. line = data
  268. else:
  269. self.info('Unknown tag {}, ignoring'.format(tag))
  270. current_data += line + '\n'
  271. store_tag(current_tag, current_data)
  272. @property
  273. def summary(self):
  274. if 'summary' in self._doc:
  275. # new lines are not allowed
  276. return self._doc['summary'].replace('\n', ' ')
  277. return None
  278. def doc_param(self, name):
  279. if 'params' in self._doc and name in self._doc['params']:
  280. return self._doc['params'][name]
  281. return None, None, None
  282. def print_openapi_param(self, name, indent):
  283. ptype, poptional, pdesc = self.doc_param(name)
  284. if pdesc is not None:
  285. print('{}description: |'.format(' ' * indent))
  286. print('{}{}'.format(' ' * (indent + 2), pdesc))
  287. else:
  288. print('{}description: the {} value'.format(' ' * indent, name))
  289. if ptype is not None:
  290. print('{}type: {}'.format(' ' * indent, ptype))
  291. else:
  292. print('{}type: string'.format(' ' * indent))
  293. if poptional:
  294. print('{}required: false'.format(' ' * indent))
  295. else:
  296. print('{}required: true'.format(' ' * indent))
  297. @property
  298. def operationId(self):
  299. if 'operation' in self._doc:
  300. return self._doc['operation']
  301. return '{}_{}'.format(self.method_name, self.reduced_function_name)
  302. @property
  303. def description(self):
  304. if 'description' in self._doc:
  305. return self._doc['description']
  306. return None
  307. @property
  308. def returns(self):
  309. if 'return_type' in self._doc:
  310. return self._doc['return_type']
  311. return None
  312. @property
  313. def tags(self):
  314. tags = []
  315. if self.schema.fields is not None:
  316. tags.append(self.schema.name)
  317. if 'tag' in self._doc:
  318. tags.extend(self._doc['tag'])
  319. return tags
  320. def print_openapi_return(self, obj, indent):
  321. if isinstance(obj, dict):
  322. print('{}type: object'.format(' ' * indent))
  323. print('{}properties:'.format(' ' * indent))
  324. for k, v in obj.items():
  325. print('{}{}:'.format(' ' * (indent + 2), k))
  326. self.print_openapi_return(v, indent + 4)
  327. elif isinstance(obj, list):
  328. if len(obj) > 1:
  329. self.error('Error while parsing @return tag, an array should have only one type')
  330. print('{}type: array'.format(' ' * indent))
  331. print('{}items:'.format(' ' * indent))
  332. self.print_openapi_return(obj[0], indent + 2)
  333. elif isinstance(obj, str) or isinstance(obj, unicode):
  334. rtype = 'type: ' + obj
  335. if obj == self.schema.name:
  336. rtype = '$ref: "#/definitions/{}"'.format(obj)
  337. print('{}{}'.format(' ' * indent, rtype))
  338. def print_openapi(self):
  339. parameters = [token[1:-2] if token.endswith('Id') else token[1:]
  340. for token in self.path.split('/')
  341. if token.startswith(':')]
  342. print(' {}:'.format(self.method_name))
  343. print(' operationId: {}'.format(self.operationId))
  344. if self.summary is not None:
  345. print(' summary: {}'.format(self.summary))
  346. if self.description is not None:
  347. print(' description: |')
  348. for line in self.description.split('\n'):
  349. if line.strip():
  350. print(' {}'.format(line))
  351. else:
  352. print('')
  353. if len(self.tags) > 0:
  354. print(' tags:')
  355. for tag in self.tags:
  356. print(' - {}'.format(tag))
  357. # export the parameters
  358. if self.method_name in ('post', 'put'):
  359. print(''' consumes:
  360. - multipart/form-data
  361. - application/json''')
  362. if len(parameters) > 0 or self.method_name in ('post', 'put'):
  363. print(' parameters:')
  364. if self.method_name in ('post', 'put'):
  365. for f in self.body_params:
  366. print(''' - name: {}
  367. in: formData'''.format(f))
  368. self.print_openapi_param(f, 10)
  369. for p in parameters:
  370. if p in self.body_params:
  371. self.error(' '.join((p, self.path, self.method_name)))
  372. print(''' - name: {}
  373. in: path'''.format(p))
  374. self.print_openapi_param(p, 10)
  375. print(''' produces:
  376. - application/json
  377. security:
  378. - UserSecurity: []
  379. responses:
  380. '200':
  381. description: |-
  382. 200 response''')
  383. if self.returns is not None:
  384. print(' schema:')
  385. self.print_openapi_return(self.returns, 12)
  386. class SchemaProperty(object):
  387. def __init__(self, statement, schema, context):
  388. self.schema = schema
  389. self.statement = statement
  390. self.name = statement.key.name or statement.key.value
  391. self.type = 'object'
  392. self.blackbox = False
  393. self.required = True
  394. imports = {}
  395. for p in statement.value.properties:
  396. try:
  397. if p.key.name == 'type':
  398. if p.value.type == 'Identifier':
  399. self.type = p.value.name.lower()
  400. elif p.value.type == 'ArrayExpression':
  401. self.type = 'array'
  402. self.elements = [e.name.lower() for e in p.value.elements]
  403. elif p.key.name == 'allowedValues':
  404. self.type = 'enum'
  405. self.enum = []
  406. def parse_enum(value, enum):
  407. if value.type == 'ArrayExpression':
  408. for e in value.elements:
  409. parse_enum(e, enum)
  410. elif value.type == 'Literal':
  411. enum.append(value.value.lower())
  412. return
  413. elif value.type == 'Identifier':
  414. # tree wide lookout for the identifier
  415. def find_variable(elem, match):
  416. if isinstance(elem, list):
  417. for value in elem:
  418. ret = find_variable(value, match)
  419. if ret is not None:
  420. return ret
  421. try:
  422. items = elem.items()
  423. except AttributeError:
  424. return None
  425. except TypeError:
  426. return None
  427. if (elem.type == 'VariableDeclarator' and
  428. elem.id.name == match):
  429. return elem
  430. elif (elem.type == 'ImportSpecifier' and
  431. elem.local.name == match):
  432. # we have to treat that case in the caller, because we lack
  433. # information of the source of the import at that point
  434. return elem
  435. elif (elem.type == 'ExportNamedDeclaration' and
  436. elem.declaration.type == 'VariableDeclaration'):
  437. ret = find_variable(elem.declaration.declarations, match)
  438. if ret is not None:
  439. return ret
  440. for type, value in items:
  441. ret = find_variable(value, match)
  442. if ret is not None:
  443. if ret.type == 'ImportSpecifier':
  444. # first open and read the import source, if
  445. # we haven't already done so
  446. path = elem.source.value
  447. if elem.source.value.startswith('/'):
  448. script_dir = os.path.dirname(os.path.realpath(__file__))
  449. path = os.path.abspath(os.path.join('{}/..'.format(script_dir), elem.source.value.lstrip('/')))
  450. else:
  451. path = os.path.abspath(os.path.join(os.path.dirname(context.path), elem.source.value))
  452. path += '.js'
  453. if path not in imports:
  454. imported_context = parse_file(path)
  455. imports[path] = imported_context
  456. imported_context = imports[path]
  457. # and then re-run the find in the imported file
  458. return find_variable(imported_context.program.body, match)
  459. return ret
  460. return None
  461. elem = find_variable(context.program.body, value.name)
  462. if elem is None:
  463. raise TypeError('can not find "{}"'.format(value.name))
  464. return parse_enum(elem.init, enum)
  465. parse_enum(p.value, self.enum)
  466. elif p.key.name == 'blackbox':
  467. self.blackbox = True
  468. elif p.key.name == 'optional' and p.value.value:
  469. self.required = False
  470. except Exception:
  471. input = ''
  472. for line in range(p.loc.start.line - err_context, p.loc.end.line + 1 + err_context):
  473. if line < p.loc.start.line or line > p.loc.end.line:
  474. input += '. '
  475. else:
  476. input += '>>'
  477. input += context.text_at(line, line)
  478. input = ''.join(input)
  479. logger.error('{}:{}-{} can not parse {}:\n{}'.format(context.path,
  480. p.loc.start.line,
  481. p.loc.end.line,
  482. p.type,
  483. input))
  484. logger.error('esprima tree:\n{}'.format(p))
  485. logger.error(traceback.format_exc())
  486. sys.exit(1)
  487. self._doc = None
  488. self._raw_doc = None
  489. @property
  490. def doc(self):
  491. return self._doc
  492. @doc.setter
  493. def doc(self, jsdoc):
  494. self._raw_doc = jsdoc
  495. self._doc = cleanup_jsdocs(jsdoc)
  496. def process_jsdocs(self, jsdocs):
  497. start = self.statement.key.loc.start.line
  498. for index, doc in enumerate(jsdocs):
  499. if start + 1 == doc.loc.start.line:
  500. self.doc = doc
  501. jsdocs.pop(index)
  502. return
  503. def __repr__(self):
  504. return 'SchemaProperty({}{}, {})'.format(self.name,
  505. '*' if self.required else '',
  506. self.doc)
  507. def print_openapi(self, indent, current_schema, required_properties):
  508. schema_name = self.schema.name
  509. name = self.name
  510. # deal with subschemas
  511. if '.' in name:
  512. if name.endswith('$'):
  513. # reference in reference
  514. subschema = ''.join([n.capitalize() for n in self.name.split('.')[:-1]])
  515. subschema = self.schema.name + subschema
  516. if current_schema != subschema:
  517. if required_properties is not None and required_properties:
  518. print(' required:')
  519. for f in required_properties:
  520. print(' - {}'.format(f))
  521. required_properties.clear()
  522. print(''' {}:
  523. type: object'''.format(subschema))
  524. return current_schema
  525. subschema = name.split('.')[0]
  526. schema_name = self.schema.name + subschema.capitalize()
  527. name = name.split('.')[-1]
  528. if current_schema != schema_name:
  529. if required_properties is not None and required_properties:
  530. print(' required:')
  531. for f in required_properties:
  532. print(' - {}'.format(f))
  533. required_properties.clear()
  534. print(''' {}:
  535. type: object
  536. properties:'''.format(schema_name))
  537. if required_properties is not None and self.required:
  538. required_properties.append(name)
  539. print('{}{}:'.format(' ' * indent, name))
  540. if self.doc is not None:
  541. print('{} description: |'.format(' ' * indent))
  542. for line in self.doc:
  543. if line.strip():
  544. print('{} {}'.format(' ' * indent, line))
  545. else:
  546. print('')
  547. ptype = self.type
  548. if ptype in ('enum', 'date'):
  549. ptype = 'string'
  550. if ptype != 'object':
  551. print('{} type: {}'.format(' ' * indent, ptype))
  552. if self.type == 'array':
  553. print('{} items:'.format(' ' * indent))
  554. for elem in self.elements:
  555. if elem == 'object':
  556. print('{} $ref: "#/definitions/{}"'.format(' ' * indent, schema_name + name.capitalize()))
  557. else:
  558. print('{} type: {}'.format(' ' * indent, elem))
  559. if not self.required:
  560. print('{} x-nullable: true'.format(' ' * indent))
  561. elif self.type == 'object':
  562. if self.blackbox:
  563. print('{} type: object'.format(' ' * indent))
  564. else:
  565. print('{} $ref: "#/definitions/{}"'.format(' ' * indent, schema_name + name.capitalize()))
  566. elif self.type == 'enum':
  567. print('{} enum:'.format(' ' * indent))
  568. for enum in self.enum:
  569. print('{} - {}'.format(' ' * indent, enum))
  570. if '.' not in self.name and not self.required:
  571. print('{} x-nullable: true'.format(' ' * indent))
  572. return schema_name
  573. class Schemas(object):
  574. def __init__(self, context, data=None, jsdocs=None, name=None):
  575. self.name = name
  576. self._data = data
  577. self.fields = None
  578. self.used = False
  579. if data is not None:
  580. if self.name is None:
  581. self.name = data.expression.callee.object.name
  582. content = data.expression.arguments[0].arguments[0]
  583. self.fields = [SchemaProperty(p, self, context) for p in content.properties]
  584. self._doc = None
  585. self._raw_doc = None
  586. if jsdocs is not None:
  587. self.process_jsdocs(jsdocs)
  588. @property
  589. def doc(self):
  590. if self._doc is None:
  591. return None
  592. return ' '.join(self._doc)
  593. @doc.setter
  594. def doc(self, jsdoc):
  595. self._raw_doc = jsdoc
  596. self._doc = cleanup_jsdocs(jsdoc)
  597. def process_jsdocs(self, jsdocs):
  598. start = self._data.loc.start.line
  599. end = self._data.loc.end.line
  600. for doc in jsdocs:
  601. if doc.loc.end.line + 1 == start:
  602. self.doc = doc
  603. docs = [doc
  604. for doc in jsdocs
  605. if doc.loc.start.line >= start and doc.loc.end.line <= end]
  606. for field in self.fields:
  607. field.process_jsdocs(docs)
  608. def print_openapi(self):
  609. # empty schemas are skipped
  610. if self.fields is None:
  611. return
  612. print(' {}:'.format(self.name))
  613. print(' type: object')
  614. if self.doc is not None:
  615. print(' description: {}'.format(self.doc))
  616. print(' properties:')
  617. # first print out the object itself
  618. properties = [field for field in self.fields if '.' not in field.name]
  619. for prop in properties:
  620. prop.print_openapi(6, None, None)
  621. required_properties = [f.name for f in properties if f.required]
  622. if required_properties:
  623. print(' required:')
  624. for f in required_properties:
  625. print(' - {}'.format(f))
  626. # then print the references
  627. current = None
  628. required_properties = []
  629. properties = [f for f in self.fields if '.' in f.name and not f.name.endswith('$')]
  630. for prop in properties:
  631. current = prop.print_openapi(6, current, required_properties)
  632. if required_properties:
  633. print(' required:')
  634. for f in required_properties:
  635. print(' - {}'.format(f))
  636. required_properties = []
  637. # then print the references in the references
  638. for prop in [f for f in self.fields if '.' in f.name and f.name.endswith('$')]:
  639. current = prop.print_openapi(6, current, required_properties)
  640. if required_properties:
  641. print(' required:')
  642. for f in required_properties:
  643. print(' - {}'.format(f))
  644. class Context(object):
  645. def __init__(self, path):
  646. self.path = path
  647. with open(path) as f:
  648. self._txt = f.readlines()
  649. data = ''.join(self._txt)
  650. self.program = esprima.parseModule(data,
  651. options={
  652. 'comment': True,
  653. 'loc': True
  654. })
  655. def txt_for(self, statement):
  656. return self.text_at(statement.loc.start.line, statement.loc.end.line)
  657. def text_at(self, begin, end):
  658. return ''.join(self._txt[begin - 1:end])
  659. def parse_file(path):
  660. try:
  661. # if the file failed, it's likely it doesn't contain a schema
  662. context = Context(path)
  663. except:
  664. return
  665. return context
  666. def parse_schemas(schemas_dir):
  667. schemas = {}
  668. entry_points = []
  669. for root, dirs, files in os.walk(schemas_dir):
  670. files.sort()
  671. for filename in files:
  672. path = os.path.join(root, filename)
  673. context = parse_file(path)
  674. program = context.program
  675. current_schema = None
  676. jsdocs = [c for c in program.comments
  677. if c.type == 'Block' and c.value.startswith('*\n')]
  678. try:
  679. for statement in program.body:
  680. # find the '<ITEM>.attachSchema(new SimpleSchema(<data>)'
  681. # those are the schemas
  682. if (statement.type == 'ExpressionStatement' and
  683. statement.expression.callee is not None and
  684. statement.expression.callee.property is not None and
  685. statement.expression.callee.property.name == 'attachSchema' and
  686. statement.expression.arguments[0].type == 'NewExpression' and
  687. statement.expression.arguments[0].callee.name == 'SimpleSchema'):
  688. schema = Schemas(context, statement, jsdocs)
  689. current_schema = schema.name
  690. schemas[current_schema] = schema
  691. # find all the 'if (Meteor.isServer) { JsonRoutes.add('
  692. # those are the entry points of the API
  693. elif (statement.type == 'IfStatement' and
  694. statement.test.type == 'MemberExpression' and
  695. statement.test.object.name == 'Meteor' and
  696. statement.test.property.name == 'isServer'):
  697. data = [s.expression.arguments
  698. for s in statement.consequent.body
  699. if (s.type == 'ExpressionStatement' and
  700. s.expression.type == 'CallExpression' and
  701. s.expression.callee.object.name == 'JsonRoutes')]
  702. # we found at least one entry point, keep them
  703. if len(data) > 0:
  704. if current_schema is None:
  705. current_schema = filename
  706. schemas[current_schema] = Schemas(context, name=current_schema)
  707. schema_entry_points = [EntryPoint(schemas[current_schema], d)
  708. for d in data]
  709. entry_points.extend(schema_entry_points)
  710. end_of_previous_operation = -1
  711. # try to match JSDoc to the operations
  712. for entry_point in schema_entry_points:
  713. operation = entry_point.method # POST/GET/PUT/DELETE
  714. # find all jsdocs that end before the current operation,
  715. # the last item in the list is the one we need
  716. jsdoc = [j for j in jsdocs
  717. if j.loc.end.line + 1 <= operation.loc.start.line and
  718. j.loc.start.line > end_of_previous_operation]
  719. if bool(jsdoc):
  720. entry_point.doc = jsdoc[-1]
  721. end_of_previous_operation = operation.loc.end.line
  722. except TypeError:
  723. logger.warning(context.txt_for(statement))
  724. logger.error('{}:{}-{} can not parse {}'.format(path,
  725. statement.loc.start.line,
  726. statement.loc.end.line,
  727. statement.type))
  728. raise
  729. return schemas, entry_points
  730. def generate_openapi(schemas, entry_points, version):
  731. print('''swagger: '2.0'
  732. info:
  733. title: Wekan REST API
  734. version: {0}
  735. description: |
  736. The REST API allows you to control and extend Wekan with ease.
  737. If you are an end-user and not a dev or a tester, [create an issue](https://github.com/wekan/wekan/issues/new) to request new APIs.
  738. > All API calls in the documentation are made using `curl`. However, you are free to use Java / Python / PHP / Golang / Ruby / Swift / Objective-C / Rust / Scala / C# or any other programming languages.
  739. # Production Security Concerns
  740. When calling a production Wekan server, ensure it is running via HTTPS and has a valid SSL Certificate. The login method requires you to post your username and password in plaintext, which is why we highly suggest only calling the REST login api over HTTPS. Also, few things to note:
  741. * Only call via HTTPS
  742. * Implement a timed authorization token expiration strategy
  743. * Ensure the calling user only has permissions for what they are calling and no more
  744. schemes:
  745. - http
  746. securityDefinitions:
  747. UserSecurity:
  748. type: apiKey
  749. in: header
  750. name: Authorization
  751. paths:
  752. /users/login:
  753. post:
  754. operationId: login
  755. summary: Login with REST API
  756. consumes:
  757. - application/x-www-form-urlencoded
  758. - application/json
  759. tags:
  760. - Login
  761. parameters:
  762. - name: username
  763. in: formData
  764. required: true
  765. description: |
  766. Your username
  767. type: string
  768. - name: password
  769. in: formData
  770. required: true
  771. description: |
  772. Your password
  773. type: string
  774. format: password
  775. responses:
  776. 200:
  777. description: |-
  778. Successful authentication
  779. schema:
  780. items:
  781. properties:
  782. id:
  783. type: string
  784. token:
  785. type: string
  786. tokenExpires:
  787. type: string
  788. 400:
  789. description: |
  790. Error in authentication
  791. schema:
  792. items:
  793. properties:
  794. error:
  795. type: number
  796. reason:
  797. type: string
  798. default:
  799. description: |
  800. Error in authentication
  801. /users/register:
  802. post:
  803. operationId: register
  804. summary: Register with REST API
  805. description: |
  806. Notes:
  807. - You will need to provide the token for any of the authenticated methods.
  808. consumes:
  809. - application/x-www-form-urlencoded
  810. - application/json
  811. tags:
  812. - Login
  813. parameters:
  814. - name: username
  815. in: formData
  816. required: true
  817. description: |
  818. Your username
  819. type: string
  820. - name: password
  821. in: formData
  822. required: true
  823. description: |
  824. Your password
  825. type: string
  826. format: password
  827. - name: email
  828. in: formData
  829. required: true
  830. description: |
  831. Your email
  832. type: string
  833. responses:
  834. 200:
  835. description: |-
  836. Successful registration
  837. schema:
  838. items:
  839. properties:
  840. id:
  841. type: string
  842. token:
  843. type: string
  844. tokenExpires:
  845. type: string
  846. 400:
  847. description: |
  848. Error in registration
  849. schema:
  850. items:
  851. properties:
  852. error:
  853. type: number
  854. reason:
  855. type: string
  856. default:
  857. description: |
  858. Error in registration
  859. '''.format(version))
  860. # GET and POST on the same path are valid, we need to reshuffle the paths
  861. # with the path as the sorting key
  862. methods = {}
  863. for ep in entry_points:
  864. if ep.path not in methods:
  865. methods[ep.path] = []
  866. methods[ep.path].append(ep)
  867. sorted_paths = list(methods.keys())
  868. sorted_paths.sort()
  869. for path in sorted_paths:
  870. print(' {}:'.format(methods[path][0].url))
  871. for ep in methods[path]:
  872. ep.print_openapi()
  873. print('definitions:')
  874. for schema in schemas.values():
  875. # do not export the objects if there is no API attached
  876. if not schema.used:
  877. continue
  878. schema.print_openapi()
  879. def main():
  880. parser = argparse.ArgumentParser(description='Generate an OpenAPI 2.0 from the given JS schemas.')
  881. script_dir = os.path.dirname(os.path.realpath(__file__))
  882. parser.add_argument('--release', default='git-master', nargs=1,
  883. help='the current version of the API, can be retrieved by running `git describe --tags --abbrev=0`')
  884. parser.add_argument('dir', default=os.path.abspath('{}/../models'.format(script_dir)), nargs='?',
  885. help='the directory where to look for schemas')
  886. args = parser.parse_args()
  887. schemas, entry_points = parse_schemas(args.dir)
  888. generate_openapi(schemas, entry_points, args.release[0])
  889. if __name__ == '__main__':
  890. main()