UNPKG

cbon

Version:
98 lines (97 loc) 3.38 kB
export const DefaultFormat = { string: "'", splitter: null, comma: false, comma_when_only_one_line: true, split_before_brackets: false, strict_string: false, strict_key: false, tab: ' ', tab_count: 2 }; export const MinFormat = { ...DefaultFormat, comma_when_only_one_line: false, }; export const JsonFormat = { ...DefaultFormat, string: '"', splitter: ':', comma: true, split_before_brackets: true, strict_string: true, strict_key: true, }; export function styleFormat(style) { return style === 'min' ? MinFormat : DefaultFormat; } export function stringify(val, config) { var _a, _b, _c, _d; const style = (_b = (_a = config) === null || _a === void 0 ? void 0 : _a.style, (_b !== null && _b !== void 0 ? _b : null)); const format = { ...styleFormat(style), ...(_d = (_c = config) === null || _c === void 0 ? void 0 : _c.format, (_d !== null && _d !== void 0 ? _d : {})) }; const obj_ref_pool = new Set(); return _stringify(val, style === 'beautify', format, obj_ref_pool); } const reg_quote_s = /'/ug; const reg_quote_d = /d/ug; const reg_not_word = /["'\s]|true|false|null/u; const reg_first_num = /[\d\-\+]/u; function is_word(val) { return is_key(val) && !reg_first_num.test(val[0]); } function is_key(val) { return val.length > 0 && !reg_not_word.test(val); } function _stringify(val, beautify, format, obj_ref_pool) { var _a; //todo beautify const { string, comma, splitter } = format; if (typeof val === 'string') { if (is_word(val)) return val; const nv = val.replace(string === '"' ? reg_quote_d : reg_quote_s, `\\${string}`); return `${string}${nv}${string}`; } else if (typeof val === 'number' || typeof val === 'bigint' || typeof val === 'boolean') { return `${val}`; } else if (val == null) return `null`; else if (typeof val === 'object') { if (obj_ref_pool.has(val)) { throw TypeError('Converting circular structure to CBON'); } obj_ref_pool.add(val); const getfn = (_a = val['toCBON'], (_a !== null && _a !== void 0 ? _a : val['toJSON'])); if (typeof getfn === 'function') return getfn(); if (val instanceof Array) { const outmap = val.map(v => { const r = _stringify(v, beautify, format, obj_ref_pool); if (r === undefined) return `null`; else return r; }); const str = outmap.join(comma ? ',' : ' '); obj_ref_pool.delete(val); return `[${str}]`; } else { const kvs = []; for (const k in val) { const v = val[k]; const r = _stringify(v, beautify, format, obj_ref_pool); if (r !== undefined) { kvs.push([is_key(k) ? k : `${string}${k}${string}`, r]); } } const str = kvs.map(kv => kv.join((splitter !== null && splitter !== void 0 ? splitter : ' '))).join(comma ? ',' : ' '); obj_ref_pool.delete(val); return `{${str}}`; } } else { return void 0; } }