rtl-analyzer 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,334 @@
1
+ import ts from 'typescript';
2
+ const unwrap = (x) => ts.isParenthesizedExpression(x) ? unwrap(x.expression) : x;
3
+ const key = (x) => ts.isIdentifier(x) || ts.isStringLiteral(x) ? x.text : undefined;
4
+ const signature = (x) => {
5
+ if (ts.isIdentifier(x) || ts.isStringLiteral(x) || ts.isNumericLiteral(x))
6
+ return `${x.kind}:${x.text}`;
7
+ const children = [];
8
+ ts.forEachChild(x, n => { children.push(signature(n)); });
9
+ return `${x.kind}(${children.join('|')})`;
10
+ };
11
+ export function analyzeRuntimeDirection(sf) {
12
+ const imports = new Map();
13
+ const namespaces = new Map();
14
+ const ambiguousImports = new Set();
15
+ const register = (name, value) => { if (imports.has(name))
16
+ ambiguousImports.add(name); imports.set(name, value); };
17
+ const declarations = new Map();
18
+ const allNodes = [];
19
+ function collect(n) {
20
+ allNodes.push(n);
21
+ if (ts.isImportDeclaration(n) && ts.isStringLiteral(n.moduleSpecifier)) {
22
+ const c = n.importClause, module = n.moduleSpecifier.text;
23
+ if (c?.name)
24
+ register(c.name.text, `${module}:${c.isTypeOnly ? 'type:' : ''}default`);
25
+ if (c?.namedBindings && ts.isNamedImports(c.namedBindings))
26
+ for (const e of c.namedBindings.elements) {
27
+ register(e.name.text, `${module}:${e.isTypeOnly || c?.isTypeOnly ? 'type:' : ''}${e.propertyName?.text ?? e.name.text}`);
28
+ }
29
+ if (c?.namedBindings && ts.isNamespaceImport(c.namedBindings))
30
+ namespaces.set(c.namedBindings.name.text, module);
31
+ }
32
+ if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name)) {
33
+ const items = declarations.get(n.name.text) ?? [];
34
+ items.push(n);
35
+ declarations.set(n.name.text, items);
36
+ }
37
+ ts.forEachChild(n, collect);
38
+ }
39
+ collect(sf);
40
+ // Record binding identities, including unsupported destructuring, before resolving uses.
41
+ // Unsupported bindings still hide outer definitions; they never authorize a proof.
42
+ const lexical = new Map();
43
+ const lexicalScope = (n) => {
44
+ let p = n.parent;
45
+ while (p && !ts.isBlock(p) && !ts.isSourceFile(p) && !ts.isFunctionLike(p) &&
46
+ !ts.isCatchClause(p) && !ts.isForStatement(p) && !ts.isForInStatement(p) && !ts.isForOfStatement(p))
47
+ p = p.parent;
48
+ return p ?? sf;
49
+ };
50
+ const record = (owner, name, node) => {
51
+ if (ts.isIdentifier(name)) {
52
+ const table = lexical.get(owner) ?? new Map();
53
+ table.set(name.text, [...(table.get(name.text) ?? []), node]);
54
+ lexical.set(owner, table);
55
+ }
56
+ else
57
+ for (const element of name.elements)
58
+ if (ts.isBindingElement(element))
59
+ record(owner, element.name, element);
60
+ };
61
+ for (const n of allNodes) {
62
+ if (ts.isVariableDeclaration(n)) {
63
+ let owner = lexicalScope(n);
64
+ if (ts.isVariableDeclarationList(n.parent) && !(n.parent.flags & ts.NodeFlags.BlockScoped)) {
65
+ while (!ts.isFunctionLike(owner) && !ts.isSourceFile(owner))
66
+ owner = lexicalScope(owner);
67
+ }
68
+ record(owner, n.name, n);
69
+ }
70
+ else if (ts.isParameter(n))
71
+ record(n.parent, n.name, n);
72
+ else if ((ts.isFunctionDeclaration(n) || ts.isClassDeclaration(n)) && n.name)
73
+ record(lexicalScope(n), n.name, n);
74
+ else if ((ts.isFunctionExpression(n) || ts.isClassExpression(n)) && n.name)
75
+ record(n, n.name, n);
76
+ }
77
+ const nearest = (x) => {
78
+ let p = x;
79
+ while (p) {
80
+ const matches = lexical.get(p)?.get(x.text);
81
+ if (matches)
82
+ return matches.length === 1 ? matches[0] : p; // ambiguity blocks outer lookup
83
+ p = p.parent;
84
+ }
85
+ return;
86
+ };
87
+ const isShadowedImport = (x) => nearest(x) !== undefined;
88
+ const binding = (x) => ts.isIdentifier(x) && !ambiguousImports.has(x.text) && !isShadowedImport(x) ? imports.get(x.text) : undefined;
89
+ const definition = (x) => {
90
+ const d = nearest(x);
91
+ if (!d || !ts.isVariableDeclaration(d) || !ts.isIdentifier(d.name) || !d.initializer ||
92
+ !ts.isVariableDeclarationList(d.parent) || !(d.parent.flags & ts.NodeFlags.Const))
93
+ return;
94
+ return { expression: d.initializer, declaration: d };
95
+ };
96
+ const moduleDefinition = (d) => ts.isVariableStatement(d.declaration.parent.parent) && ts.isSourceFile(d.declaration.parent.parent.parent);
97
+ const properties = (x) => {
98
+ if (!ts.isObjectLiteralExpression(x))
99
+ return;
100
+ const result = new Map();
101
+ for (const p of x.properties) {
102
+ if (!ts.isPropertyAssignment(p))
103
+ return;
104
+ const name = key(p.name);
105
+ if (!name || result.has(name))
106
+ return;
107
+ result.set(name, p);
108
+ }
109
+ return result;
110
+ };
111
+ // Reject mutation/escape of runtime definitions instead of treating const as deep immutability.
112
+ const escaped = (d) => allNodes.some(n => {
113
+ if (!ts.isIdentifier(n) || definition(n)?.declaration !== d.declaration || n === d.declaration.name)
114
+ return false;
115
+ let p = n;
116
+ while (ts.isPropertyAccessExpression(p.parent) || ts.isElementAccessExpression(p.parent))
117
+ p = p.parent;
118
+ const parent = p.parent;
119
+ return ts.isBinaryExpression(parent) && parent.left === p && parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment ||
120
+ (ts.isPostfixUnaryExpression(parent) || ts.isPrefixUnaryExpression(parent) || ts.isDeleteExpression(parent)) ||
121
+ ts.isCallExpression(parent) || ts.isNewExpression(parent) || ts.isReturnStatement(parent) ||
122
+ ts.isPropertyAssignment(parent) || ts.isArrayLiteralExpression(parent) || ts.isVariableDeclaration(parent) || ts.isExportSpecifier(parent);
123
+ });
124
+ const reasons = [];
125
+ const fail = (reason) => { reasons.push(reason); return undefined; };
126
+ function cache(x) {
127
+ x = unwrap(x);
128
+ if (!ts.isIdentifier(x))
129
+ return fail('Cache must reference a module const created by the directly imported factory.');
130
+ const d = definition(x);
131
+ if (!d || !moduleDefinition(d) || escaped(d) || ts.isVariableStatement(d.declaration.parent.parent) && d.declaration.parent.parent.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword))
132
+ return fail('Cache definition is ambiguous, mutable, escaping or created inside a render/function.');
133
+ const call = d.expression;
134
+ if (!ts.isCallExpression(call) || binding(call.expression) !== '@emotion/cache:default' || call.arguments.length !== 1)
135
+ return fail('Unknown cache factory or nonliteral cache options.');
136
+ const props = properties(call.arguments[0]);
137
+ if (!props || [...props.keys()].some(k => !['key', 'stylisPlugins'].includes(k)))
138
+ return fail('Cache options contain unsupported fields, duplicate keys or spreads.');
139
+ const k = props.get('key')?.initializer;
140
+ if (!k || !ts.isStringLiteral(k) || !/^[a-z-]+$/.test(k.text))
141
+ return fail('Cache key must be a nonempty literal lowercase/hyphen string.');
142
+ const plugins = props.get('stylisPlugins')?.initializer;
143
+ if (!plugins || !ts.isArrayLiteralExpression(plugins))
144
+ return fail('Missing or dynamic plugin array; prefixer must be explicit.');
145
+ const names = plugins.elements.map(p => binding(p));
146
+ if (names[0] !== 'stylis:prefixer')
147
+ return fail('Missing prefixer or incorrect plugin order.');
148
+ let direction;
149
+ if (names.length === 1)
150
+ direction = 'ltr';
151
+ else if (names.length === 2 && names[1] === '@mui/stylis-plugin-rtl:default')
152
+ direction = 'rtl';
153
+ else
154
+ return fail('Missing/unknown/dynamic/duplicate RTL processor or unsupported plugin order.');
155
+ return { direction, key: k.text, declaration: d.declaration };
156
+ }
157
+ function theme(x) {
158
+ x = unwrap(x);
159
+ if (!ts.isIdentifier(x))
160
+ return fail('Theme must reference a module const with explicit literal direction.');
161
+ const d = definition(x);
162
+ if (!d || !moduleDefinition(d) || escaped(d))
163
+ return fail('Theme definition is ambiguous, mutable, escaping or render-local.');
164
+ const call = d.expression;
165
+ if (!ts.isCallExpression(call) || !['@mui/material:createTheme', '@mui/material/styles:createTheme'].includes(binding(call.expression) ?? '') || call.arguments.length !== 1)
166
+ return fail('Unsupported theme factory/options.');
167
+ const props = properties(call.arguments[0]), p = props?.get('direction');
168
+ if (!p || !ts.isStringLiteral(p.initializer) || !['ltr', 'rtl'].includes(p.initializer.text))
169
+ return fail('Theme direction is not an explicit supported literal.');
170
+ return { direction: p.initializer.text, property: p };
171
+ }
172
+ function selection(x, leaf, seen = new Set()) {
173
+ x = unwrap(x);
174
+ if (ts.isIdentifier(x)) {
175
+ const d = definition(x);
176
+ if (d && ts.isConditionalExpression(unwrap(d.expression))) {
177
+ if (seen.has(d.declaration) || escaped(d))
178
+ return fail('Cyclic or escaping selection alias.');
179
+ return selection(d.expression, leaf, new Set([...seen, d.declaration]));
180
+ }
181
+ }
182
+ if (ts.isConditionalExpression(x)) {
183
+ // Only side-effect-free comparison predicates. Opaque identifiers/calls are not proven selectors.
184
+ const c = unwrap(x.condition);
185
+ if (!ts.isBinaryExpression(c) || c.operatorToken.kind !== ts.SyntaxKind.EqualsEqualsEqualsToken ||
186
+ !ts.isIdentifier(c.left) || !ts.isStringLiteral(c.right) || !['rtl', 'ar'].includes(c.right.text))
187
+ return fail('Unsupported direction predicate.');
188
+ const yes = leaf(x.whenTrue), no = leaf(x.whenFalse);
189
+ return yes && no ? { predicate: signature(c), yes, no } : undefined;
190
+ }
191
+ const value = leaf(x);
192
+ return value !== undefined ? { yes: value, no: value } : undefined;
193
+ }
194
+ const attribute = (n, name) => {
195
+ if (n.attributes.properties.some(p => ts.isJsxSpreadAttribute(p)))
196
+ return;
197
+ const attrs = n.attributes.properties.filter(p => ts.isJsxAttribute(p) && p.name.getText(sf) === name);
198
+ const a = attrs[0];
199
+ return attrs.length === 1 && ts.isJsxAttribute(a) && a.initializer && ts.isJsxExpression(a.initializer) ? a.initializer.expression : undefined;
200
+ };
201
+ const importedTag = (n, role) => {
202
+ const name = n.tagName.getText(sf);
203
+ if (imports.get(name)?.endsWith(`:${role}`))
204
+ return true;
205
+ if (ts.isPropertyAccessExpression(n.tagName) && ts.isIdentifier(n.tagName.expression) &&
206
+ namespaces.has(n.tagName.expression.text) && n.tagName.name.text === role)
207
+ return true;
208
+ // Local aliases and named re-exports remain visible, but are never accepted as direct bindings.
209
+ const d = ts.isIdentifier(n.tagName) ? definition(n.tagName) : undefined;
210
+ return !!d && ts.isIdentifier(d.expression) && imports.get(d.expression.text)?.endsWith(`:${role}`) === true;
211
+ };
212
+ const openings = allNodes.filter((n) => ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n));
213
+ const cacheNodes = openings.filter(n => importedTag(n, 'CacheProvider') || n.tagName.getText(sf) === 'CacheProvider');
214
+ const proofs = [];
215
+ for (const node of cacheNodes) {
216
+ reasons.length = 0;
217
+ if (binding(node.tagName) !== '@emotion/react:CacheProvider')
218
+ fail('Unresolved CacheProvider alias, namespace, wrapper or re-export.');
219
+ const value = attribute(node, 'value');
220
+ const cs = value ? selection(value, cache) : fail('CacheProvider value missing, duplicated or spread.');
221
+ // Require exactly one directly nested ThemeProvider, not an untraced wrapper.
222
+ const parent = node.parent;
223
+ const children = ts.isJsxElement(parent) && parent.openingElement === node ? parent.children.filter(n => !ts.isJsxText(n) || n.getText(sf).trim()) : [];
224
+ const nested = children.length === 1 && ts.isJsxElement(children[0]) ? children[0].openingElement : undefined;
225
+ if (!nested || !['@mui/material:ThemeProvider', '@mui/material/styles:ThemeProvider'].includes(binding(nested.tagName) ?? ''))
226
+ fail('A single direct ThemeProvider child is required; wrapper topology is unresolved.');
227
+ const tv = nested && attribute(nested, 'theme');
228
+ const th = tv ? selection(tv, theme) : fail('Theme selection is missing or unsupported.');
229
+ if (cs && th && (cs.predicate !== th.predicate || cs.yes.direction !== th.yes.direction || cs.no.direction !== th.no.direction))
230
+ fail('Theme/cache direction selection mismatch.');
231
+ if (cs) {
232
+ if (cs.predicate && (cs.yes.direction !== 'rtl' || cs.no.direction !== 'ltr'))
233
+ fail('RTL/Arabic predicate branches must select RTL then LTR.');
234
+ const definitions = new Map();
235
+ // All recognizable module caches share one document namespace, including unused definitions.
236
+ for (const list of declarations.values())
237
+ for (const d of list)
238
+ if (d.initializer && ts.isCallExpression(d.initializer) && binding(d.initializer.expression) === '@emotion/cache:default') {
239
+ const p = d.initializer.arguments[0] && properties(d.initializer.arguments[0]);
240
+ const k = p?.get('key')?.initializer;
241
+ if (k && ts.isStringLiteral(k))
242
+ definitions.set(d, k.text);
243
+ }
244
+ if (new Set(definitions.values()).size !== definitions.size)
245
+ fail('Duplicate cache keys in analyzed file.');
246
+ if (cs.yes.direction !== cs.no.direction && cs.yes.key === cs.no.key)
247
+ fail('LTR and RTL caches require distinct keys.');
248
+ const docs = allNodes.filter((n) => ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.EqualsToken && n.left.getText(sf) === 'document.documentElement.dir');
249
+ const ds = docs.map(n => selection(n.right, x => ts.isStringLiteral(x) && ['ltr', 'rtl'].includes(x.text) ? x.text : undefined));
250
+ if (!ds.length || ds.some(d => !d || d.predicate !== cs.predicate || d.yes !== cs.yes.direction || d.no !== cs.no.direction))
251
+ fail('Document/theme/cache selection cannot be correlated within this source file.');
252
+ }
253
+ // Predicate identifiers must bind to the same lexical declaration across selectors.
254
+ if (cs?.predicate) {
255
+ const conditions = [];
256
+ for (const x of [value, tv, ...allNodes.filter((n) => ts.isBinaryExpression(n) && n.left.getText(sf) === 'document.documentElement.dir').map(n => n.right)]) {
257
+ if (!x)
258
+ continue;
259
+ let e = unwrap(x);
260
+ if (ts.isIdentifier(e)) {
261
+ const d = definition(e);
262
+ if (d)
263
+ e = unwrap(d.expression);
264
+ }
265
+ if (ts.isConditionalExpression(e) && ts.isBinaryExpression(e.condition) && ts.isIdentifier(e.condition.left))
266
+ conditions.push(e.condition.left);
267
+ }
268
+ function predicateBinding(n) {
269
+ const resolved = nearest(n);
270
+ if (!resolved)
271
+ return;
272
+ if (ts.isVariableDeclaration(resolved))
273
+ return definition(n)?.declaration;
274
+ if (ts.isParameter(resolved))
275
+ return ts.isIdentifier(resolved.name) && !resolved.initializer && !resolved.dotDotDotToken ? resolved : undefined;
276
+ if (!ts.isBindingElement(resolved) || resolved.initializer || resolved.dotDotDotToken || !ts.isObjectBindingPattern(resolved.parent))
277
+ return;
278
+ // Keep the existing flat immutable object-selector grammar; nested/rest/array
279
+ // bindings hide outer selectors but remain unsupported for correlation.
280
+ const owner = resolved.parent.parent;
281
+ if (ts.isParameter(owner))
282
+ return !owner.initializer && !owner.dotDotDotToken ? resolved : undefined;
283
+ if (ts.isVariableDeclaration(owner) && ts.isVariableDeclarationList(owner.parent) && owner.parent.flags & ts.NodeFlags.Const)
284
+ return resolved;
285
+ return;
286
+ }
287
+ const declarationsFor = conditions.map(predicateBinding);
288
+ if (!conditions.length || declarationsFor.some(d => !d) || new Set(declarationsFor).size !== 1)
289
+ fail('Direction predicate binding is unresolved or differs between selectors.');
290
+ if (conditions.some(n => allNodes.some(x => ts.isBinaryExpression(x) && x.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && x.operatorToken.kind <= ts.SyntaxKind.LastAssignment && ts.isIdentifier(x.left) && nearest(x.left) === predicateBinding(n) || (ts.isPostfixUnaryExpression(x) || ts.isPrefixUnaryExpression(x)) && ts.isIdentifier(x.operand) && nearest(x.operand) === predicateBinding(n))))
291
+ fail('Direction predicate is reassigned; sequencing is unsupported.');
292
+ }
293
+ proofs.push({ node, supported: reasons.length === 0, reasons: [...new Set(reasons)], themeDirections: reasons.length === 0 && th ? [...new Set([th.yes.property, th.no.property])] : [] });
294
+ }
295
+ // A proved subtree cannot excuse another untraced ThemeProvider in the same file.
296
+ const nestedThemes = new Set(proofs.map(p => {
297
+ const parent = p.node.parent;
298
+ return ts.isJsxElement(parent) ? parent.children.find(ts.isJsxElement)?.openingElement : undefined;
299
+ }));
300
+ const extraThemes = openings.some(n => importedTag(n, 'ThemeProvider') && !nestedThemes.has(n));
301
+ if (extraThemes)
302
+ for (const p of proofs) {
303
+ p.supported = false;
304
+ p.themeDirections = [];
305
+ p.reasons.push('Additional ThemeProvider topology remains unresolved.');
306
+ }
307
+ if (proofs.length && proofs.every(p => p.supported)) {
308
+ // Ignore genuinely unused, unexported literal themes; do not claim imported consumers unreachable.
309
+ for (const list of declarations.values())
310
+ for (const declaration of list) {
311
+ const expression = declaration.initializer;
312
+ if (!expression || !ts.isCallExpression(expression) || !['@mui/material:createTheme', '@mui/material/styles:createTheme'].includes(binding(expression.expression) ?? ''))
313
+ continue;
314
+ if (!ts.isVariableStatement(declaration.parent.parent) || declaration.parent.parent.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword))
315
+ continue;
316
+ const refs = allNodes.filter(n => ts.isIdentifier(n) && n !== declaration.name && definition(n)?.declaration === declaration);
317
+ const property = expression.arguments[0] && properties(expression.arguments[0])?.get('direction');
318
+ if (!refs.length && property && ts.isStringLiteral(property.initializer))
319
+ proofs[0].themeDirections.push(property);
320
+ }
321
+ }
322
+ for (const [name, source] of imports)
323
+ if (source.endsWith(':CacheProvider')) {
324
+ const uses = allNodes.filter(n => ts.isIdentifier(n) && n.text === name && binding(n) === source && !ts.isImportSpecifier(n.parent) && !ts.isJsxClosingElement(n.parent));
325
+ const untraced = uses.find(n => !proofs.some(p => p.node === n.parent) && !ts.isImportClause(n.parent));
326
+ if (untraced || !cacheNodes.length) {
327
+ const node = untraced ?? allNodes.find(n => ts.isImportSpecifier(n) && n.name.text === name);
328
+ proofs.push({ node, supported: false, reasons: ['CacheProvider binding escapes into an unresolved alias/wrapper or has no traceable JSX use.'], themeDirections: [] });
329
+ for (const p of proofs)
330
+ p.themeDirections = [];
331
+ }
332
+ }
333
+ return proofs;
334
+ }
package/dist/scan.js ADDED
@@ -0,0 +1,59 @@
1
+ import { join } from 'node:path';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { extractCss, extractScss } from './css.js';
4
+ import { extractHtml } from './html.js';
5
+ import { extractTypescript } from './typescript.js';
6
+ import { detect } from './rules.js';
7
+ import { loadPolicy, policySourceText } from './policy.js';
8
+ import { auditPolicy } from './policy-audit.js';
9
+ import { classifyDiagnostics } from './coverage.js';
10
+ import { hash } from './model.js';
11
+ import { discover } from './discovery.js';
12
+ export async function scan(root) {
13
+ const discovery = await discover(root);
14
+ const { files, skipped } = discovery;
15
+ root = discovery.root;
16
+ files.sort();
17
+ const evidence = [], diagnostics = [], inputs = [], sources = new Map();
18
+ const policy = await loadPolicy(root);
19
+ for (const p of files) {
20
+ const s = await readFile(join(root, p), 'utf8');
21
+ inputs.push(p + '\0' + s);
22
+ sources.set(p, s);
23
+ if (s.length > 2_000_000)
24
+ throw new Error('Source exceeds size limit');
25
+ const r = p.endsWith('.scss') ? extractScss(p, s) : p.endsWith('.css') ? extractCss(p, s) : p.endsWith('.html') ? extractHtml(p, s) : extractTypescript(p, s);
26
+ evidence.push(...r.evidence);
27
+ diagnostics.push(...r.diagnostics);
28
+ }
29
+ const compare = (a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.range.start.offset - b.range.start.offset;
30
+ evidence.sort(compare);
31
+ diagnostics.sort(compare);
32
+ const occurrences = new Map();
33
+ for (const e of evidence) {
34
+ const anchor = [e.path, e.mechanism, e.context, e.property, e.value].join('|');
35
+ const ordinal = occurrences.get(anchor) ?? 0;
36
+ occurrences.set(anchor, ordinal + 1);
37
+ e.id = hash(anchor + '|' + ordinal);
38
+ }
39
+ for (const p of skipped)
40
+ if (/\.(scss|sass|less|styl|css|tsx?|jsx?)$/.test(p) && !p.endsWith('.stories.tsx'))
41
+ diagnostics.push({ path: p, code: 'SOURCE_COVERAGE', message: 'Unsupported or skipped source may contain directional styling; source not followed.', range: { start: { offset: 0, line: 1, column: 1 }, end: { offset: 0, line: 1, column: 1 } } });
42
+ const coverage = classifyDiagnostics(diagnostics, evidence, sources, policy);
43
+ // Audit against original risk anchors, with exceptions/approvals disabled. Roles remain
44
+ // source metadata so existing brand associations can be matched without changing rules.
45
+ const auditCoverage = coverage.map(d => ({ ...d }));
46
+ const anchors = detect(evidence, sources, { ...policy, approvals: [], exceptions: [], ownerOverrides: [] }, auditCoverage);
47
+ const policyDiagnostics = auditPolicy(policy, policySourceText(policy), evidence, sources, anchors, coverage);
48
+ coverage.push(...policyDiagnostics);
49
+ // Blocking policy uncertainty must not apply any effect-bearing policy records.
50
+ const effectivePolicy = policyDiagnostics.some(d => d.blocking) ? { ...policy, approvals: [], exceptions: [], dynamicExceptions: [], ownerOverrides: [] } : policy;
51
+ if (effectivePolicy !== policy) {
52
+ coverage.splice(0, coverage.length, ...classifyDiagnostics(diagnostics, evidence, sources, effectivePolicy), ...policyDiagnostics);
53
+ }
54
+ const findings = detect(evidence, sources, effectivePolicy, coverage);
55
+ coverage.sort(compare);
56
+ const count = (key) => Object.fromEntries([...new Set(findings.map(f => f[key]))].sort().map(v => [v, findings.filter(f => f[key] === v).length]));
57
+ const metrics = { byCategory: count('category'), bySeverity: count('severity'), byConfidence: count('confidence'), uniqueAffectedFiles: new Set(findings.map(f => f.path)).size, referenceCaseIds: [...new Set(findings.flatMap(f => f.issueIds))].sort() };
58
+ return { schemaVersion: 2, kind: 'rtl-risk-report', policyDigest: hash(JSON.stringify(policy)), inputDigest: hash(inputs.join('\0')), files, skipped: skipped.sort(), evidence, diagnostics: coverage, findings, metrics, complete: !coverage.some(d => d.blocking) };
59
+ }
@@ -0,0 +1,177 @@
1
+ import { constants } from 'node:fs';
2
+ import { lstat, open } from 'node:fs/promises';
3
+ import { isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
4
+ export const SOURCE_SNIPPET_LIMITS = Object.freeze({ contextLines: 5, maxLines: 100, maxBytes: 16 * 1024, totalBytes: 2 * 1024 * 1024 });
5
+ const pathError = (path) => !path || isAbsolute(path) || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith('\\\\') || path.startsWith('//') || path.includes('\\') || /[\0\r\n]/.test(path) || path.split('/').some(part => part === '..');
6
+ const unavailable = (findingId, reason) => ({ findingId, available: false, reason });
7
+ async function validatePath(root, path) {
8
+ if (pathError(path))
9
+ return 'INVALID_PATH';
10
+ const rootAbsolute = resolve(root), portablePath = path.split('/').join(sep), normalized = normalize(portablePath), absolute = resolve(rootAbsolute, normalized), rel = relative(rootAbsolute, absolute);
11
+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel) || normalized !== portablePath)
12
+ return 'INVALID_PATH';
13
+ try {
14
+ const rootStat = await lstat(rootAbsolute);
15
+ if (rootStat.isSymbolicLink())
16
+ return 'SYMLINK';
17
+ const parts = path.split('/');
18
+ let current = rootAbsolute;
19
+ for (const part of parts) {
20
+ current = join(current, part);
21
+ const stat = await lstat(current);
22
+ if (stat.isSymbolicLink())
23
+ return 'SYMLINK';
24
+ }
25
+ const stat = await lstat(absolute);
26
+ if (!stat.isFile())
27
+ return 'NON_REGULAR_FILE';
28
+ }
29
+ catch (error) {
30
+ if (error.code === 'ENOENT')
31
+ return 'MISSING_FILE';
32
+ return 'READ_FAILURE';
33
+ }
34
+ return { absolute };
35
+ }
36
+ async function readVerified(path, absolute) {
37
+ if (!constants.O_NOFOLLOW)
38
+ return 'UNSUPPORTED_NOFOLLOW';
39
+ let handle;
40
+ try {
41
+ handle = await open(absolute, constants.O_RDONLY | constants.O_NOFOLLOW);
42
+ const before = await handle.stat();
43
+ if (!before.isFile())
44
+ return 'NON_REGULAR_FILE';
45
+ const text = await handle.readFile({ encoding: 'utf8' });
46
+ const after = await handle.stat();
47
+ if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size)
48
+ return 'IDENTITY_CHANGED';
49
+ return { text, size: after.size };
50
+ }
51
+ catch (error) {
52
+ const code = error.code;
53
+ if (code === 'ENOENT')
54
+ return 'MISSING_FILE';
55
+ if (code === 'ELOOP')
56
+ return 'SYMLINK';
57
+ return 'READ_FAILURE';
58
+ }
59
+ finally {
60
+ await handle?.close().catch(() => undefined);
61
+ }
62
+ }
63
+ function lineTable(text) {
64
+ const lines = [];
65
+ let start = 0;
66
+ for (let i = 0; i <= text.length;) {
67
+ const match = text.slice(i).match(/\r\n|\r|\n/);
68
+ if (!match) {
69
+ lines.push({ text: text.slice(start), start, end: text.length });
70
+ break;
71
+ }
72
+ const end = i + match.index;
73
+ lines.push({ text: text.slice(start, end), start, end });
74
+ i = end + match[0].length;
75
+ start = i;
76
+ }
77
+ return lines.length ? lines : [{ text: '', start: 0, end: 0 }];
78
+ }
79
+ function lineAt(lines, offset) { const index = lines.findIndex(line => offset >= line.start && offset <= line.end); return index < 0 ? -1 : index; }
80
+ function scannerPoint(text, offset) {
81
+ const prefix = text.slice(0, offset), parts = prefix.split(/\r\n|\r|\n/);
82
+ return { offset, line: parts.length, column: parts.at(-1).length + 1 };
83
+ }
84
+ function samePoint(actual, expected) {
85
+ return actual.offset === expected.offset && actual.line === expected.line && actual.column === expected.column;
86
+ }
87
+ function makeWindow(path, finding, text, options) {
88
+ const lines = lineTable(text), start = finding.range.start.offset, end = finding.range.end.offset;
89
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start || end > text.length)
90
+ return 'INVALID_RANGE';
91
+ if (!samePoint(scannerPoint(text, start), finding.range.start) || !samePoint(scannerPoint(text, end), finding.range.end))
92
+ return 'POSITION_MISMATCH';
93
+ if (text.slice(start, end) !== finding.original)
94
+ return 'SOURCE_CHANGED';
95
+ const first = lineAt(lines, start), last = lineAt(lines, Math.max(start, end - 1));
96
+ if (first < 0 || last < 0)
97
+ return 'INVALID_RANGE';
98
+ if (last - first + 1 > options.maxLines || Buffer.byteLength(text.slice(start, end), 'utf8') > options.maxBytes)
99
+ return 'HIGHLIGHT_TOO_LARGE';
100
+ let from = Math.max(0, first - options.contextLines), to = Math.min(lines.length - 1, last + options.contextLines);
101
+ while (to - from + 1 > options.maxLines) {
102
+ if (from < first)
103
+ from++;
104
+ else if (to > last)
105
+ to--;
106
+ else
107
+ return 'SNIPPET_TOO_LARGE';
108
+ }
109
+ let bytes = Buffer.byteLength(text.slice(lines[from].start, lines[to].end), 'utf8');
110
+ while (bytes > options.maxBytes && (from < first || to > last)) {
111
+ if (from < first)
112
+ from++;
113
+ else
114
+ to--;
115
+ bytes = Buffer.byteLength(text.slice(lines[from].start, lines[to].end), 'utf8');
116
+ }
117
+ if (bytes > options.maxBytes)
118
+ return 'SNIPPET_TOO_LARGE';
119
+ const id = `${path}:${from + 1}-${to + 1}`;
120
+ return { id, path, startLine: from + 1, endLine: to + 1, bytes, lines: lines.slice(from, to + 1).map((line, i) => ({ number: from + i + 1, text: line.text, highlighted: from + i >= first && from + i <= last })) };
121
+ }
122
+ /**
123
+ * Reads only finding-bearing files. Range matching verifies anchors, not full snapshot identity.
124
+ * O_NOFOLLOW protects the opened file, but the lstat/open sequence cannot eliminate an
125
+ * attacker replacing an ancestor directory concurrently; the approved scan root and its
126
+ * ancestors must therefore be trusted during generation. These are generation-time reads,
127
+ * not authoritative live or full-file snapshots.
128
+ */
129
+ export async function extractSourceSnippets(root, findings, options = {}) {
130
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
131
+ const limits = { ...SOURCE_SNIPPET_LIMITS, ...options }, ordered = findings.slice().sort((a, b) => compare(a.path, b.path) || a.range.start.offset - b.range.start.offset || compare(a.id, b.id));
132
+ const files = new Map(), windows = new Map(), output = [];
133
+ let embeddedBytes = 0;
134
+ for (const finding of ordered) {
135
+ let file = files.get(finding.path);
136
+ if (!file) {
137
+ const validated = await validatePath(root, finding.path);
138
+ file = {};
139
+ files.set(finding.path, file);
140
+ if (typeof validated === 'string')
141
+ file.result = validated;
142
+ else {
143
+ file.absolute = validated.absolute;
144
+ const read = await readVerified(finding.path, validated.absolute);
145
+ if (typeof read === 'string')
146
+ file.result = read;
147
+ else
148
+ file.text = read.text;
149
+ }
150
+ }
151
+ if (file.text === undefined) {
152
+ output.push(unavailable(finding.id, file.result ?? 'READ_FAILURE'));
153
+ continue;
154
+ }
155
+ const window = makeWindow(finding.path, finding, file.text, limits);
156
+ if (typeof window === 'string') {
157
+ output.push(unavailable(finding.id, window));
158
+ continue;
159
+ }
160
+ if (embeddedBytes + (windows.has(window.id) ? 0 : window.bytes) > limits.totalBytes) {
161
+ output.push(unavailable(finding.id, 'TOTAL_LIMIT'));
162
+ continue;
163
+ }
164
+ const alreadyStored = windows.has(window.id);
165
+ windows.set(window.id, window);
166
+ if (!alreadyStored)
167
+ embeddedBytes += window.bytes;
168
+ output.push({ findingId: finding.id, sourceId: window.id, available: true, startLine: window.startLine, endLine: window.endLine });
169
+ }
170
+ const sourceTextByPath = {};
171
+ for (const [path, file] of files)
172
+ if (file.text !== undefined)
173
+ sourceTextByPath[path] = file.text;
174
+ const result = { sources: [...windows.values()].sort((a, b) => compare(a.id, b.id)), findings: output, embeddedBytes };
175
+ Object.defineProperty(result, 'sourceTextByPath', { value: sourceTextByPath, enumerable: false, writable: false });
176
+ return result;
177
+ }
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { runCli } from './cli.js';
6
+ const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
7
+ async function version() {
8
+ const packageJson = JSON.parse(await readFile(join(packageRoot, 'package.json'), 'utf8'));
9
+ return packageJson.version ?? '0.0.0';
10
+ }
11
+ function help() {
12
+ return `RTL Analyzer — conservative RTL risk scanning\n\nUsage:\n rtl-analyzer scan [path] [options]\n rtl-analyzer --help\n rtl-analyzer --version\n\nOptions:\n --root <path> Scan this project root\n --format <format> json, markdown, markdown-structured, or dashboard\n --output-dir <path> Write report artifacts to this directory\n --fail-on-findings Exit 1 when actionable findings exist\n --embed-source-snippets Embed bounded source snippets in dashboard output\n`;
13
+ }
14
+ const io = {
15
+ writeStdout: value => process.stdout.write(value),
16
+ writeStderr: value => process.stderr.write(`${value}\n`),
17
+ };
18
+ async function main(argv) {
19
+ if (argv.length === 0 || argv[0] === '--help' || argv[0] === '-h') {
20
+ io.writeStdout(help());
21
+ return 0;
22
+ }
23
+ if (argv[0] === '--version' || argv[0] === '-v') {
24
+ io.writeStdout(`${await version()}\n`);
25
+ return 0;
26
+ }
27
+ if (argv[0] !== 'scan') {
28
+ io.writeStderr(`Unknown command: ${argv[0]}. Use --help for usage.`);
29
+ return 2;
30
+ }
31
+ const scanArgs = argv.slice(1);
32
+ const firstPath = scanArgs[0];
33
+ if (firstPath && !firstPath.startsWith('-')) {
34
+ scanArgs.splice(0, 1, '--root', firstPath);
35
+ }
36
+ return runCli(scanArgs, io);
37
+ }
38
+ process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,36 @@
1
+ const sort = (a, b) => a.localeCompare(b);
2
+ // Escape backslashes before pipes as well as the pipe itself. Otherwise an
3
+ // input such as `\\|` can leave a pipe that CommonMark treats as a column.
4
+ const esc = (s) => s.replace(/[\u0000-\u001f\u007f]/g, '�').replace(/\\/g, '\\\\').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\|/g, '\\|').replace(/`/g, '\\`').replace(/\r?\n/g, ' ');
5
+ const block = (s) => { const runs = [...s.matchAll(/`+/g)].map(x => x[0].length); const fence = '`'.repeat(Math.max(3, (runs.length ? Math.max(...runs) : 2) + 1)); return fence + '\n' + s.replace(/[\u0000-\u001f\u007f]/g, '�') + '\n' + fence; };
6
+ const tally = (xs) => { const m = new Map(); xs.forEach(x => m.set(x, (m.get(x) || 0) + 1)); return [...m].sort((a, b) => sort(a[0], b[0])); };
7
+ export function structuredMarkdown(r) {
8
+ const groups = [
9
+ ['Actionable findings', r.findings.filter(f => ['AUTO_CANDIDATE', 'MANUAL_REVIEW', 'RUNTIME_CONFIG'].includes(f.category))],
10
+ ['Informational findings', r.findings.filter(f => f.category === 'INFORMATIONAL')],
11
+ ['Intentional-LTR findings', r.findings.filter(f => f.category === 'INTENTIONAL_LTR')],
12
+ ];
13
+ const table = (title, rows) => `## ${title}\n\n| Name | Count |\n| --- | ---: |\n${rows.map(x => `| ${esc(x[0])} | ${x[1]} |`).join('\n')}\n\n`;
14
+ let out = `# Structured RTL risk report\n\nStatic analysis and documented exceptions; not proof of visual failure.\n\n## Executive summary\n\n- Scan status: **${r.complete ? 'Complete' : 'Incomplete'}**\n- Schema: ${r.schemaVersion}\n- Files analyzed: ${r.files.length}\n- Skipped paths: ${r.skipped.length}\n- Findings: ${r.findings.length}\n- Diagnostics: ${r.diagnostics.length}\n- Blocking diagnostics: ${r.diagnostics.filter(d => d.blocking).length}\n\n${r.complete ? '' : '> This report is incomplete; absence of a finding is not evidence of safety.\n\n'}`;
15
+ out += `## Report metadata\n\n- Kind: ${esc(r.kind)}\n- Schema version: ${r.schemaVersion}\n- Input digest: ${esc(r.inputDigest)}\n- Policy digest: ${esc(r.policyDigest)}\n- Unique affected files: ${r.metrics.uniqueAffectedFiles}\n- Confidence metrics: ${Object.entries(r.metrics.byConfidence).sort(([a], [b]) => sort(a, b)).map(([k, v]) => `${esc(k)}=${v}`).join(', ') || 'none'}\n- Reference case IDs: ${r.metrics.referenceCaseIds.slice().sort(sort).map(esc).join(', ') || 'none'}\n\n`;
16
+ out += table('Findings overview', [['Actionable', groups[0][1].length], ['Informational', groups[1][1].length], ['Intentional LTR', groups[2][1].length]]);
17
+ out += table('Category breakdown', ['AUTO_CANDIDATE', 'MANUAL_REVIEW', 'RUNTIME_CONFIG', 'INFORMATIONAL', 'INTENTIONAL_LTR'].map(category => [category, r.findings.filter(f => f.category === category).length]));
18
+ out += table('Severity breakdown', tally(r.findings.map(f => f.severity)));
19
+ out += table('Rule breakdown', tally(r.findings.map(f => f.ruleId)));
20
+ out += table('Ownership', tally(r.findings.map(f => f.ownership)));
21
+ out += table('Application reachability', tally(r.findings.flatMap(f => f.applications.length ? f.applications : ['Shared or unresolved reachability'])));
22
+ out += '> Application attribution counts may overlap; they are not a unique finding total.\n\n';
23
+ for (const [title, list] of groups) {
24
+ out += `## ${title}\n\n`;
25
+ for (const f of list.slice().sort((a, b) => sort(a.path, b.path) || a.range.start.offset - b.range.start.offset || sort(a.id, b.id))) {
26
+ const ref = r.evidenceReferences.find(x => x.findingId === f.id);
27
+ const locations = f.relatedLocations.slice().sort((a, b) => sort(a.path, b.path) || a.range.start.offset - b.range.start.offset).map(x => `${esc(x.path)}:${x.range.start.line}:${x.range.start.column}`).join(', ') || 'none';
28
+ const exception = f.exceptionReason ? `\nException metadata: ${esc(f.exceptionReason)}; original category: ${esc(f.originalCategory ?? 'unknown')}.\n` : '';
29
+ const suggestion = f.suggestion ? `\nConditional suggestion (review required; not an automatic fix):\n\n- Property: ${esc(f.suggestion.property)}\n- Value:\n\n${block(f.suggestion.value)}\n` : '';
30
+ out += `### ${esc(f.id)}\n\n**${esc(f.title)}** — ${f.category}; ${f.severity}; ${f.confidence} confidence.\n\n- Source: ${esc(f.path)}:${f.range.start.line}:${f.range.start.column}\n- Owner: ${esc(f.ownership)}\n- Applications: ${f.applications.length ? f.applications.slice().sort(sort).map(esc).join(', ') : 'shared or unresolved reachability'}\n- Evidence IDs: ${ref?.evidenceIds.map(esc).join(', ') || 'none'}${ref?.missingEvidenceIds.length ? ` (missing: ${ref.missingEvidenceIds.map(esc).join(', ')})` : ''}${ref?.duplicateEvidenceIds.length ? ` (duplicate: ${ref.duplicateEvidenceIds.map(esc).join(', ')})` : ''}\n- Related locations: ${locations}\n\nOriginal declaration:\n\n${block(f.original)}\n\nRationale: ${esc(f.rationale)}\n\nTreatment: ${esc(f.treatment)}\n\nLimits: ${esc(f.limitation)}\n${exception}${suggestion}\n`;
31
+ }
32
+ }
33
+ const diagnostics = r.diagnostics.slice().sort((a, b) => sort(a.path, b.path) || a.range.start.offset - b.range.start.offset || sort(a.code, b.code)).map(d => `- ${esc(d.path)}:${d.range.start.line}:${d.range.start.column} — ${esc(d.code)}, impact=${esc(d.impact ?? 'none')}, blocking=${d.blocking}: ${esc(d.message)} ${esc(d.rationale ?? '')}`).join('\n') || '_None._';
34
+ const evidence = r.evidence.slice().sort((a, b) => sort(a.id, b.id)).map(e => `### ${esc(e.id)}\n\n- Source: ${esc(e.path)}:${e.range.start.line}:${e.range.start.column}\n- Mechanism: ${esc(e.mechanism)}\n- Property: ${esc(e.property)}\n- Value: ${block(e.value)}\n- Semantics: ${esc(e.semantics)}\n\n${block(e.original)}`).join('\n\n') || '_None._';
35
+ return out + `## Diagnostics and coverage warnings\n\n${diagnostics}\n\n## Evidence index\n\n${evidence}\n`;
36
+ }