UNPKG

@rickyli79/rich-json

Version:

Serialize and Deserialize javascript objects

95 lines (94 loc) 3.33 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.parse = void 0; const jsonpath_1 = __importDefault(require("jsonpath")); const lib_1 = require("./lib"); const refMap = new Map(); let buildinSerializers; function getRichlValue(value, nativeKeys) { return { type: value[nativeKeys.type], className: value[nativeKeys.className], content: value[nativeKeys.content], }; } function fromRich(value, root, nativeKeys) { if (!(0, lib_1.isNativeProperty)(value, nativeKeys)) return value; const { type, content, className } = getRichlValue(value, nativeKeys); switch (type) { case '$ref': { const contentStr = JSON.stringify(content); let refObj = refMap.get(contentStr); if (refObj === undefined) { const jp = [...content]; refObj = jsonpath_1.default.value(root, jsonpath_1.default.stringify(jp)); if (refObj === undefined) { refObj = root; jp.shift(); while (jp.length !== 0) { refObj = jsonpath_1.default.value(refObj, jsonpath_1.default.stringify(['$', jp.shift()])); if (refObj instanceof Map) { const v = jp.pop(); const k = jp.pop(); refObj = Array.from(refObj.entries())[k][v]; } else if (refObj instanceof Set) { const i = jp.pop(); refObj = Array.from(refObj)[i]; } } } refMap.set(contentStr, refObj); } return refObj; } break; case 'Class': { let converter = lib_1.customerSerializers.find(i => i.className === className); if (!converter) { converter = buildinSerializers.find(i => i.className === className); } if (converter) { return converter.fromContent(content); } } break; default: { const n = type; } break; } return value; } function parse(text) { buildinSerializers = (0, lib_1.getBuildinSerializers)(); try { if (text === undefined) return undefined; let wrap; let nativeKeys; refMap.clear(); const re = JSON.parse(text, function (key, value) { if (wrap === undefined) { wrap = this; nativeKeys = (0, lib_1.getNativeKeys)(wrap.SP, wrap.MARK); return value; } return fromRich(value, wrap.root, nativeKeys); }); if (typeof re !== 'object' || re === null) return re; return re.root; } finally { refMap.clear(); } } exports.parse = parse;