All files index.ts

81.51% Statements 97/119
72.05% Branches 49/68
94.11% Functions 16/17
85.29% Lines 87/102

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 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211              1x                 1x                     33x     33x     33x       33x     33x 33x       50x 50x 42x 30x 22x 16x 16x 10x       16x 15x 15x 75x 6x 6x     9x       22x 22x 22x 22x 9x 9x       13x 10x 10x     4x     3x       22x 22x 5x 5x   22x       8x 8x 8x 8x 8x 11x 3x 3x     6x 6x             11x 11x 10x 7x 7x 7x 7x   4x 3x   3x       6x 6x 6x 6x 10x 4x 4x 1x       6x 2x   4x             10x       10x 10x 10x   8x 8x 8x     6x                                   8x 8x   6x         83x 2x         21x       12x       33x   1x      
import { Allow } from "./options";
export * from "./options";
 
class PartialJSON extends Error {}
 
class MalformedJSON extends Error {}
 
const literals = [
    ["null", Allow.NULL, null, 1],
    ["true", Allow.BOOL, true, 1],
    ["false", Allow.BOOL, false, 1],
    ["Infinity", Allow.INFINITY, Infinity, 1],
    ["-Infinity", Allow._INFINITY, -Infinity, 2],
    ["NaN", Allow.NAN, NaN, 1],
] as const;
 
const notLiteral = Symbol("notLiteral");
 
/**
 * 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);
}
 
class Parser {
    private index = 0;
 
    constructor(
        private jsonString: string,
        private allow: number,
    ) {}
 
    parseAny(): any {
        this.skipBlank();
        if (this.index >= this.jsonString.length) this.markPartialJSON("Unexpected end of input");
        if (this.jsonString[this.index] === '"') return this.parseStr();
        if (this.jsonString[this.index] === "{") return this.parseObj();
        if (this.jsonString[this.index] === "[") return this.parseArr();
        const literal = this.parseLiteral();
        if (literal !== notLiteral) return literal;
        return this.parseNum();
    }
 
    private parseLiteral() {
        if (!"ntfI-N".includes(this.jsonString[this.index])) return notLiteral;
        const rest = this.jsonString.substring(this.index);
        for (const [text, flag, value, minLength] of literals) {
            if (rest.substring(0, text.length) === text || (flag & this.allow && rest.length < text.length && rest.length >= minLength && text.startsWith(rest))) {
                this.index += text.length;
                return value;
            }
        }
        return notLiteral;
    }
 
    private parseStr(): string {
        const start = this.index;
        this.index++; // skip initial quote
        const escape = this.scanString();
        if (this.jsonString.charAt(this.index) == '"') {
            try {
                return JSON.parse(this.jsonString.substring(start, ++this.index - Number(escape)));
            } catch (e) {
                this.throwMalformedError(String(e));
            }
        } else if (Allow.STR & this.allow) {
            try {
                return JSON.parse(this.jsonString.substring(start, this.index - Number(escape)) + '"');
            } catch (e) {
                // SyntaxError: Invalid escape sequence
                return JSON.parse(this.jsonString.substring(start, this.jsonString.lastIndexOf("\\")) + '"');
            }
        }
        this.markPartialJSON("Unterminated string literal");
    }
 
    private scanString() {
        let escape = false;
        while (this.index < this.jsonString.length && (this.jsonString[this.index] !== '"' || (escape && this.jsonString[this.index - 1] === "\\"))) {
            escape = this.jsonString[this.index] === "\\" ? !escape : false;
            this.index++;
        }
        return escape;
    }
 
    private parseObj() {
        this.index++; // skip initial brace
        this.skipBlank();
        const obj: Record<string, any> = {};
        try {
            while (this.jsonString[this.index] !== "}") {
                if (this.parseObjEntry(obj)) return obj;
                this.skipBlank();
                Iif (this.jsonString[this.index] === ",") this.index++; // skip comma
            }
        } catch (e) {
            Iif (Allow.OBJ & this.allow) return obj;
            else this.markPartialJSON("Expected '}' at end of object");
        }
        this.index++; // skip final brace
        return obj;
    }
 
    private parseObjEntry(obj: Record<string, any>) {
        this.skipBlank();
        if (this.index >= this.jsonString.length && Allow.OBJ & this.allow) return true;
        const key = this.parseStr();
        this.skipBlank();
        this.index++; // skip colon
        try {
            obj[key] = this.parseAny();
        } catch (e) {
            if (Allow.OBJ & this.allow) return true;
            else throw e;
        }
        return false;
    }
 
    private parseArr() {
        this.index++; // skip initial bracket
        const arr = [];
        try {
            while (this.jsonString[this.index] !== "]") {
                arr.push(this.parseAny());
                this.skipBlank();
                if (this.jsonString[this.index] === ",") {
                    this.index++; // skip comma
                }
            }
        } catch (e) {
            if (Allow.ARR & this.allow) {
                return arr;
            }
            this.markPartialJSON("Expected ']' at end of array");
        }
        this.index++; // skip final bracket
        return arr;
    }
 
    private parseNum() {
        return this.index === 0 ? this.parseRootNum() : this.parseNestedNum();
    }
 
    private parseRootNum() {
        Iif (this.jsonString === "-") this.throwMalformedError("Not sure what '-' is");
        try {
            return JSON.parse(this.jsonString);
        } catch (e) {
            Eif (Allow.NUM & this.allow) {
                try {
                    return this.parseNumBeforeExponent(0);
                } catch (e) {}
            }
            this.throwMalformedError(String(e));
        }
    }
 
    private parseNestedNum() {
        const start = this.index;
        if (this.jsonString[this.index] === "-") this.index++;
        while (this.jsonString[this.index] && ",]}".indexOf(this.jsonString[this.index]) === -1) this.index++;
        if (this.index == this.jsonString.length && !(Allow.NUM & this.allow)) this.markPartialJSON("Unterminated number literal");
        try {
            return JSON.parse(this.jsonString.substring(start, this.index));
        } catch (e) {
            if (this.jsonString.substring(start, this.index) === "-") this.markPartialJSON("Not sure what '-' is");
            return this.parseNumBeforeExponent(start);
        }
    }
 
    private parseNumBeforeExponent(start: number) {
        try {
            return JSON.parse(this.jsonString.substring(start, this.jsonString.lastIndexOf("e")));
        } catch (e) {
            this.throwMalformedError(String(e));
        }
    }
 
    private skipBlank() {
        while (this.index < this.jsonString.length && " \n\r\t".includes(this.jsonString[this.index])) {
            this.index++;
        }
    }
 
    private markPartialJSON(msg: string): never {
        throw new PartialJSON(`${msg} at position ${this.index}`);
    }
 
    private throwMalformedError(msg: string): never {
        throw new MalformedJSON(`${msg} at position ${this.index}`);
    }
}
 
const _parseJSON = (jsonString: string, allow: number) => new Parser(jsonString, allow).parseAny();
 
const parse = parseJSON;
 
export { parse, parseJSON, PartialJSON, MalformedJSON, Allow };