UNPKG

12.3 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.visit = visit;
7exports.visitInParallel = visitInParallel;
8exports.visitWithTypeInfo = visitWithTypeInfo;
9exports.getVisitFn = getVisitFn;
10exports.BREAK = exports.QueryDocumentKeys = void 0;
11
12var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
13
14function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
16var QueryDocumentKeys = {
17 Name: [],
18 Document: ['definitions'],
19 OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'],
20 VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'],
21 Variable: ['name'],
22 SelectionSet: ['selections'],
23 Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],
24 Argument: ['name', 'value'],
25 FragmentSpread: ['name', 'directives'],
26 InlineFragment: ['typeCondition', 'directives', 'selectionSet'],
27 FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed
28 // or removed in the future.
29 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'],
30 IntValue: [],
31 FloatValue: [],
32 StringValue: [],
33 BooleanValue: [],
34 NullValue: [],
35 EnumValue: [],
36 ListValue: ['values'],
37 ObjectValue: ['fields'],
38 ObjectField: ['name', 'value'],
39 Directive: ['name', 'arguments'],
40 NamedType: ['name'],
41 ListType: ['type'],
42 NonNullType: ['type'],
43 SchemaDefinition: ['directives', 'operationTypes'],
44 OperationTypeDefinition: ['type'],
45 ScalarTypeDefinition: ['description', 'name', 'directives'],
46 ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],
47 FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],
48 InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'],
49 InterfaceTypeDefinition: ['description', 'name', 'directives', 'fields'],
50 UnionTypeDefinition: ['description', 'name', 'directives', 'types'],
51 EnumTypeDefinition: ['description', 'name', 'directives', 'values'],
52 EnumValueDefinition: ['description', 'name', 'directives'],
53 InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],
54 DirectiveDefinition: ['description', 'name', 'arguments', 'locations'],
55 SchemaExtension: ['directives', 'operationTypes'],
56 ScalarTypeExtension: ['name', 'directives'],
57 ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
58 InterfaceTypeExtension: ['name', 'directives', 'fields'],
59 UnionTypeExtension: ['name', 'directives', 'types'],
60 EnumTypeExtension: ['name', 'directives', 'values'],
61 InputObjectTypeExtension: ['name', 'directives', 'fields']
62};
63exports.QueryDocumentKeys = QueryDocumentKeys;
64var BREAK = Object.freeze({});
65/**
66 * visit() will walk through an AST using a depth first traversal, calling
67 * the visitor's enter function at each node in the traversal, and calling the
68 * leave function after visiting that node and all of its child nodes.
69 *
70 * By returning different values from the enter and leave functions, the
71 * behavior of the visitor can be altered, including skipping over a sub-tree of
72 * the AST (by returning false), editing the AST by returning a value or null
73 * to remove the value, or to stop the whole traversal by returning BREAK.
74 *
75 * When using visit() to edit an AST, the original AST will not be modified, and
76 * a new version of the AST with the changes applied will be returned from the
77 * visit function.
78 *
79 * const editedAST = visit(ast, {
80 * enter(node, key, parent, path, ancestors) {
81 * // @return
82 * // undefined: no action
83 * // false: skip visiting this node
84 * // visitor.BREAK: stop visiting altogether
85 * // null: delete this node
86 * // any value: replace this node with the returned value
87 * },
88 * leave(node, key, parent, path, ancestors) {
89 * // @return
90 * // undefined: no action
91 * // false: no action
92 * // visitor.BREAK: stop visiting altogether
93 * // null: delete this node
94 * // any value: replace this node with the returned value
95 * }
96 * });
97 *
98 * Alternatively to providing enter() and leave() functions, a visitor can
99 * instead provide functions named the same as the kinds of AST nodes, or
100 * enter/leave visitors at a named key, leading to four permutations of
101 * visitor API:
102 *
103 * 1) Named visitors triggered when entering a node a specific kind.
104 *
105 * visit(ast, {
106 * Kind(node) {
107 * // enter the "Kind" node
108 * }
109 * })
110 *
111 * 2) Named visitors that trigger upon entering and leaving a node of
112 * a specific kind.
113 *
114 * visit(ast, {
115 * Kind: {
116 * enter(node) {
117 * // enter the "Kind" node
118 * }
119 * leave(node) {
120 * // leave the "Kind" node
121 * }
122 * }
123 * })
124 *
125 * 3) Generic visitors that trigger upon entering and leaving any node.
126 *
127 * visit(ast, {
128 * enter(node) {
129 * // enter any node
130 * },
131 * leave(node) {
132 * // leave any node
133 * }
134 * })
135 *
136 * 4) Parallel visitors for entering and leaving nodes of a specific kind.
137 *
138 * visit(ast, {
139 * enter: {
140 * Kind(node) {
141 * // enter the "Kind" node
142 * }
143 * },
144 * leave: {
145 * Kind(node) {
146 * // leave the "Kind" node
147 * }
148 * }
149 * })
150 */
151
152exports.BREAK = BREAK;
153
154function visit(root, visitor) {
155 var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys;
156
157 /* eslint-disable no-undef-init */
158 var stack = undefined;
159 var inArray = Array.isArray(root);
160 var keys = [root];
161 var index = -1;
162 var edits = [];
163 var node = undefined;
164 var key = undefined;
165 var parent = undefined;
166 var path = [];
167 var ancestors = [];
168 var newRoot = root;
169 /* eslint-enable no-undef-init */
170
171 do {
172 index++;
173 var isLeaving = index === keys.length;
174 var isEdited = isLeaving && edits.length !== 0;
175
176 if (isLeaving) {
177 key = ancestors.length === 0 ? undefined : path[path.length - 1];
178 node = parent;
179 parent = ancestors.pop();
180
181 if (isEdited) {
182 if (inArray) {
183 node = node.slice();
184 } else {
185 var clone = {};
186
187 for (var _i2 = 0, _Object$keys2 = Object.keys(node); _i2 < _Object$keys2.length; _i2++) {
188 var k = _Object$keys2[_i2];
189 clone[k] = node[k];
190 }
191
192 node = clone;
193 }
194
195 var editOffset = 0;
196
197 for (var ii = 0; ii < edits.length; ii++) {
198 var editKey = edits[ii][0];
199 var editValue = edits[ii][1];
200
201 if (inArray) {
202 editKey -= editOffset;
203 }
204
205 if (inArray && editValue === null) {
206 node.splice(editKey, 1);
207 editOffset++;
208 } else {
209 node[editKey] = editValue;
210 }
211 }
212 }
213
214 index = stack.index;
215 keys = stack.keys;
216 edits = stack.edits;
217 inArray = stack.inArray;
218 stack = stack.prev;
219 } else {
220 key = parent ? inArray ? index : keys[index] : undefined;
221 node = parent ? parent[key] : newRoot;
222
223 if (node === null || node === undefined) {
224 continue;
225 }
226
227 if (parent) {
228 path.push(key);
229 }
230 }
231
232 var result = void 0;
233
234 if (!Array.isArray(node)) {
235 if (!isNode(node)) {
236 throw new Error('Invalid AST Node: ' + (0, _inspect.default)(node));
237 }
238
239 var visitFn = getVisitFn(visitor, node.kind, isLeaving);
240
241 if (visitFn) {
242 result = visitFn.call(visitor, node, key, parent, path, ancestors);
243
244 if (result === BREAK) {
245 break;
246 }
247
248 if (result === false) {
249 if (!isLeaving) {
250 path.pop();
251 continue;
252 }
253 } else if (result !== undefined) {
254 edits.push([key, result]);
255
256 if (!isLeaving) {
257 if (isNode(result)) {
258 node = result;
259 } else {
260 path.pop();
261 continue;
262 }
263 }
264 }
265 }
266 }
267
268 if (result === undefined && isEdited) {
269 edits.push([key, node]);
270 }
271
272 if (isLeaving) {
273 path.pop();
274 } else {
275 stack = {
276 inArray: inArray,
277 index: index,
278 keys: keys,
279 edits: edits,
280 prev: stack
281 };
282 inArray = Array.isArray(node);
283 keys = inArray ? node : visitorKeys[node.kind] || [];
284 index = -1;
285 edits = [];
286
287 if (parent) {
288 ancestors.push(parent);
289 }
290
291 parent = node;
292 }
293 } while (stack !== undefined);
294
295 if (edits.length !== 0) {
296 newRoot = edits[edits.length - 1][1];
297 }
298
299 return newRoot;
300}
301
302function isNode(maybeNode) {
303 return Boolean(maybeNode && typeof maybeNode.kind === 'string');
304}
305/**
306 * Creates a new visitor instance which delegates to many visitors to run in
307 * parallel. Each visitor will be visited for each node before moving on.
308 *
309 * If a prior visitor edits a node, no following visitors will see that node.
310 */
311
312
313function visitInParallel(visitors) {
314 var skipping = new Array(visitors.length);
315 return {
316 enter: function enter(node) {
317 for (var i = 0; i < visitors.length; i++) {
318 if (!skipping[i]) {
319 var fn = getVisitFn(visitors[i], node.kind,
320 /* isLeaving */
321 false);
322
323 if (fn) {
324 var result = fn.apply(visitors[i], arguments);
325
326 if (result === false) {
327 skipping[i] = node;
328 } else if (result === BREAK) {
329 skipping[i] = BREAK;
330 } else if (result !== undefined) {
331 return result;
332 }
333 }
334 }
335 }
336 },
337 leave: function leave(node) {
338 for (var i = 0; i < visitors.length; i++) {
339 if (!skipping[i]) {
340 var fn = getVisitFn(visitors[i], node.kind,
341 /* isLeaving */
342 true);
343
344 if (fn) {
345 var result = fn.apply(visitors[i], arguments);
346
347 if (result === BREAK) {
348 skipping[i] = BREAK;
349 } else if (result !== undefined && result !== false) {
350 return result;
351 }
352 }
353 } else if (skipping[i] === node) {
354 skipping[i] = null;
355 }
356 }
357 }
358 };
359}
360/**
361 * Creates a new visitor instance which maintains a provided TypeInfo instance
362 * along with visiting visitor.
363 */
364
365
366function visitWithTypeInfo(typeInfo, visitor) {
367 return {
368 enter: function enter(node) {
369 typeInfo.enter(node);
370 var fn = getVisitFn(visitor, node.kind,
371 /* isLeaving */
372 false);
373
374 if (fn) {
375 var result = fn.apply(visitor, arguments);
376
377 if (result !== undefined) {
378 typeInfo.leave(node);
379
380 if (isNode(result)) {
381 typeInfo.enter(result);
382 }
383 }
384
385 return result;
386 }
387 },
388 leave: function leave(node) {
389 var fn = getVisitFn(visitor, node.kind,
390 /* isLeaving */
391 true);
392 var result;
393
394 if (fn) {
395 result = fn.apply(visitor, arguments);
396 }
397
398 typeInfo.leave(node);
399 return result;
400 }
401 };
402}
403/**
404 * Given a visitor instance, if it is leaving or not, and a node kind, return
405 * the function the visitor runtime should call.
406 */
407
408
409function getVisitFn(visitor, kind, isLeaving) {
410 var kindVisitor = visitor[kind];
411
412 if (kindVisitor) {
413 if (!isLeaving && typeof kindVisitor === 'function') {
414 // { Kind() {} }
415 return kindVisitor;
416 }
417
418 var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter;
419
420 if (typeof kindSpecificVisitor === 'function') {
421 // { Kind: { enter() {}, leave() {} } }
422 return kindSpecificVisitor;
423 }
424 } else {
425 var specificVisitor = isLeaving ? visitor.leave : visitor.enter;
426
427 if (specificVisitor) {
428 if (typeof specificVisitor === 'function') {
429 // { enter() {}, leave() {} }
430 return specificVisitor;
431 }
432
433 var specificKindVisitor = specificVisitor[kind];
434
435 if (typeof specificKindVisitor === 'function') {
436 // { enter: { Kind() {} }, leave: { Kind() {} } }
437 return specificKindVisitor;
438 }
439 }
440 }
441}