printer.js.flow 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. // @flow strict
  2. import type { ASTNode } from './ast';
  3. import { visit } from './visitor';
  4. import { printBlockString } from './blockString';
  5. /**
  6. * Converts an AST into a string, using one set of reasonable
  7. * formatting rules.
  8. */
  9. export function print(ast: ASTNode): string {
  10. return visit(ast, { leave: printDocASTReducer });
  11. }
  12. const MAX_LINE_LENGTH = 80;
  13. // TODO: provide better type coverage in future
  14. const printDocASTReducer: any = {
  15. Name: (node) => node.value,
  16. Variable: (node) => '$' + node.name,
  17. // Document
  18. Document: (node) => join(node.definitions, '\n\n') + '\n',
  19. OperationDefinition(node) {
  20. const op = node.operation;
  21. const name = node.name;
  22. const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')');
  23. const directives = join(node.directives, ' ');
  24. const selectionSet = node.selectionSet;
  25. // Anonymous queries with no directives or variable definitions can use
  26. // the query short form.
  27. return !name && !directives && !varDefs && op === 'query'
  28. ? selectionSet
  29. : join([op, join([name, varDefs]), directives, selectionSet], ' ');
  30. },
  31. VariableDefinition: ({ variable, type, defaultValue, directives }) =>
  32. variable +
  33. ': ' +
  34. type +
  35. wrap(' = ', defaultValue) +
  36. wrap(' ', join(directives, ' ')),
  37. SelectionSet: ({ selections }) => block(selections),
  38. Field: ({ alias, name, arguments: args, directives, selectionSet }) => {
  39. const prefix = wrap('', alias, ': ') + name;
  40. let argsLine = prefix + wrap('(', join(args, ', '), ')');
  41. if (argsLine.length > MAX_LINE_LENGTH) {
  42. argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)');
  43. }
  44. return join([argsLine, join(directives, ' '), selectionSet], ' ');
  45. },
  46. Argument: ({ name, value }) => name + ': ' + value,
  47. // Fragments
  48. FragmentSpread: ({ name, directives }) =>
  49. '...' + name + wrap(' ', join(directives, ' ')),
  50. InlineFragment: ({ typeCondition, directives, selectionSet }) =>
  51. join(
  52. ['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet],
  53. ' ',
  54. ),
  55. FragmentDefinition: ({
  56. name,
  57. typeCondition,
  58. variableDefinitions,
  59. directives,
  60. selectionSet,
  61. }) =>
  62. // Note: fragment variable definitions are experimental and may be changed
  63. // or removed in the future.
  64. `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` +
  65. `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` +
  66. selectionSet,
  67. // Value
  68. IntValue: ({ value }) => value,
  69. FloatValue: ({ value }) => value,
  70. StringValue: ({ value, block: isBlockString }, key) =>
  71. isBlockString
  72. ? printBlockString(value, key === 'description' ? '' : ' ')
  73. : JSON.stringify(value),
  74. BooleanValue: ({ value }) => (value ? 'true' : 'false'),
  75. NullValue: () => 'null',
  76. EnumValue: ({ value }) => value,
  77. ListValue: ({ values }) => '[' + join(values, ', ') + ']',
  78. ObjectValue: ({ fields }) => '{' + join(fields, ', ') + '}',
  79. ObjectField: ({ name, value }) => name + ': ' + value,
  80. // Directive
  81. Directive: ({ name, arguments: args }) =>
  82. '@' + name + wrap('(', join(args, ', '), ')'),
  83. // Type
  84. NamedType: ({ name }) => name,
  85. ListType: ({ type }) => '[' + type + ']',
  86. NonNullType: ({ type }) => type + '!',
  87. // Type System Definitions
  88. SchemaDefinition: addDescription(({ directives, operationTypes }) =>
  89. join(['schema', join(directives, ' '), block(operationTypes)], ' '),
  90. ),
  91. OperationTypeDefinition: ({ operation, type }) => operation + ': ' + type,
  92. ScalarTypeDefinition: addDescription(({ name, directives }) =>
  93. join(['scalar', name, join(directives, ' ')], ' '),
  94. ),
  95. ObjectTypeDefinition: addDescription(
  96. ({ name, interfaces, directives, fields }) =>
  97. join(
  98. [
  99. 'type',
  100. name,
  101. wrap('implements ', join(interfaces, ' & ')),
  102. join(directives, ' '),
  103. block(fields),
  104. ],
  105. ' ',
  106. ),
  107. ),
  108. FieldDefinition: addDescription(
  109. ({ name, arguments: args, type, directives }) =>
  110. name +
  111. (hasMultilineItems(args)
  112. ? wrap('(\n', indent(join(args, '\n')), '\n)')
  113. : wrap('(', join(args, ', '), ')')) +
  114. ': ' +
  115. type +
  116. wrap(' ', join(directives, ' ')),
  117. ),
  118. InputValueDefinition: addDescription(
  119. ({ name, type, defaultValue, directives }) =>
  120. join(
  121. [name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')],
  122. ' ',
  123. ),
  124. ),
  125. InterfaceTypeDefinition: addDescription(
  126. ({ name, interfaces, directives, fields }) =>
  127. join(
  128. [
  129. 'interface',
  130. name,
  131. wrap('implements ', join(interfaces, ' & ')),
  132. join(directives, ' '),
  133. block(fields),
  134. ],
  135. ' ',
  136. ),
  137. ),
  138. UnionTypeDefinition: addDescription(({ name, directives, types }) =>
  139. join(
  140. [
  141. 'union',
  142. name,
  143. join(directives, ' '),
  144. types && types.length !== 0 ? '= ' + join(types, ' | ') : '',
  145. ],
  146. ' ',
  147. ),
  148. ),
  149. EnumTypeDefinition: addDescription(({ name, directives, values }) =>
  150. join(['enum', name, join(directives, ' '), block(values)], ' '),
  151. ),
  152. EnumValueDefinition: addDescription(({ name, directives }) =>
  153. join([name, join(directives, ' ')], ' '),
  154. ),
  155. InputObjectTypeDefinition: addDescription(({ name, directives, fields }) =>
  156. join(['input', name, join(directives, ' '), block(fields)], ' '),
  157. ),
  158. DirectiveDefinition: addDescription(
  159. ({ name, arguments: args, repeatable, locations }) =>
  160. 'directive @' +
  161. name +
  162. (hasMultilineItems(args)
  163. ? wrap('(\n', indent(join(args, '\n')), '\n)')
  164. : wrap('(', join(args, ', '), ')')) +
  165. (repeatable ? ' repeatable' : '') +
  166. ' on ' +
  167. join(locations, ' | '),
  168. ),
  169. SchemaExtension: ({ directives, operationTypes }) =>
  170. join(['extend schema', join(directives, ' '), block(operationTypes)], ' '),
  171. ScalarTypeExtension: ({ name, directives }) =>
  172. join(['extend scalar', name, join(directives, ' ')], ' '),
  173. ObjectTypeExtension: ({ name, interfaces, directives, fields }) =>
  174. join(
  175. [
  176. 'extend type',
  177. name,
  178. wrap('implements ', join(interfaces, ' & ')),
  179. join(directives, ' '),
  180. block(fields),
  181. ],
  182. ' ',
  183. ),
  184. InterfaceTypeExtension: ({ name, interfaces, directives, fields }) =>
  185. join(
  186. [
  187. 'extend interface',
  188. name,
  189. wrap('implements ', join(interfaces, ' & ')),
  190. join(directives, ' '),
  191. block(fields),
  192. ],
  193. ' ',
  194. ),
  195. UnionTypeExtension: ({ name, directives, types }) =>
  196. join(
  197. [
  198. 'extend union',
  199. name,
  200. join(directives, ' '),
  201. types && types.length !== 0 ? '= ' + join(types, ' | ') : '',
  202. ],
  203. ' ',
  204. ),
  205. EnumTypeExtension: ({ name, directives, values }) =>
  206. join(['extend enum', name, join(directives, ' '), block(values)], ' '),
  207. InputObjectTypeExtension: ({ name, directives, fields }) =>
  208. join(['extend input', name, join(directives, ' '), block(fields)], ' '),
  209. };
  210. function addDescription(cb) {
  211. return (node) => join([node.description, cb(node)], '\n');
  212. }
  213. /**
  214. * Given maybeArray, print an empty string if it is null or empty, otherwise
  215. * print all items together separated by separator if provided
  216. */
  217. function join(maybeArray: ?Array<string>, separator = ''): string {
  218. return maybeArray?.filter((x) => x).join(separator) ?? '';
  219. }
  220. /**
  221. * Given array, print each item on its own line, wrapped in an
  222. * indented "{ }" block.
  223. */
  224. function block(array: ?Array<string>): string {
  225. return wrap('{\n', indent(join(array, '\n')), '\n}');
  226. }
  227. /**
  228. * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string.
  229. */
  230. function wrap(start: string, maybeString: ?string, end: string = ''): string {
  231. return maybeString != null && maybeString !== ''
  232. ? start + maybeString + end
  233. : '';
  234. }
  235. function indent(str: string): string {
  236. return wrap(' ', str.replace(/\n/g, '\n '));
  237. }
  238. function isMultiline(str: string): boolean {
  239. return str.indexOf('\n') !== -1;
  240. }
  241. function hasMultilineItems(maybeArray: ?Array<string>): boolean {
  242. return maybeArray != null && maybeArray.some(isMultiline);
  243. }