import { createHash } from 'node:crypto'; import canonicalize from 'canonicalize'; import { parseTree } from 'jsonc-parser'; function validateValue(value) { if (typeof value === 'number' && !Number.isFinite(value)) throw new Error('non-finite JSON number'); if (typeof value === 'string') { for (let i = 0; i < value.length; i++) { const code = value.charCodeAt(i); if (code >= 0xd800 && code <= 0xdbff) { const next = value.charCodeAt(++i); if (!(next >= 0xdc00 && next <= 0xdfff)) throw new Error('lone JSON surrogate'); } else if (code >= 0xdc00 && code <= 0xdfff) throw new Error('lone JSON surrogate'); } } else if (Array.isArray(value)) { for (const item of value) validateValue(item); } else if (value && typeof value === 'object') { for (const [key, item] of Object.entries(value)) { validateValue(key); validateValue(item); } } } export function canonicalBytes(value) { validateValue(value); const json = canonicalize(value); if (typeof json !== 'string') throw new Error('value is not JSON'); return Buffer.from(json, 'utf8'); } export function parseJson(bytes) { if (!Buffer.isBuffer(bytes)) throw new TypeError('JSON input must be a Buffer'); const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); const errors = []; const tree = parseTree(text, errors, { allowTrailingComma: false, disallowComments: true }); if (errors.length || !tree) throw new Error('invalid JSON syntax'); function visit(node) { if (node.type === 'object') { const seen = new Set(); for (const property of node.children ?? []) { const key = property.children?.[0]?.value; if (seen.has(key)) throw new Error('duplicate JSON key'); seen.add(key); visit(property.children[1]); } } else for (const child of node.children ?? []) visit(child); } visit(tree); const value = JSON.parse(text); validateValue(value); return value; } export function sha256(bytes) { return createHash('sha256').update(bytes).digest('hex'); }