UNPKG

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