File size: 11,393 Bytes
a6b96c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
"use strict";
/**
 * ADR Markdown parser — parses Architecture Decision Record documents into
 * structured objects for downstream processing (adr command, gap checker, etc.).
 *
 * ADR-457 build-at-publish: the hand-written bin/lib/adr-parser.cjs collapsed
 * to a TypeScript source of truth. Behaviour is preserved byte-for-behaviour
 * from the prior hand-written .cjs; only types are added.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const security_cjs_1 = require("./security.cjs");
const STATUS_REJECT_SET = new Set(['superseded', 'rejected', 'deprecated']);
const CANONICAL_HEADERS = {
    status: ['status', 'state', 'lifecycle', 'stage'],
    goal: [
        'context',
        'background',
        'problem statement',
        'problem',
        'situation',
        'forces',
        'motivation',
        'issue',
        'drivers',
        'pain points',
        'story',
        'setting',
        'premise',
        'status quo',
        'context and problem statement',
    ],
    decisions: [
        'decision',
        'decisions',
        'resolution',
        'conclusion',
        'choice',
        'we decided',
        'direction',
        'approach',
        'solution',
        'outcome',
        'selected option',
        'recommendation',
        'strategy',
        'decision outcome',
    ],
    considered_options: [
        'considered options',
        'alternatives',
        'options',
        'choices',
        'candidates',
        'approaches considered',
        'variants',
        'trade-offs',
        'pros and cons of the options',
        'discussion',
    ],
    risks: [
        'risks',
        'trade-offs',
        'drawbacks',
        'cost',
        'tensions',
        'liabilities',
        'negative consequences',
        'side effects',
    ],
    success_criteria: [
        'success criteria',
        'acceptance criteria',
        'validation',
        "how we'll know",
        'metrics',
        'kpis',
        'verification',
        'test strategy',
        'compliance',
        'definition of done',
        'exit criteria',
        'positive consequences',
    ],
    plan_sequence: [
        'implementation plan',
        'implementation notes',
        'steps',
        'tasks',
        'roadmap',
        'sequence',
        'migration plan',
        'plan',
        'action items',
        'work breakdown',
        'phases',
        'milestones',
        'stages',
    ],
    key_files: [
        'affected files',
        'files touched',
        'surface area',
        'modules affected',
        'code locations',
        'file changes',
        'diff summary',
        'touched code',
    ],
    out_of_scope: [
        'out of scope',
        'non-goals',
        'excluded',
        'not in this adr',
        'out of bounds',
        "won't do",
        "won't have",
        'beyond scope',
        'anti-goals',
    ],
    deferred: [
        'future work',
        'deferred',
        'future',
        'later',
        'follow-up',
        'next steps',
    ],
    dependencies: [
        'dependencies',
        'depends on',
        'prerequisites',
        'sequencing',
        'order',
        'blocked by',
        'cross-cuts',
        'related adrs',
        'links',
        'references',
        'see also',
        'upstream',
        'inbound',
    ],
    update: [
        'update',
        'revision',
        'amendment',
        'locked design',
        'final decision',
        'post-grilling',
        'addendum',
    ],
    consequences: [
        'consequences',
        'implications',
        'impact',
        'what this means',
        'result',
    ],
};
const CONSEQUENCE_NEGATIVE_HINTS = [
    'negative',
    'drawback',
    'risk',
    'cost',
    'liability',
    'trade-off',
    'tension',
    'side effect',
];
const CONSEQUENCE_POSITIVE_HINTS = [
    'positive',
    'success',
    'metric',
    'kpi',
    'verification',
    'acceptance',
    'benefit',
];
function normalizeAdrHeader(raw) {
    const s = typeof raw === 'string' ? raw : '';
    return s
        .trim()
        .toLowerCase()
        .replace(/[\s:._-]+/g, ' ')
        .replace(/[^\w\s]/g, '')
        .trim();
}
function classifyHeader(normalizedHeader) {
    for (const [canonical, synonyms] of Object.entries(CANONICAL_HEADERS)) {
        for (const synonym of synonyms) {
            if (normalizedHeader === synonym)
                return canonical;
            if (normalizedHeader.startsWith(`${synonym} `))
                return canonical;
        }
    }
    return null;
}
function splitEntries(blockText) {
    return (typeof blockText === 'string' ? blockText : '')
        .split(/\r?\n/)
        .map((line) => line.trim())
        .filter(Boolean)
        .map((line) => line.replace(/^[-*+]\s+/, '').trim())
        .filter(Boolean);
}
function parseSections(markdown) {
    const lines = (typeof markdown === 'string' ? markdown : '').split(/\r?\n/);
    const sections = [];
    let current = { heading: null, body: [] };
    for (const line of lines) {
        const m = line.match(/^#{1,6}\s+(.*)$/);
        if (m) {
            if (current.heading || current.body.length)
                sections.push(current);
            current = { heading: m[1].trim(), body: [] };
        }
        else {
            current.body.push(line);
        }
    }
    if (current.heading || current.body.length)
        sections.push(current);
    return sections;
}
function parseStatusFromSections(sections) {
    for (const section of sections) {
        const canonical = classifyHeader(normalizeAdrHeader(section.heading));
        if (canonical !== 'status')
            continue;
        const line = splitEntries(section.body.join('\n'))[0] || '';
        const norm = normalizeAdrHeader(line);
        if (!norm)
            return '';
        if (norm.includes('accepted'))
            return 'accepted';
        if (norm.includes('proposed'))
            return 'proposed';
        if (norm.includes('superseded'))
            return 'superseded';
        if (norm.includes('rejected'))
            return 'rejected';
        if (norm.includes('deprecated'))
            return 'deprecated';
        return norm;
    }
    return '';
}
function pushUnique(target, values) {
    const seen = new Set(target);
    for (const value of values) {
        if (!seen.has(value)) {
            target.push(value);
            seen.add(value);
        }
    }
}
function parseConsequences(lines, out) {
    for (const entry of lines) {
        const lower = entry.toLowerCase();
        if (CONSEQUENCE_NEGATIVE_HINTS.some((hint) => lower.includes(hint))) {
            out.consequences_negative.push(entry);
            continue;
        }
        if (CONSEQUENCE_POSITIVE_HINTS.some((hint) => lower.includes(hint))) {
            out.consequences_positive.push(entry);
            continue;
        }
        out.consequences_positive.push(entry);
    }
}
function parseAdrMarkdown(markdown, { sourcePath = '', format = 'auto' } = {}) {
    const sections = parseSections(markdown);
    const titleLine = (typeof markdown === 'string' ? markdown : '').split(/\r?\n/).find((line) => /^#\s+/.test(line)) || '';
    const title = titleLine.replace(/^#\s+/, '').trim();
    const out = {
        title,
        status: parseStatusFromSections(sections) || 'accepted',
        context: '',
        decisions: [],
        options_considered: [],
        consequences_positive: [],
        consequences_negative: [],
        out_of_scope: [],
        deferred: [],
        dependencies: [],
        updates: [],
        source_path: sourcePath,
        key_files: [],
        plan_sequence: [],
        format,
        unmapped_headers: [],
    };
    for (const section of sections) {
        const heading = section.heading || '';
        if (!heading)
            continue;
        const canonical = classifyHeader(normalizeAdrHeader(heading));
        const entries = splitEntries(section.body.join('\n'));
        const prose = section.body.join('\n').trim();
        if (!canonical) {
            out.unmapped_headers.push(heading);
            continue;
        }
        switch (canonical) {
            case 'goal':
                if (!out.context && prose)
                    out.context = prose;
                break;
            case 'decisions':
                pushUnique(out.decisions, entries);
                break;
            case 'considered_options':
                pushUnique(out.options_considered, entries);
                break;
            case 'risks':
                pushUnique(out.consequences_negative, entries);
                break;
            case 'success_criteria':
                pushUnique(out.consequences_positive, entries);
                break;
            case 'plan_sequence':
                pushUnique(out.plan_sequence, entries);
                break;
            case 'key_files':
                pushUnique(out.key_files, entries);
                break;
            case 'out_of_scope':
                pushUnique(out.out_of_scope, entries);
                break;
            case 'deferred':
                pushUnique(out.deferred, entries);
                break;
            case 'dependencies':
                pushUnique(out.dependencies, entries);
                break;
            case 'update':
                out.updates.push({ heading, entries });
                break;
            case 'consequences':
                parseConsequences(entries, out);
                break;
            default:
                break;
        }
    }
    return out;
}
function shouldRejectAdrStatus(status) {
    return STATUS_REJECT_SET.has(normalizeAdrHeader(status));
}
function parseCliArgs(argv) {
    const opts = { input: null, format: 'auto', projectDir: process.cwd() };
    for (let i = 0; i < argv.length; i++) {
        const arg = argv[i];
        if (arg === '--input') {
            opts.input = argv[++i] || null;
        }
        else if (arg === '--format') {
            opts.format = argv[++i] || 'auto';
        }
        else if (arg === '--project-dir') {
            opts.projectDir = argv[++i] || process.cwd();
        }
        else {
            throw new Error(`Unknown argument: ${arg}`);
        }
    }
    if (!opts.input) {
        throw new Error('Missing required --input <path>');
    }
    return opts;
}
function main(argv) {
    const opts = parseCliArgs(argv);
    const safePath = (0, security_cjs_1.requireSafePath)(opts.input, node_path_1.default.resolve(opts.projectDir), 'ADR input path', { allowAbsolute: true });
    const content = node_fs_1.default.readFileSync(safePath, 'utf8');
    const parsed = parseAdrMarkdown(content, { sourcePath: opts.input ?? undefined, format: opts.format });
    process.stdout.write(JSON.stringify(parsed, null, 2));
}
if (require.main === module) {
    try {
        main(process.argv.slice(2));
    }
    catch (error) {
        process.stderr.write(`Error: ${error.message}\n`);
        process.exit(1);
    }
}
module.exports = {
    CANONICAL_HEADERS,
    normalizeAdrHeader,
    parseAdrMarkdown,
    shouldRejectAdrStatus,
};