All files index.ts

80.95% Statements 102/126
79.34% Branches 73/92
100% Functions 10/10
84.95% Lines 96/113

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190                                33x     33x     33x     1x 33x 33x   33x 21x     33x 6x     33x 50x 50x 42x 30x 22x 16x 1x 1x   15x 1x 1x   14x 1x 1x   13x 1x 1x   12x 1x 1x   11x 1x 1x   10x     33x 22x 22x 22x 22x 5x 5x   22x 9x 9x       13x 10x 10x     4x     3x     33x 8x 8x 8x 8x 8x 11x 11x 10x 7x 7x 7x 7x 3x   4x 3x   3x 3x     6x 6x           33x 6x 6x 6x 6x 10x 4x 4x 1x       6x 2x   4x           33x 10x 10x 10x 10x   8x 8x 8x   6x                                             33x 83x 2x     33x     1x      
import { Allow } from "./options";
export * from "./options";
 
class PartialJSON extends Error {}
 
class MalformedJSON extends Error {}
 
/**
 * Parse incomplete JSON
 * @param {string} jsonString Partial JSON to be parsed
 * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details
 * @returns The parsed JSON
 * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter)
 * @throws {MalformedJSON} If the JSON is malformed
 */
function parseJSON(jsonString: string, allowPartial: number = Allow.ALL): any {
    Iif (typeof jsonString !== "string") {
        throw new TypeError(`expecting str, got ${typeof jsonString}`);
    }
    Iif (!jsonString.trim()) {
        throw new Error(`${jsonString} is empty`);
    }
    return _parseJSON(jsonString.trim(), allowPartial);
}
 
const _parseJSON = (jsonString: string, allow: number) => {
    const length = jsonString.length;
    let index = 0;
 
    const markPartialJSON = (msg: string) => {
        throw new PartialJSON(`${msg} at position ${index}`);
    };
 
    const throwMalformedError = (msg: string) => {
        throw new MalformedJSON(`${msg} at position ${index}`);
    };
 
    const parseAny: () => any = () => {
        skipBlank();
        if (index >= length) markPartialJSON("Unexpected end of input");
        if (jsonString[index] === '"') return parseStr();
        if (jsonString[index] === "{") return parseObj();
        if (jsonString[index] === "[") return parseArr();
        if (jsonString.substring(index, index + 4) === "null" || (Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index)))) {
            index += 4;
            return null;
        }
        if (jsonString.substring(index, index + 4) === "true" || (Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index)))) {
            index += 4;
            return true;
        }
        if (jsonString.substring(index, index + 5) === "false" || (Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index)))) {
            index += 5;
            return false;
        }
        if (jsonString.substring(index, index + 8) === "Infinity" || (Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index)))) {
            index += 8;
            return Infinity;
        }
        if (jsonString.substring(index, index + 9) === "-Infinity" || (Allow._INFINITY & allow && 1 < length - index && length - index < 9 && "-Infinity".startsWith(jsonString.substring(index)))) {
            index += 9;
            return -Infinity;
        }
        if (jsonString.substring(index, index + 3) === "NaN" || (Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index)))) {
            index += 3;
            return NaN;
        }
        return parseNum();
    };
 
    const parseStr: () => string = () => {
        const start = index;
        let escape = false;
        index++; // skip initial quote
        while (index < length && (jsonString[index] !== '"' || (escape && jsonString[index - 1] === "\\"))) {
            escape = jsonString[index] === "\\" ? !escape : false;
            index++;
        }
        if (jsonString.charAt(index) == '"') {
            try {
                return JSON.parse(jsonString.substring(start, ++index - Number(escape)));
            } catch (e) {
                throwMalformedError(String(e));
            }
        } else if (Allow.STR & allow) {
            try {
                return JSON.parse(jsonString.substring(start, index - Number(escape)) + '"');
            } catch (e) {
                // SyntaxError: Invalid escape sequence
                return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"');
            }
        }
        markPartialJSON("Unterminated string literal");
    };
 
    const parseObj = () => {
        index++; // skip initial brace
        skipBlank();
        const obj: Record<string, any> = {};
        try {
            while (jsonString[index] !== "}") {
                skipBlank();
                if (index >= length && Allow.OBJ & allow) return obj;
                const key = parseStr();
                skipBlank();
                index++; // skip colon
                try {
                    const value = parseAny();
                    obj[key] = value;
                } catch (e) {
                    if (Allow.OBJ & allow) return obj;
                    else throw e;
                }
                skipBlank();
                Iif (jsonString[index] === ",") index++; // skip comma
            }
        } catch (e) {
            Iif (Allow.OBJ & allow) return obj;
            else markPartialJSON("Expected '}' at end of object");
        }
        index++; // skip final brace
        return obj;
    };
 
    const parseArr = () => {
        index++; // skip initial bracket
        const arr = [];
        try {
            while (jsonString[index] !== "]") {
                arr.push(parseAny());
                skipBlank();
                if (jsonString[index] === ",") {
                    index++; // skip comma
                }
            }
        } catch (e) {
            if (Allow.ARR & allow) {
                return arr;
            }
            markPartialJSON("Expected ']' at end of array");
        }
        index++; // skip final bracket
        return arr;
    };
 
    const parseNum = () => {
        Eif (index === 0) {
            Iif (jsonString === "-") throwMalformedError("Not sure what '-' is");
            try {
                return JSON.parse(jsonString);
            } catch (e) {
                Eif (Allow.NUM & allow)
                    try {
                        return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e")));
                    } catch (e) {}
                throwMalformedError(String(e));
            }
        }
 
        const start = index;
 
        if (jsonString[index] === "-") index++;
        while (jsonString[index] && ",]}".indexOf(jsonString[index]) === -1) index++;
 
        if (index == length && !(Allow.NUM & allow)) markPartialJSON("Unterminated number literal");
 
        try {
            return JSON.parse(jsonString.substring(start, index));
        } catch (e) {
            if (jsonString.substring(start, index) === "-") markPartialJSON("Not sure what '-' is");
            try {
                return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e")));
            } catch (e) {
                throwMalformedError(String(e));
            }
        }
    };
 
    const skipBlank = () => {
        while (index < length && " \n\r\t".includes(jsonString[index])) {
            index++;
        }
    };
    return parseAny();
};
 
const parse = parseJSON;
 
export { parse, parseJSON, PartialJSON, MalformedJSON, Allow };