@gleif-it/did-webs-ts
Version:
did-webs typescript library
85 lines (84 loc) • 3.26 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseKeyEventStream = exports._fancyPrintEvents = void 0;
const Event_js_1 = require("../../core/Event.js");
const isValidEvent = (obj) => Event_js_1.EventSchema.safeParse(obj).success;
const extractNextEventBlock = (str, startIndex) => {
const firstBrace = str.indexOf('{', startIndex);
if (firstBrace === -1)
return null;
const traverse = (index, braceCount, inString, escape) => {
if (index >= str.length)
return index;
const char = str[index];
return inString
? escape
? traverse(index + 1, braceCount, inString, false)
: char === '\\'
? traverse(index + 1, braceCount, inString, true)
: char === '"'
? traverse(index + 1, braceCount, false, false)
: traverse(index + 1, braceCount, inString, false)
: char === '"'
? traverse(index + 1, braceCount, true, false)
: char === '{'
? traverse(index + 1, braceCount + 1, inString, false)
: char === '}'
? braceCount - 1 === 0
? index
: traverse(index + 1, braceCount - 1, inString, false)
: traverse(index + 1, braceCount, inString, false);
};
const endIndex = traverse(firstBrace, 0, false, false);
const block = str.substring(firstBrace, endIndex + 1);
return { block, nextIndex: endIndex + 1 };
};
const getEventBlocks = (str, startIndex = 0) => {
const blockInfo = extractNextEventBlock(str, startIndex);
return !blockInfo
? []
: [blockInfo.block, ...getEventBlocks(str, blockInfo.nextIndex)];
};
// custom print function for events in a list
const _fancyPrintEvents = (events, depth = 0) => {
const indent = (level) => ' '.repeat(level * 2);
const printObject = (obj, currentDepth) => {
if (obj === null || typeof obj !== 'object') {
return String(obj);
}
if (Array.isArray(obj)) {
return ('[\n' +
obj
.map((item) => indent(currentDepth + 1) + printObject(item, currentDepth + 1))
.join(',\n') +
'\n' +
indent(currentDepth) +
']');
}
const entries = Object.entries(obj);
return ('{\n' +
entries
.map(([key, value]) => indent(currentDepth + 1) +
key +
': ' +
printObject(value, currentDepth + 1))
.join(',\n') +
'\n' +
indent(currentDepth) +
'}');
};
console.log(printObject(events, depth));
};
exports._fancyPrintEvents = _fancyPrintEvents;
const parseKeyEventStream = (cesr) => getEventBlocks(cesr)
.map((block) => {
try {
return JSON.parse(block);
}
catch (error) {
console.error('Error parsing JSON:', error);
return null;
}
})
.filter((event) => event !== null && isValidEvent(event));
exports.parseKeyEventStream = parseKeyEventStream;