Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 28 additions & 8 deletions src/transforms/uslm-to-ir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ const HIERARCHY_TAGS = ['subtitle', 'part', 'subpart', 'chapter', 'subchapter']
const SECTION_BODY_TAGS = ['subsection', 'paragraph', 'subparagraph', 'clause', 'subclause', 'item', 'subitem'] as const;
const NOTE_SCOPE_TAGS = new Set(['note', 'notes']);
const BLOCK_NOTE_TAGS = new Set(['p', 'section', 'table']);
// Both parsers see the same <section> elements but walk them in different orders (the non-ordered tree
// groups children by tag, so a chapter's <subchapter> children are visited before its direct <section>
// children). Each <section> start tag is stamped with its document position so the two views can be
// paired by identity rather than by list index.
const SECTION_SEQUENCE_ATTRIBUTE = 'data-us-code-tools-section-seq';
const SECTION_SEQUENCE_KEY = `@_${SECTION_SEQUENCE_ATTRIBUTE}`;

const parser = new XMLParser({
ignoreAttributes: false,
Expand Down Expand Up @@ -91,7 +97,7 @@ interface XmlNode {

export function parseUslmToIr(xml: string, xmlPath?: string): ParsedTitleResult {
const parseErrors: ParseError[] = [];
const strippedXml = stripBom(xml);
const strippedXml = stampSectionSequence(stripBom(xml));

let document: { uslm?: { title?: XmlNode }; uscDoc?: { meta?: XmlNode; main?: { title?: XmlNode } } };
let orderedDocument: OrderedEntry[];
Expand Down Expand Up @@ -132,10 +138,12 @@ export function parseUslmToIr(xml: string, xmlPath?: string): ParsedTitleResult
};

let uncodifiedSectionIndex = 0;
const orderedSections = collectOrderedSectionNodes(orderedTitleNode);
const orderedSectionsBySequence = new Map(
collectOrderedSectionNodes(orderedTitleNode).map((entry) => [entry.sequence, entry] as const),
);

for (const [sectionIndex, { node: sectionNode, hierarchy }] of collectSectionNodes(titleNode).entries()) {
const orderedSectionNode = orderedSections[sectionIndex];
for (const { node: sectionNode, hierarchy } of collectSectionNodes(titleNode)) {
const orderedSectionNode = orderedSectionsBySequence.get(readSectionSequence(sectionNode));
const sectionNumber = readCanonicalNumText(parseErrors, sectionNode.num, xmlPath, 'section number');
const fallbackSectionNumber = sectionNumber || `uncodified-${++uncodifiedSectionIndex}`;

Expand Down Expand Up @@ -209,8 +217,20 @@ function findOrderedPath(nodes: OrderedEntry[] | undefined, path: string[]): Ord
return current;
}

function collectOrderedSectionNodes(titleNode: OrderedEntry[]): Array<{ children: OrderedEntry[]; hierarchy: HierarchyIR }> {
const sections: Array<{ children: OrderedEntry[]; hierarchy: HierarchyIR }> = [];
type OrderedSectionNode = { children: OrderedEntry[]; hierarchy: HierarchyIR; sequence: string | undefined };

function stampSectionSequence(xml: string): string {
let sequence = 0;
return xml.replace(/<((?:[\w.-]+:)?section)(?=[\s/>])/g, (_match, tag: string) => `<${tag} ${SECTION_SEQUENCE_ATTRIBUTE}="${sequence++}"`);
}

function readSectionSequence(sectionNode: XmlNode): string | undefined {
const value = (sectionNode as Record<string, unknown>)[SECTION_SEQUENCE_KEY];
return typeof value === 'string' ? value : undefined;
}

function collectOrderedSectionNodes(titleNode: OrderedEntry[]): OrderedSectionNode[] {
const sections: OrderedSectionNode[] = [];
collectOrderedSectionNodesRecursive(titleNode, {}, sections, false);
return sections;
}
Expand Down Expand Up @@ -265,7 +285,7 @@ function collectSectionNodesRecursive(
function collectOrderedSectionNodesRecursive(
nodes: OrderedEntry[],
hierarchy: HierarchyIR,
sections: Array<{ children: OrderedEntry[]; hierarchy: HierarchyIR }>,
sections: OrderedSectionNode[],
insideNoteScope: boolean,
): void {
for (const entry of nodes) {
Expand All @@ -288,7 +308,7 @@ function collectOrderedSectionNodesRecursive(

if (tag === 'section') {
if (!insideNoteScope) {
sections.push({ children: value, hierarchy });
sections.push({ children: value, hierarchy, sequence: orderedAttributes(entry)?.[SECTION_SEQUENCE_KEY] });
}
collectOrderedSectionNodesRecursive(value, hierarchy, sections, insideNoteScope);
continue;
Expand Down
71 changes: 71 additions & 0 deletions tests/unit/transforms/section-pairing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { describe, it, expect } from 'vitest';
import { parseUslmToIr } from '../../../src/transforms/uslm-to-ir';

// Regression: section numbers (read from the non-ordered parse) were paired with headings and content
// (read from the order-preserving parse) by list index. The non-ordered walk visits a container's
// <subchapter>/<part> children before its direct <section> children, so whenever a chapter mixes the two
// every following section got its neighbour's number. Real titles (e.g. 42, 50) were ~1 in 3 affected.
function buildXml(body: string): string {
return `<?xml version="1.0" encoding="UTF-8"?>
<uscDoc xmlns="http://xml.house.gov/schemas/uslm/1.0"><main>
<title identifier="/us/usc/t50"><num value="50">Title 50</num><heading>WAR AND NATIONAL DEFENSE</heading>
${body}
</title></main></uscDoc>`;
}

function section(num: string, heading: string, text: string): string {
return `<section identifier="/us/usc/t50/s${num}"><num value="${num}">§ ${num}.</num><heading>${heading}</heading>`
+ `<content><p>${text}</p></content></section>`;
}

function textOf(value: unknown): string {
return JSON.stringify(value);
}

describe('section number / body pairing', () => {
it('keeps each section number with its own heading and content when sections precede subchapters', () => {
const xml = buildXml(`
<chapter identifier="/us/usc/t50/ch44"><num value="44">CHAPTER 44</num><heading>NATIONAL SECURITY</heading>
${section('3001', 'Short title', 'alpha text')}
<subchapter identifier="/us/usc/t50/ch44/schI"><num value="I">SUBCHAPTER I</num><heading>COORDINATION</heading>
${section('3002', 'Congressional declaration of purpose', 'bravo text')}
${section('3003', 'Definitions', 'charlie text')}
</subchapter>
${section('3004', 'Trailing section', 'delta text')}
<part identifier="/us/usc/t50/ch44/ptA"><num value="A">PART A</num><heading>MISC</heading>
${section('3005', 'Part section', 'echo text')}
</part>
</chapter>`);

const { titleIr, parseErrors } = parseUslmToIr(xml);
expect(parseErrors).toEqual([]);

const byNumber = new Map(titleIr.sections.map((s) => [s.sectionNumber, s]));
const expected: Array<[string, string, string]> = [
['3001', 'Short title', 'alpha text'],
['3002', 'Congressional declaration of purpose', 'bravo text'],
['3003', 'Definitions', 'charlie text'],
['3004', 'Trailing section', 'delta text'],
['3005', 'Part section', 'echo text'],
];
expect(titleIr.sections).toHaveLength(expected.length);
for (const [num, heading, text] of expected) {
const parsed = byNumber.get(num);
expect(parsed?.heading).toBe(heading);
expect(parsed?.identifier).toBe(`/us/usc/t50/s${num}`);
expect(textOf(parsed?.content)).toContain(text);
for (const [, , other] of expected.filter(([n]) => n !== num)) {
expect(textOf(parsed?.content)).not.toContain(other);
}
}
});

it('does not leak the internal sequence marker into parsed output', () => {
const xml = buildXml(`
<chapter identifier="/us/usc/t50/ch44"><num value="44">CHAPTER 44</num><heading>NATIONAL SECURITY</heading>
${section('3001', 'Short title', 'alpha text')}
</chapter>`);
const { titleIr } = parseUslmToIr(xml);
expect(JSON.stringify(titleIr)).not.toContain('section-seq');
});
});
Loading