Tools for generating human-readable diagnostic output and commented CBOR format for debugging, analysis, and understanding CBOR data structures.
Generate diagnostic format string from CBOR data for human-readable analysis of CBOR structure and content.
/**
* Generate diagnostic format string from CBOR data
* @param {BufferLike} input - CBOR data to analyze
* @param {DiagnoseOptions|diagnoseCallback} [options] - Options or callback
* @param {diagnoseCallback} [cb] - Callback function
* @returns {Promise<string>|void} Diagnostic string or void if callback provided
*/
function diagnose(input, options, cb);Usage Examples:
const cbor = require("cbor");
// Basic diagnostic output
const data = { name: "Alice", age: 30, scores: [95, 87, 92] };
const encoded = cbor.encode(data);
// Synchronous diagnostic
const diagnostic = await cbor.diagnose(encoded);
console.log(diagnostic);
// Output: {"name": "Alice", "age": 30, "scores": [95, 87, 92]}
// Async diagnostic with callback
cbor.diagnose(encoded, (err, result) => {
if (err) {
console.error('Diagnostic failed:', err);
} else {
console.log('CBOR diagnostic:', result);
}
});
// Diagnostic with options
const diagnosticWithOptions = await cbor.diagnose(encoded, {
float_bytes: 4,
separator: '\n',
max_depth: 10
});
// Complex data structures
const complexData = {
timestamp: new Date(),
bignum: 123456789012345678901234567890n,
regex: /pattern/gi,
map: new Map([["key1", "value1"], ["key2", "value2"]]),
set: new Set([1, 2, 3]),
tagged: new cbor.Tagged(100, "custom data")
};
const complexEncoded = cbor.encode(complexData);
const complexDiagnostic = await cbor.diagnose(complexEncoded);
console.log(complexDiagnostic);
// Shows CBOR structure with tags, types, and semantic informationGenerate commented CBOR format for detailed debugging and educational purposes.
/**
* Generate commented CBOR format for debugging
* @param {BufferLike} input - CBOR data to comment
* @param {CommentOptions|commentCallback} [options] - Options or callback
* @param {commentCallback} [cb] - Callback function
* @returns {Promise<string>|void} Commented format or void if callback provided
*/
function comment(input, options, cb);Usage Examples:
const cbor = require("cbor");
// Basic commented output
const data = { name: "Bob", active: true, count: 42 };
const encoded = cbor.encode(data);
// Generate commented format
const commented = await cbor.comment(encoded);
console.log(commented);
// Output shows byte-level breakdown with comments:
// a3 # map(3)
// 64 # text(4)
// 6e616d65 # "name"
// 63 # text(3)
// 426f62 # "Bob"
// 66 # text(6)
// 616374697665 # "active"
// f5 # primitive(21)
// 65 # text(5)
// 636f756e74 # "count"
// 182a # unsigned(42)
// Async commented format with callback
cbor.comment(encoded, { max_depth: 5 }, (err, result) => {
if (err) {
console.error('Comment generation failed:', err);
} else {
console.log('Commented CBOR:\n', result);
}
});
// Array data
const arrayData = [1, "two", true, null, undefined];
const arrayEncoded = cbor.encode(arrayData);
const arrayCommented = await cbor.comment(arrayEncoded);
console.log(arrayCommented);
// Shows array structure with item comments
// Complex nested structures
const nestedData = {
users: [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
],
metadata: {
version: "1.0",
created: new Date("2023-01-01")
}
};
const nestedEncoded = cbor.encode(nestedData);
const nestedCommented = await cbor.comment(nestedEncoded);
console.log(nestedCommented);
// Detailed breakdown of nested structureStream-based diagnostic generation for processing large CBOR data.
/**
* Stream-based diagnostic generator
*/
class Diagnose extends Transform {
/**
* Create diagnostic stream
* @param {DiagnoseOptions} [options] - Diagnostic options
*/
constructor(options);
/**
* Float byte precision for display
* @type {number}
*/
float_bytes;
/**
* Object separator character
* @type {string}
*/
separator;
/**
* Include errors in stream output
* @type {boolean}
*/
stream_errors;
/**
* Internal decoder for parsing
* @type {Decoder}
*/
parser;
}Usage Examples:
const cbor = require("cbor");
const fs = require("fs");
// Stream diagnostic processing
const diagnoseStream = new cbor.Diagnose({
float_bytes: 8,
separator: '\n',
stream_errors: true
});
// Process large CBOR file
fs.createReadStream('large-data.cbor')
.pipe(diagnoseStream)
.pipe(fs.createWriteStream('diagnostic-output.txt'));
// Handle diagnostic stream events
diagnoseStream.on('data', (chunk) => {
console.log('Diagnostic chunk:', chunk.toString());
});
diagnoseStream.on('error', (err) => {
console.error('Diagnostic stream error:', err);
});
// Manual diagnostic streaming
const manualDiagnose = new cbor.Diagnose();
manualDiagnose.on('data', (diagnostic) => {
process.stdout.write(diagnostic);
});
const testData = cbor.encode({ test: "streaming diagnostic" });
manualDiagnose.write(testData);
manualDiagnose.end();Stream-based commented format generation for large CBOR data analysis.
/**
* Stream-based commented format generator
*/
class Commented extends Transform {
/**
* Create commenting stream
* @param {CommentOptions} [options] - Comment options
*/
constructor(options);
/**
* Current indentation depth
* @type {number}
*/
depth;
/**
* Maximum depth to process
* @type {number}
*/
max_depth;
/**
* All input bytes accumulator
* @type {NoFilter}
*/
all;
/**
* Internal decoder for parsing
* @type {Decoder}
*/
parser;
}Usage Examples:
const cbor = require("cbor");
const fs = require("fs");
// Stream commented processing
const commentStream = new cbor.Commented({
max_depth: 64
});
// Process and comment CBOR file
fs.createReadStream('data.cbor')
.pipe(commentStream)
.pipe(fs.createWriteStream('commented-output.txt'));
// Real-time commenting
commentStream.on('data', (chunk) => {
console.log('Comment chunk:\n', chunk.toString());
});
// Comment multiple items
const multiCommentStream = new cbor.Commented();
multiCommentStream.on('data', (comments) => {
console.log('--- CBOR Comments ---');
console.log(comments.toString());
console.log('--- End Comments ---\n');
});
// Write multiple CBOR items
const items = [
{ id: 1, name: "Item 1" },
{ id: 2, name: "Item 2" },
[1, 2, 3, 4, 5]
];
items.forEach(item => {
const encoded = cbor.encode(item);
multiCommentStream.write(encoded);
});
multiCommentStream.end();Advanced techniques for debugging complex CBOR structures and identifying issues.
Usage Examples:
const cbor = require("cbor");
// Debug tagged values
const taggedData = new cbor.Tagged(999, { custom: "data", values: [1, 2, 3] });
const taggedEncoded = cbor.encode(taggedData);
const taggedDiagnostic = await cbor.diagnose(taggedEncoded);
console.log('Tagged diagnostic:', taggedDiagnostic);
// Shows: 999({"custom": "data", "values": [1, 2, 3]})
const taggedCommented = await cbor.comment(taggedEncoded);
console.log('Tagged commented:\n', taggedCommented);
// Shows byte-level breakdown with tag information
// Debug indefinite-length structures
const indefiniteMap = new Map();
indefiniteMap.set("key1", "value1");
indefiniteMap.set("key2", "value2");
const indefiniteEncoded = cbor.encode(indefiniteMap);
const indefiniteDiagnostic = await cbor.diagnose(indefiniteEncoded);
console.log('Map diagnostic:', indefiniteDiagnostic);
// Debug binary data
const binaryData = {
buffer: Buffer.from("Hello World"),
uint8: new Uint8Array([1, 2, 3, 4, 5]),
base64: new cbor.Tagged(34, "SGVsbG8=")
};
const binaryEncoded = cbor.encode(binaryData);
const binaryCommented = await cbor.comment(binaryEncoded);
console.log('Binary data commented:\n', binaryCommented);
// Debug error conditions
async function debugErrorConditions() {
try {
// Truncated CBOR data
const truncated = Buffer.from([0xa1, 0x61]); // Incomplete map
await cbor.diagnose(truncated);
} catch (error) {
console.log('Truncated data error:', error.message);
}
try {
// Invalid CBOR data
const invalid = Buffer.from([0xff, 0xff, 0xff]);
await cbor.comment(invalid);
} catch (error) {
console.log('Invalid data error:', error.message);
}
}
// Compare different encodings
function compareEncodings(data) {
const normal = cbor.encode(data);
const canonical = cbor.encodeCanonical(data);
console.log('Normal encoding diagnostic:');
cbor.diagnose(normal).then(console.log);
console.log('Canonical encoding diagnostic:');
cbor.diagnose(canonical).then(console.log);
console.log('Differences in commented format:');
Promise.all([
cbor.comment(normal),
cbor.comment(canonical)
]).then(([normalCommented, canonicalCommented]) => {
console.log('Normal:\n', normalCommented);
console.log('Canonical:\n', canonicalCommented);
});
}
compareEncodings({ z: 1, a: 2, m: 3 });Diagnostic tools are particularly useful for: