All files index.ts

92% Statements 161/175
85.31% Branches 122/143
100% Functions 10/10
91.86% Lines 158/172

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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344                                46x     46x     46x     1x 46x 46x 46x 46x   46x 28x     46x 8x     46x 131x 131x 129x     129x     109x 26x 26x 16x 16x       83x 26x 26x 19x 19x       57x           1x 1x   56x           1x 1x   55x           1x 1x   54x           1x 1x   53x             1x 1x   52x           1x 1x   51x     46x 56x 56x 56x 56x 148x 148x 46x 46x 46x         102x 1x   101x   102x     10x 7x   7x     1x 1x 1x 1x           3x     46x 26x 26x 26x 26x 26x 26x 48x 48x 12x       6x   6x     36x 36x 36x 2x   34x 34x   34x 34x 28x   6x       4x   2x   28x   28x 11x 11x   11x           10x     10x     6x 6x 6x                 46x 26x 26x 26x 26x 26x 67x 67x 16x       9x   7x     51x 46x 46x   46x 33x 33x   33x           12x 5x   7x   5x 5x 5x                 46x 51x     51x     51x 45x       51x 3x 3x 6x         51x 3x 3x 2x   3x 1x       51x   51x 51x   8x   8x 8x 2x 2x       6x       46x 489x 62x       46x 29x   29x       29x     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 string, got ${typeof jsonString}`);
  }
  Iif (!jsonString.trim()) {
    throw new Error(`Input is empty`);
  }
  return _parseJSON(jsonString.trim(), allowPartial);
}
 
const _parseJSON = (jsonString: string, allow: number) => {
  const length = jsonString.length;
  let index = 0;
  let objectDepth = 0; // Track the current depth of objects
  let arrayDepth = 0; // Track the current depth of arrays
 
  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");
    const currentChar = jsonString[index];
 
    // Handle string
    if (currentChar === '"') return parseStr();
 
    // Handle object
    if (currentChar === "{") {
      objectDepth++;
      const result = parseObj();
      objectDepth--;
      return result;
    }
 
    // Handle array
    if (currentChar === "[") {
      arrayDepth++;
      const result = parseArr();
      arrayDepth--;
      return result;
    }
 
    // Handle literals and numbers
    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) {
      const char = jsonString[index];
      if (char === '"' && !escape) {
        index++; // include the closing quote
        try {
          return JSON.parse(jsonString.substring(start, index));
        } catch (e) {
          throwMalformedError(`Invalid string: ${e}`);
        }
      }
      if (char === "\\" && !escape) {
        escape = true;
      } else {
        escape = false;
      }
      index++;
    }
    // If we reach here, the string was unterminated
    if (Allow.STR & allow) {
      try {
        // Attempt to close the string by adding the closing quote
        return JSON.parse(jsonString.substring(start, index) + '"');
      } catch (e) {
        // Attempt to recover by removing trailing backslashes
        const lastBackslash = jsonString.lastIndexOf("\\");
        Eif (lastBackslash > start) {
          try {
            return JSON.parse(jsonString.substring(start, lastBackslash) + '"');
          } catch (_) {}
        }
        throwMalformedError("Unterminated string literal");
      }
    }
    markPartialJSON("Unterminated string literal");
  };
 
  const parseObj = () => {
    const isOutermost = objectDepth === 1;
    index++; // skip initial brace
    skipBlank();
    const obj: Record<string, any> = {};
    try {
      while (jsonString[index] !== "}") {
        skipBlank();
        if (index >= length) {
          if (
            (isOutermost && allow & Allow.OUTERMOST_OBJ) ||
            allow & Allow.OBJ
          ) {
            return obj;
          }
          markPartialJSON("Unexpected end of object");
        }
        // Parse key
        const key = parseStr();
        skipBlank();
        if (jsonString[index] !== ":") {
          throwMalformedError(`Expected ':' after key "${key}"`);
        }
        index++; // skip colon
        skipBlank();
        // Parse value
        try {
          const value = parseAny();
          obj[key] = value;
        } catch (e) {
          if (
            (isOutermost && allow & Allow.OUTERMOST_OBJ) ||
            allow & Allow.OBJ
          ) {
            return obj;
          }
          throw e;
        }
        skipBlank();
        // Handle comma or end of object
        if (jsonString[index] === ",") {
          index++; // skip comma
          skipBlank();
          // If next character is '}', it's the end of the object
          Iif (jsonString[index] === "}") {
            break;
          }
        }
      }
    } catch (e) {
      Iif ((isOutermost && allow & Allow.OUTERMOST_OBJ) || allow & Allow.OBJ) {
        return obj;
      } else {
        markPartialJSON("Expected '}' at end of object");
      }
    }
    Eif (jsonString[index] === "}") {
      index++; // skip final brace
      return obj;
    }
    // If we reach here, the object was not properly closed
    if ((isOutermost && allow & Allow.OUTERMOST_OBJ) || allow & Allow.OBJ) {
      return obj;
    }
    markPartialJSON("Expected '}' at end of object");
  };
 
  const parseArr = () => {
    const isOutermost = arrayDepth === 1;
    index++; // skip initial bracket
    const arr: any[] = [];
    try {
      while (jsonString[index] !== "]") {
        skipBlank();
        if (index >= length) {
          if (
            (isOutermost && allow & Allow.OUTERMOST_ARR) ||
            allow & Allow.ARR
          ) {
            return arr;
          }
          markPartialJSON("Unexpected end of array");
        }
        // Parse value
        const value = parseAny();
        arr.push(value);
        skipBlank();
        // Handle comma or end of array
        if (jsonString[index] === ",") {
          index++; // skip comma
          skipBlank();
          // If next character is ']', it's the end of the array
          Iif (jsonString[index] === "]") {
            break;
          }
        }
      }
    } catch (e) {
      if ((isOutermost && allow & Allow.OUTERMOST_ARR) || allow & Allow.ARR) {
        return arr;
      }
      throw e;
    }
    Eif (jsonString[index] === "]") {
      index++; // skip final bracket
      return arr;
    }
    // If we reach here, the array was not properly closed
    if ((isOutermost && allow & Allow.OUTERMOST_ARR) || allow & Allow.ARR) {
      return arr;
    }
    markPartialJSON("Expected ']' at end of array");
  };
 
  const parseNum = () => {
    const start = index;
 
    // Handle negative sign
    if (jsonString[index] === "-") index++;
 
    // Integral part
    while (index < length && /[0-9]/.test(jsonString[index])) {
      index++;
    }
 
    // Fractional part
    if (jsonString[index] === ".") {
      index++;
      while (index < length && /[0-9]/.test(jsonString[index])) {
        index++;
      }
    }
 
    // Exponent part
    if (jsonString[index] === "e" || jsonString[index] === "E") {
      index++;
      if (jsonString[index] === "+" || jsonString[index] === "-") {
        index++;
      }
      while (index < length && /[0-9]/.test(jsonString[index])) {
        index++;
      }
    }
 
    const numStr = jsonString.substring(start, index);
 
    try {
      return JSON.parse(numStr);
    } catch (e) {
      Eif (Allow.NUM & allow) {
        // Attempt to parse the valid part of the number
        const validMatch = numStr.match(/^-?\d+(\.\d+)?([eE][+-]?\d+)?/);
        if (validMatch && validMatch[0]) {
          try {
            return JSON.parse(validMatch[0]);
          } catch (_) {}
        }
      }
      throwMalformedError(`Invalid number '${numStr}'`);
    }
  };
 
  const skipBlank = () => {
    while (index < length && " \n\r\t".includes(jsonString[index])) {
      index++;
    }
  };
 
  const result = parseAny();
  skipBlank();
 
  Iif (index < length) {
    throwMalformedError(`Unexpected token '${jsonString[index]}'`);
  }
 
  return result;
};
 
const parse = parseJSON;
 
export { parse, parseJSON, PartialJSON, MalformedJSON, Allow };