// Reference implementation for the typed-bracket path contract. // Usage: node flatten.js const fs = require('node:fs'); const assert = require('node:assert/strict'); const SAFE_KEY = /^[A-Za-z_][A-Za-z0-9_-]*$/; const MISSING = Symbol('missing array slot'); class PathContractError extends Error {} class DepthLimitError extends PathContractError {} class CircularReferenceError extends PathContractError {} class PathConflictError extends PathContractError {} function quotedKey(key) { return `[${JSON.stringify(key)}]`; } function renderPath(segments) { if (segments.length === 0) throw new PathContractError('cannot render an empty path'); let rendered = ''; for (const segment of segments) { if (segment.kind === 'index') { rendered += `[${segment.value}]`; continue; } if (SAFE_KEY.test(segment.value)) { rendered += rendered ? `.${segment.value}` : segment.value; } else { rendered += quotedKey(segment.value); } } return rendered; } function parseQuotedKey(path, bracketStart) { const quoteStart = bracketStart + 1; let quoteEnd = quoteStart + 1; let escaped = false; while (quoteEnd < path.length) { const char = path[quoteEnd]; if (escaped) { escaped = false; } else if (char === '\\') { escaped = true; } else if (char === '"') { break; } quoteEnd += 1; } if (quoteEnd >= path.length || path[quoteEnd + 1] !== ']') { throw new PathContractError(`unclosed quoted key in path ${JSON.stringify(path)}`); } let key; try { key = JSON.parse(path.slice(quoteStart, quoteEnd + 1)); } catch (error) { throw new PathContractError(`invalid quoted key in path ${JSON.stringify(path)}`, { cause: error }); } if (typeof key !== 'string') { throw new PathContractError(`quoted path segment must be a string in ${JSON.stringify(path)}`); } return { key, next: quoteEnd + 2 }; } function parsePath(path) { if (typeof path !== 'string' || path.length === 0) { throw new PathContractError('path must be a non-empty string'); } const segments = []; let index = 0; let allowBareKey = true; while (index < path.length) { const char = path[index]; if (char === '.') { if (allowBareKey) throw new PathContractError(`unexpected dot in path ${JSON.stringify(path)}`); allowBareKey = true; index += 1; if (index >= path.length) throw new PathContractError(`path cannot end with a dot: ${JSON.stringify(path)}`); continue; } if (char === '[') { if (path[index + 1] === '"') { const parsed = parseQuotedKey(path, index); segments.push({ kind: 'key', value: parsed.key }); index = parsed.next; } else { let end = index + 1; while (end < path.length && /\d/.test(path[end])) end += 1; const digits = path.slice(index + 1, end); if (!digits || path[end] !== ']') { throw new PathContractError(`invalid array index in path ${JSON.stringify(path)}`); } if (digits.length > 1 && digits.startsWith('0')) { throw new PathContractError(`array index cannot have leading zeros in path ${JSON.stringify(path)}`); } segments.push({ kind: 'index', value: Number(digits) }); index = end + 1; } allowBareKey = false; continue; } if (!allowBareKey) { throw new PathContractError(`missing dot before object key in path ${JSON.stringify(path)}`); } let end = index; while (end < path.length && path[end] !== '.' && path[end] !== '[') end += 1; const key = path.slice(index, end); if (!SAFE_KEY.test(key)) { throw new PathContractError(`object key must be quoted in path ${JSON.stringify(path)}: ${JSON.stringify(key)}`); } segments.push({ kind: 'key', value: key }); index = end; allowBareKey = false; } if (allowBareKey) throw new PathContractError(`path cannot end with a dot: ${JSON.stringify(path)}`); return segments; } function isPlainObject(value) { if (value === null || typeof value !== 'object' || Array.isArray(value)) return false; const prototype = Object.getPrototypeOf(value); return prototype === Object.prototype || prototype === null; } function isJsonScalar(value) { return value === null || typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value)); } function flatten(obj, { maxDepth = 32, preserveEmpty = true } = {}) { if (!isPlainObject(obj) && !Array.isArray(obj)) { throw new PathContractError('root value must be an object or an array'); } if (Object.keys(obj).length === 0) { throw new PathContractError('empty root containers cannot be represented without metadata'); } const result = {}; const activeContainers = new Set(); function walk(value, segments) { if (segments.length > maxDepth) throw new DepthLimitError(`path depth exceeds ${maxDepth}`); if (isPlainObject(value) || Array.isArray(value)) { if (activeContainers.has(value)) throw new CircularReferenceError('circular reference detected'); const entries = Array.isArray(value) ? value.map((child, childIndex) => [childIndex, child]) : Object.entries(value); if (entries.length === 0) { if (!preserveEmpty) return; if (segments.length === 0) { throw new PathContractError('empty root containers cannot be represented without metadata'); } result[renderPath(segments)] = structuredClone(value); return; } activeContainers.add(value); try { for (const [key, child] of entries) { const segment = Array.isArray(value) ? { kind: 'index', value: key } : { kind: 'key', value: key }; walk(child, [...segments, segment]); } } finally { activeContainers.delete(value); } return; } if (!isJsonScalar(value)) { throw new PathContractError(`non-JSON leaf type: ${Object.prototype.toString.call(value)}`); } if (segments.length === 0) throw new PathContractError('scalar root values cannot be represented as paths'); result[renderPath(segments)] = value; } walk(obj, []); return result; } function containerFor(segment) { return segment.kind === 'index' ? [] : {}; } function validateFlatValue(value) { if (isJsonScalar(value)) return; if ((isPlainObject(value) || Array.isArray(value)) && Object.keys(value).length === 0) return; throw new PathContractError('flat values must be JSON scalars or empty containers'); } function hasOwn(object, key) { return Object.prototype.hasOwnProperty.call(object, key); } function setOwn(object, key, value) { Object.defineProperty(object, key, { value, writable: true, enumerable: true, configurable: true, }); } function assertNoMissingSlots(value) { if (Array.isArray(value)) { for (const item of value) { if (item === MISSING) throw new PathConflictError('array paths cannot skip indexes'); assertNoMissingSlots(item); } } else if (isPlainObject(value)) { for (const item of Object.values(value)) assertNoMissingSlots(item); } } function setPath(root, segments, value) { let node = root; for (let position = 0; position < segments.length; position += 1) { const segment = segments[position]; const isLast = position === segments.length - 1; if (segment.kind === 'key') { if (!isPlainObject(node)) throw new PathConflictError('object key conflicts with an array or scalar path'); if (isLast) { if (hasOwn(node, segment.value)) throw new PathConflictError(`duplicate or conflicting path at ${segment.value}`); setOwn(node, segment.value, structuredClone(value)); return; } const nextSegment = segments[position + 1]; if (!hasOwn(node, segment.value)) setOwn(node, segment.value, containerFor(nextSegment)); const expectedArray = nextSegment.kind === 'index'; if (Array.isArray(node[segment.value]) !== expectedArray || (!expectedArray && !isPlainObject(node[segment.value]))) { throw new PathConflictError(`path conflict at object key ${segment.value}`); } node = node[segment.value]; continue; } if (!Array.isArray(node)) throw new PathConflictError('array index conflicts with an object or scalar path'); while (node.length <= segment.value) node.push(MISSING); if (isLast) { if (node[segment.value] !== MISSING) throw new PathConflictError(`duplicate or conflicting path at index ${segment.value}`); node[segment.value] = structuredClone(value); return; } const nextSegment = segments[position + 1]; if (node[segment.value] === MISSING) node[segment.value] = containerFor(nextSegment); const expectedArray = nextSegment.kind === 'index'; if (Array.isArray(node[segment.value]) !== expectedArray || (!expectedArray && !isPlainObject(node[segment.value]))) { throw new PathConflictError(`path conflict at array index ${segment.value}`); } node = node[segment.value]; } } function unflatten(flat, { maxDepth = 32 } = {}) { if (!isPlainObject(flat) || Object.keys(flat).length === 0) { throw new PathContractError('flat input must be a non-empty object'); } let root; for (const [path, value] of Object.entries(flat)) { const segments = parsePath(path); if (segments.length > maxDepth) throw new DepthLimitError(`path depth exceeds ${maxDepth}`); validateFlatValue(value); if (root === undefined) { root = segments[0].kind === 'index' ? [] : {}; } else if ((segments[0].kind === 'index') !== Array.isArray(root)) { throw new PathConflictError('root object and root array paths cannot be mixed'); } setPath(root, segments, value); } assertNoMissingSlots(root); return root; } if (require.main === module) { const nested = JSON.parse(fs.readFileSync('sample.json', 'utf8')); const flattened = flatten(nested); console.log('=== Flattened ==='); for (const [key, value] of Object.entries(flattened)) console.log(` ${key}: ${value}`); const restored = unflatten(flattened); console.log('\n=== Round-trip ==='); console.log(JSON.stringify(restored, null, 2)); assert.deepEqual(restored, nested); console.log('\nOK - lossless round-trip'); } module.exports = { flatten, unflatten, parsePath, renderPath, PathContractError, DepthLimitError, CircularReferenceError, PathConflictError, };