"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseLiteral = exports.parseObject = exports.ensureObject = exports.identity = void 0;
const graphql_1 = require("graphql");
const error_js_1 = require("../../error.js");
function identity(value) {
    return value;
}
exports.identity = identity;
// eslint-disable-next-line @typescript-eslint/ban-types
function ensureObject(value, ast) {
    if (typeof value !== 'object' || value === null || Array.isArray(value)) {
        throw (0, error_js_1.createGraphQLError)(`JSONObject cannot represent non-object value: ${value}`, ast
            ? {
                nodes: ast,
            }
            : undefined);
    }
    return value;
}
exports.ensureObject = ensureObject;
function parseObject(ast, variables) {
    const value = Object.create(null);
    ast.fields.forEach(field => {
        // eslint-disable-next-line no-use-before-define
        value[field.name.value] = parseLiteral(field.value, variables);
    });
    return value;
}
exports.parseObject = parseObject;
function parseLiteral(ast, variables) {
    switch (ast.kind) {
        case graphql_1.Kind.STRING:
        case graphql_1.Kind.BOOLEAN:
            return ast.value;
        case graphql_1.Kind.INT:
        case graphql_1.Kind.FLOAT:
            return parseFloat(ast.value);
        case graphql_1.Kind.OBJECT:
            return parseObject(ast, variables);
        case graphql_1.Kind.LIST:
            return ast.values.map(n => parseLiteral(n, variables));
        case graphql_1.Kind.NULL:
            return null;
        case graphql_1.Kind.VARIABLE: {
            const name = ast.name.value;
            return variables ? variables[name] : undefined;
        }
    }
}
exports.parseLiteral = parseLiteral;
