@graphql-eslint/eslint-plugin
Version:
GraphQL plugin for ESLint
68 lines (64 loc) • 2.89 kB
JavaScript
;Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
var _graphql = require('graphql');
function checkDepthLimit(document, options) {
const fragments = getDefinitionsByName(
document.definitions,
_graphql.Kind.FRAGMENT_DEFINITION
);
const operations = getDefinitionsByName(
document.definitions,
_graphql.Kind.OPERATION_DEFINITION
);
for (const [operationName, operation] of Object.entries(operations)) {
determineDepth(operation, fragments, 0, operationName, options);
}
}
function getDefinitionsByName(definitions, kind) {
const map = {};
for (const definition of definitions) {
if (definition.kind === kind) {
map[_nullishCoalesce(_optionalChain([definition, 'access', _ => _.name, 'optionalAccess', _2 => _2.value]), () => ( ""))] = definition;
}
}
return map;
}
function determineDepth(node, fragments, depthSoFar, operationName, options) {
if (depthSoFar > options.maxDepth) {
options.onDepthExceeded(node, operationName);
return depthSoFar;
}
switch (node.kind) {
case _graphql.Kind.FIELD: {
const shouldIgnore = node.name.value.startsWith("__") || isIgnored(node.name.value, options.ignore);
if (shouldIgnore || !node.selectionSet) {
return 0;
}
return 1 + Math.max(
...node.selectionSet.selections.map(
(selection) => determineDepth(selection, fragments, depthSoFar + 1, operationName, options)
)
);
}
case _graphql.Kind.FRAGMENT_SPREAD: {
const fragment = fragments[node.name.value];
if (!fragment) {
throw new Error(`Unknown fragment "${node.name.value}"`);
}
return determineDepth(fragment, fragments, depthSoFar, operationName, options);
}
case _graphql.Kind.INLINE_FRAGMENT:
case _graphql.Kind.FRAGMENT_DEFINITION:
case _graphql.Kind.OPERATION_DEFINITION:
return Math.max(
...node.selectionSet.selections.map(
(selection) => determineDepth(selection, fragments, depthSoFar, operationName, options)
)
);
}
}
function isIgnored(fieldName, ignore) {
return ignore.some(
(rule) => typeof rule === "function" ? rule(fieldName) : fieldName.match(rule)
);
}
exports.checkDepthLimit = checkDepthLimit;