introspection.lua 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. local path = (...):gsub('%.[^%.]+$', '')
  2. local types = require(path .. '.types')
  3. local util = require(path .. '.util')
  4. local cjson = require 'cjson' -- needs to be cloned from here https://github.com/openresty/lua-cjson for cjson.empty_array feature
  5. local function isNullish(value)
  6. return value == nil
  7. end
  8. local function instanceof(t, s)
  9. return t.__type == s
  10. end
  11. local function resolveDirective(directive)
  12. local res = {}
  13. if directive.onQuery then table.insert(res, 'QUERY') end
  14. if directive.onMutation then table.insert(res, 'MUTATION') end
  15. if directive.onSubscription then table.insert(res, 'SUBSCRIPTION') end
  16. if directive.onField then table.insert(res, 'FIELD') end
  17. if directive.onFragmentDefinition then table.insert(res, 'FRAGMENT_DEFINITION') end
  18. if directive.onFragmentSpread then table.insert(res, 'FRAGMENT_SPREAD') end
  19. if directive.onInlineFragment then table.insert(res, 'INLINE_FRAGMENT') end
  20. return res
  21. end
  22. local function mapToList(m)
  23. local r = {}
  24. for k,v in pairs(m) do
  25. table.insert(r, v)
  26. end
  27. return r
  28. end
  29. local __Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue,__EnumValue, TypeKind, __TypeKind, SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef, astFromValue, printAst, printers
  30. local DirectiveLocation = {
  31. QUERY = 'QUERY', MUTATION = 'MUTATION', SUBSCRIPTION = 'SUBSCRIPTION', FIELD = 'FIELD', FRAGMENT_DEFINITION = 'FRAGMENT_DEFINITION', FRAGMENT_SPREAD = 'FRAGMENT_SPREAD', INLINE_FRAGMENT = 'INLINE_FRAGMENT'
  32. }
  33. __Schema = types.object({
  34. name = '__Schema',
  35. description =
  36. 'A GraphQL Schema defines the capabilities of a GraphQL server. It ' ..
  37. 'exposes all available types and directives on the server, as well as ' ..
  38. 'the entry points for query, mutation, and subscription operations.',
  39. fields = function() return {
  40. types = {
  41. description = 'A list of all types supported by this server.',
  42. kind = types.nonNull(types.list(types.nonNull(__Type))),
  43. resolve = function(schema)
  44. local typeMap = schema:getTypeMap(); local res = {}
  45. for k,v in pairs(typeMap) do table.insert(res, typeMap[k]) end; return res
  46. end
  47. },
  48. queryType = {
  49. description = 'The type that query operations will be rooted at.',
  50. kind = types.nonNull(__Type),
  51. resolve = function(schema) return schema:getQueryType() end
  52. },
  53. mutationType = {
  54. description = 'If this server supports mutation, the type that ' ..
  55. 'mutation operations will be rooted at.',
  56. kind = __Type,
  57. resolve = function(schema) return schema:getMutationType() end
  58. },
  59. subscriptionType = {
  60. description = 'If this server support subscription, the type that ' ..
  61. 'subscription operations will be rooted at.',
  62. kind = __Type,
  63. resolve = function(schema) return schema:getSubscriptionType() end
  64. },
  65. directives = {
  66. description = 'A list of all directives supported by this server.',
  67. kind =
  68. types.nonNull(types.list(types.nonNull(__Directive))),
  69. resolve = function(schema) return schema.directives end
  70. }
  71. } end
  72. });
  73. __Directive = types.object({
  74. name = '__Directive',
  75. description =
  76. 'A Directive provides a way to describe alternate runtime execution and ' ..
  77. 'type validation behavior in a GraphQL document.' ..
  78. '\n\nIn some cases, you need to provide options to alter GraphQL’s ' ..
  79. 'execution behavior in ways field arguments will not suffice, such as ' ..
  80. 'conditionally including or skipping a field. Directives provide this by ' ..
  81. 'describing additional information to the executor.',
  82. fields = function() return {
  83. name = types.nonNull(types.string),
  84. description = types.string,
  85. locations = {
  86. kind = types.nonNull(types.list(types.nonNull(
  87. __DirectiveLocation
  88. ))), resolve = resolveDirective
  89. },
  90. args = {
  91. kind =
  92. types.nonNull(types.list(types.nonNull(__InputValue))),
  93. --resolve = function(directive) return directive.arguments or {} end
  94. resolve = function(field)
  95. local args = {}
  96. local transform = function(a, n)
  97. if a.__type then
  98. return {kind = a, name = n}
  99. else
  100. if not a.name then
  101. local r = {name = n}
  102. for k,v in pairs(a) do
  103. r[k] = v
  104. end
  105. return r
  106. else
  107. return a
  108. end
  109. end
  110. end
  111. for k, v in pairs(field.arguments or {}) do table.insert(args, transform(v, k)) end
  112. -- p(args)
  113. -- return args
  114. if #args > 0 then return args else return cjson.empty_array end
  115. end
  116. },
  117. -- NOTE = the following three fields are deprecated and are no longer part
  118. -- of the GraphQL specification.
  119. onOperation = {
  120. deprecationReason = 'Use `locations`.',
  121. kind = types.nonNull(types.boolean),
  122. resolve = function(d) return
  123. d.locations:find(DirectiveLocation.QUERY) ~= nil or
  124. d.locations:find(DirectiveLocation.MUTATION) ~= nil or
  125. d.locations:find(DirectiveLocation.SUBSCRIPTION) ~= nil end
  126. },
  127. onFragment = {
  128. deprecationReason = 'Use `locations`.',
  129. kind = types.nonNull(types.boolean),
  130. resolve = function(d) return
  131. d.locations:find(DirectiveLocation.FRAGMENT_SPREAD) ~= nil or
  132. d.locations:find(DirectiveLocation.INLINE_FRAGMENT) ~= nil or
  133. d.locations:find(DirectiveLocation.FRAGMENT_DEFINITION) ~= nil end
  134. },
  135. onField = {
  136. deprecationReason = 'Use `locations`.',
  137. kind = types.nonNull(types.boolean),
  138. resolve = function(d) return d.locations:find(DirectiveLocation.FIELD) ~= nil end
  139. }
  140. } end
  141. });
  142. __DirectiveLocation = types.enum({
  143. name = '__DirectiveLocation',
  144. description =
  145. 'A Directive can be adjacent to many parts of the GraphQL language, a ' ..
  146. '__DirectiveLocation describes one such possible adjacencies.',
  147. values = {
  148. QUERY = {
  149. value = DirectiveLocation.QUERY,
  150. description = 'Location adjacent to a query operation.'
  151. },
  152. MUTATION = {
  153. value = DirectiveLocation.MUTATION,
  154. description = 'Location adjacent to a mutation operation.'
  155. },
  156. SUBSCRIPTION = {
  157. value = DirectiveLocation.SUBSCRIPTION,
  158. description = 'Location adjacent to a subscription operation.'
  159. },
  160. FIELD = {
  161. value = DirectiveLocation.FIELD,
  162. description = 'Location adjacent to a field.'
  163. },
  164. FRAGMENT_DEFINITION = {
  165. value = DirectiveLocation.FRAGMENT_DEFINITION,
  166. description = 'Location adjacent to a fragment definition.'
  167. },
  168. FRAGMENT_SPREAD = {
  169. value = DirectiveLocation.FRAGMENT_SPREAD,
  170. description = 'Location adjacent to a fragment spread.'
  171. },
  172. INLINE_FRAGMENT = {
  173. value = DirectiveLocation.INLINE_FRAGMENT,
  174. description = 'Location adjacent to an inline fragment.'
  175. },
  176. }
  177. });
  178. __Type = types.object({
  179. name = '__Type',
  180. description =
  181. 'The fundamental unit of any GraphQL Schema is the type. There are ' ..
  182. 'many kinds of types in GraphQL as represented by the `__TypeKind` enum.' ..
  183. '\n\nDepending on the kind of a type, certain fields describe ' ..
  184. 'information about that type. Scalar types provide no information ' ..
  185. 'beyond a name and description, while Enum types provide their values. ' ..
  186. 'Object and Interface types provide the fields they describe. Abstract ' ..
  187. 'types, Union and Interface, provide the Object types possible ' ..
  188. 'at runtime. List and NonNull types compose other types.',
  189. fields = function() return {
  190. kind = {
  191. kind = types.nonNull(__TypeKind),
  192. resolve = function (type)
  193. if instanceof(type, 'Scalar') then
  194. return TypeKind.SCALAR;
  195. elseif instanceof(type, 'Object') then
  196. return TypeKind.OBJECT;
  197. elseif instanceof(type, 'Interface') then
  198. return TypeKind.INTERFACE;
  199. elseif instanceof(type, 'Union') then
  200. return TypeKind.UNION;
  201. elseif instanceof(type, 'Enum') then
  202. return TypeKind.ENUM;
  203. elseif instanceof(type, 'InputObject') then
  204. return TypeKind.INPUT_OBJECT;
  205. elseif instanceof(type, 'List') then
  206. return TypeKind.LIST;
  207. elseif instanceof(type, 'NonNull') then
  208. return TypeKind.NON_NULL;
  209. end
  210. error('Unknown kind of kind = ' .. type);
  211. end
  212. },
  213. name = types.string,
  214. description = types.string,
  215. fields = {
  216. kind = types.list(types.nonNull(__Field)),
  217. arguments = {
  218. -- includeDeprecated = types.boolean
  219. includeDeprecated = { kind = types.boolean, defaultValue = false }
  220. },
  221. resolve = function(t, args)
  222. if instanceof(t, 'Object') or
  223. instanceof(t, 'Interface') then
  224. local fieldMap = t.fields;
  225. local fields = {}; for k,v in pairs(fieldMap) do table.insert(fields, fieldMap[k]) end
  226. if not args.includeDeprecated then
  227. fields = util.filter(fields, function(field) return not field.deprecationReason end);
  228. end
  229. if #fields > 0 then return fields else return cjson.empty_array end
  230. end
  231. return nil;
  232. end
  233. },
  234. interfaces = {
  235. kind = types.list(types.nonNull(__Type)),
  236. resolve = function(type)
  237. if instanceof(type, 'Object') then
  238. return type.interfaces and type.interfaces or cjson.empty_array;
  239. end
  240. end
  241. },
  242. possibleTypes = {
  243. kind = types.list(types.nonNull(__Type)),
  244. resolve = function(type, args, context, obj)
  245. if instanceof(type, 'Interface') or
  246. instanceof(type, 'Union') then
  247. return context.schema:getPossibleTypes(type);
  248. end
  249. end
  250. },
  251. enumValues = {
  252. kind = types.list(types.nonNull(__EnumValue)),
  253. arguments = {
  254. -- includeDeprecated = types.boolean
  255. includeDeprecated = { kind = types.boolean, defaultValue = false }
  256. },
  257. resolve = function(type, args)
  258. if instanceof(type, 'Enum') then
  259. local values = type.values;
  260. if not args.includeDeprecated then
  261. values = util.filter(values, function(value) return not value.deprecationReason end);
  262. end
  263. return mapToList(values);
  264. end
  265. end
  266. },
  267. inputFields = {
  268. kind = types.list(types.nonNull(__InputValue)),
  269. resolve = function(type)
  270. if instanceof(type, 'InputObject') then
  271. local fieldMap = type.fields;
  272. local fields = {}; for k,v in pairs(fieldMap) do table.insert(fields, fieldMap[k]) end; return fields
  273. end
  274. end
  275. },
  276. ofType = { kind = __Type }
  277. } end
  278. });
  279. __Field = types.object({
  280. name = '__Field',
  281. description =
  282. 'Object and Interface types are described by a list of Fields, each of ' ..
  283. 'which has a name, potentially a list of arguments, and a return type.',
  284. fields = function() return {
  285. name = types.nonNull(types.string),
  286. description = types.string,
  287. args = {
  288. -- kind = types.list(__InputValue),
  289. kind = types.nonNull(types.list(types.nonNull(__InputValue))),
  290. resolve = function(field)
  291. local args = {}
  292. local transform = function(a, n)
  293. if a.__type then
  294. return {kind = a, name = n}
  295. else
  296. if not a.name then
  297. local r = {name = n}
  298. for k,v in pairs(a) do
  299. r[k] = v
  300. end
  301. return r
  302. else
  303. return a
  304. end
  305. end
  306. end
  307. for k, v in pairs(field.arguments or {}) do table.insert(args, transform(v, k)) end
  308. -- return args
  309. if #args > 0 then return args else return cjson.empty_array end
  310. end
  311. },
  312. type = { kind = types.nonNull(__Type), resolve = function(field) return field.kind end },
  313. isDeprecated = {
  314. kind = types.nonNull(types.boolean),
  315. resolve = function(field) return not isNullish(field.deprecationReason) end
  316. },
  317. deprecationReason = types.string
  318. } end
  319. });
  320. __InputValue = types.object({
  321. name = '__InputValue',
  322. description =
  323. 'Arguments provided to Fields or Directives and the input fields of an ' ..
  324. 'InputObject are represented as Input Values which describe their type ' ..
  325. 'and optionally a default value.',
  326. fields = function() return {
  327. name = types.nonNull(types.string),
  328. description = types.string,
  329. type = { kind = types.nonNull(__Type), resolve = function(field) return field.kind end },
  330. defaultValue = {
  331. kind = types.string,
  332. description =
  333. 'A GraphQL-formatted string representing the default value for this ' ..
  334. 'input value.',
  335. resolve = function(inputVal) if isNullish(inputVal.defaultValue)
  336. then return nil
  337. else return printAst(astFromValue(inputVal.defaultValue, inputVal)) end end
  338. }
  339. } end
  340. });
  341. __EnumValue = types.object({
  342. name = '__EnumValue',
  343. description =
  344. 'One possible value for a given Enum. Enum values are unique values, not ' ..
  345. 'a placeholder for a string or numeric value. However an Enum value is ' ..
  346. 'returned in a JSON response as a string.',
  347. fields = function() return {
  348. name = types.nonNull(types.string),
  349. description = types.string,
  350. isDeprecated = {
  351. kind = types.nonNull(types.boolean),
  352. resolve = function(enumValue) return not isNullish(enumValue.deprecationReason) end
  353. },
  354. deprecationReason =
  355. types.string
  356. } end
  357. });
  358. TypeKind = {
  359. SCALAR = 'SCALAR',
  360. OBJECT = 'OBJECT',
  361. INTERFACE = 'INTERFACE',
  362. UNION = 'UNION',
  363. ENUM = 'ENUM',
  364. INPUT_OBJECT = 'INPUT_OBJECT',
  365. LIST = 'LIST',
  366. NON_NULL = 'NON_NULL'
  367. };
  368. __TypeKind = types.enum({
  369. name = '__TypeKind',
  370. description = 'An enum describing what kind of type a given `__Type` is.',
  371. values = {
  372. SCALAR = {
  373. value = TypeKind.SCALAR,
  374. description = 'Indicates this type is a scalar.'
  375. },
  376. OBJECT = {
  377. value = TypeKind.OBJECT,
  378. description = 'Indicates this type is an object. ' ..
  379. '`fields` and `interfaces` are valid fields.'
  380. },
  381. INTERFACE = {
  382. value = TypeKind.INTERFACE,
  383. description = 'Indicates this type is an interface. ' ..
  384. '`fields` and `possibleTypes` are valid fields.'
  385. },
  386. UNION = {
  387. value = TypeKind.UNION,
  388. description = 'Indicates this type is a union. ' ..
  389. '`possibleTypes` is a valid field.'
  390. },
  391. ENUM = {
  392. value = TypeKind.ENUM,
  393. description = 'Indicates this type is an enum. ' ..
  394. '`enumValues` is a valid field.'
  395. },
  396. INPUT_OBJECT = {
  397. value = TypeKind.INPUT_OBJECT,
  398. description = 'Indicates this type is an input object. ' ..
  399. '`inputFields` is a valid field.'
  400. },
  401. LIST = {
  402. value = TypeKind.LIST,
  403. description = 'Indicates this type is a list. ' ..
  404. '`ofType` is a valid field.'
  405. },
  406. NON_NULL = {
  407. value = TypeKind.NON_NULL,
  408. description = 'Indicates this type is a non-null. ' ..
  409. '`ofType` is a valid field.'
  410. }
  411. }
  412. });
  413. --
  414. -- Note that these are GraphQLFieldDefinition and not GraphQLFieldConfig,
  415. -- so the format for args is different.
  416. --
  417. SchemaMetaFieldDef = {
  418. name = '__schema',
  419. kind = types.nonNull(__Schema),
  420. description = 'Access the current type schema of this server.',
  421. arguments = {},
  422. resolve = function(source, args, context, obj) return context.schema end
  423. };
  424. TypeMetaFieldDef = {
  425. name = '__type',
  426. kind = __Type,
  427. description = 'Request the type information of a single type.',
  428. arguments = {
  429. name = types.nonNull(types.string)
  430. }
  431. --,resolve = function(source, { name } = { name = string }, context, { schema })
  432. -- return schema.getType(name) end
  433. };
  434. TypeNameMetaFieldDef = {
  435. name = '__typename',
  436. kind = types.nonNull(types.string),
  437. description = 'The name of the current Object type at runtime.',
  438. arguments = {},
  439. resolve = function(source, args, context, obj) return obj.parentType.name end
  440. };
  441. -- Produces a GraphQL Value AST given a lua value.
  442. -- Optionally, a GraphQL type may be provided, which will be used to
  443. -- disambiguate between value primitives.
  444. -- | JSON Value | GraphQL Value |
  445. -- | ------------- | -------------------- |
  446. -- | Object | Input Object |
  447. -- | Array | List |
  448. -- | Boolean | Boolean |
  449. -- | String | String / Enum Value |
  450. -- | Number | Int / Float |
  451. local Kind = {
  452. LIST = 'ListValue',
  453. BOOLEAN = 'BooleanValue',
  454. FLOAT = 'FloatValue',
  455. INT = 'IntValue',
  456. FLOAT = 'FloatValue',
  457. ENUM = 'EnumValue',
  458. STRING = 'StringValue',
  459. OBJECT_FIELD = 'ObjectField',
  460. NAME = 'Name',
  461. OBJECT = 'ObjectValue'
  462. }
  463. printers = {
  464. IntValue = function(v) return v.value end,
  465. FloatValue = function(v) return v.value end,
  466. StringValue = function(v) return cjson.encode(v.value) end,
  467. BooleanValue = function(v) return cjson.encode(v.value) end,
  468. EnumValue = function(v) return v.value end,
  469. ListValue = function(v) return '[' .. table.concat(util.map(v.values, printAst), ', ') .. ']' end,
  470. ObjectValue = function(v) return '{' .. table.concat(util.map(v.fields, printAst), ', ') .. '}' end,
  471. ObjectField = function(v) return v.name .. ': ' .. v.value end
  472. }
  473. printAst = function(v)
  474. return printers[v.kind](v)
  475. end
  476. astFromValue = function(value, tt)
  477. -- Ensure flow knows that we treat function params as const.
  478. local _value = value
  479. if instanceof(tt,'NonNull') then
  480. -- Note: we're not checking that the result is non-null.
  481. -- This function is not responsible for validating the input value.
  482. return astFromValue(_value, tt.ofType)
  483. end
  484. if isNullish(_value) then
  485. return nil
  486. end
  487. -- Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
  488. -- the value is not an array, convert the value using the list's item type.
  489. if type(_value) == 'table' and #_value > 0 then
  490. local itemType = instanceof(tt, 'List') and tt.ofType or nil
  491. return {
  492. kind = Kind.LIST,
  493. values = util.map(_value, function(item)
  494. local itemValue = astFromValue(item, itemType)
  495. assert(itemValue, 'Could not create AST item.')
  496. return itemValue
  497. end)
  498. }
  499. elseif instanceof(tt, 'List') then
  500. -- Because GraphQL will accept single values as a "list of one" when
  501. -- expecting a list, if there's a non-array value and an expected list type,
  502. -- create an AST using the list's item type.
  503. return astFromValue(_value, tt.ofType)
  504. end
  505. if type(_value) == 'boolean' then
  506. return { kind = Kind.BOOLEAN, value = _value }
  507. end
  508. -- JavaScript numbers can be Float or Int values. Use the GraphQLType to
  509. -- differentiate if available, otherwise prefer Int if the value is a
  510. -- valid Int.
  511. if type(_value) == 'number' then
  512. local stringNum = String(_value)
  513. local isIntValue = _value%1 == 0
  514. if isIntValue then
  515. if tt == types.float then
  516. return { kind = Kind.FLOAT, value = stringNum .. '.0' }
  517. end
  518. return { kind = Kind.INT, value = stringNum }
  519. end
  520. return { kind = Kind.FLOAT, value = stringNum }
  521. end
  522. -- JavaScript strings can be Enum values or String values. Use the
  523. -- GraphQLType to differentiate if possible.
  524. if type(_value) == 'string' then
  525. if instanceof(tt, 'Enum') and _value:match('/^[_a-zA-Z][_a-zA-Z0-9]*$/') then
  526. return { kind =Kind.ENUM, value = _value }
  527. end
  528. -- Use JSON stringify, which uses the same string encoding as GraphQL,
  529. -- then remove the quotes.
  530. return {
  531. kind = Kind.STRING,
  532. value = (cjson.encode(_value)):sub(1, -1)
  533. }
  534. end
  535. -- last remaining possible typeof
  536. assert(type(_value) == 'table')
  537. assert(_value ~= nil)
  538. -- Populate the fields of the input object by creating ASTs from each value
  539. -- in the JavaScript object.
  540. local fields = {}
  541. for fieldName,v in pairs(_value) do
  542. local fieldType
  543. if instanceof(tt, 'InputObject') then
  544. local fieldDef = tt.fields[fieldName];
  545. fieldType = fieldDef and fieldDef.kind;
  546. end
  547. local fieldValue = astFromValue(_value[fieldName], fieldType);
  548. if fieldValue then
  549. table.insert(fields, {
  550. kind = Kind.OBJECT_FIELD,
  551. name = { kind = Kind.NAME, value = fieldName },
  552. value = fieldValue
  553. })
  554. end
  555. end
  556. return { kind = Kind.OBJECT, fields = fields }
  557. end
  558. return {
  559. __Schema = __Schema,
  560. __Directive = __Directive,
  561. __DirectiveLocation = __DirectiveLocation,
  562. __Type = __Type,
  563. __Field = __Field,
  564. __EnumValue = __EnumValue,
  565. TypeKind = TypeKind,
  566. __TypeKind = __TypeKind,
  567. SchemaMetaFieldDef = SchemaMetaFieldDef,
  568. TypeMetaFieldDef = TypeMetaFieldDef,
  569. TypeNameMetaFieldDef = TypeNameMetaFieldDef
  570. }