rtl-analyzer 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +82 -2
- package/dist/bootstrap.js +27 -0
- package/dist/cli.js +76 -0
- package/dist/codemod.js +53 -0
- package/dist/coverage.js +36 -0
- package/dist/css.js +61 -0
- package/dist/dashboard-client.js +167 -0
- package/dist/dashboard-data.js +22 -0
- package/dist/dashboard-html.js +27 -0
- package/dist/discovery.js +71 -0
- package/dist/eligibility.js +19 -0
- package/dist/html.js +34 -0
- package/dist/model.js +9 -0
- package/dist/policy-audit.js +109 -0
- package/dist/policy-validation.js +137 -0
- package/dist/policy.js +32 -0
- package/dist/presentation-adapter.js +52 -0
- package/dist/preview-manifest.js +15 -0
- package/dist/report-publisher.js +110 -0
- package/dist/report.js +8 -0
- package/dist/review-session.js +153 -0
- package/dist/rules.js +215 -0
- package/dist/runtime-direction.js +334 -0
- package/dist/scan.js +59 -0
- package/dist/source-snippets.js +177 -0
- package/dist/standalone-cli.js +107 -0
- package/dist/structured-markdown.js +36 -0
- package/dist/tailwind.js +21 -0
- package/dist/typescript.js +191 -0
- package/package.json +30 -4
package/dist/rules.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
2
|
+
import { analyzeRuntimeDirection } from './runtime-direction.js';
|
|
3
|
+
import valueParser from 'postcss-value-parser';
|
|
4
|
+
import { hash, range } from './model.js';
|
|
5
|
+
const plain = (v) => v.replace(/^['"`]|['"`]$/g, '');
|
|
6
|
+
const cssKey = (p) => p.replace(/[A-Z]/g, c => '-' + c.toLowerCase());
|
|
7
|
+
export function detect(evidence, sources, policy, diagnostics) {
|
|
8
|
+
const findings = [];
|
|
9
|
+
const findingOccurrences = new Map();
|
|
10
|
+
function add(ruleId, title, a, category, rationale, treatment, ownership = 'unknown', refs = [], confidence = 'High', severity = 'Minor', suggestion = null, limitation = 'Static evidence indicates a risk; rendered behavior is not established by this scan.') {
|
|
11
|
+
const exception = policy.exceptions.find(x => x.ruleId === ruleId && x.path === a.path && x.context === a.context && x.originalDigest === hash(a.original));
|
|
12
|
+
const originalCategory = category;
|
|
13
|
+
if (exception)
|
|
14
|
+
category = exception.category;
|
|
15
|
+
const key = ruleId + '|' + a.id;
|
|
16
|
+
const occurrence = findingOccurrences.get(key) ?? 0;
|
|
17
|
+
findingOccurrences.set(key, occurrence + 1);
|
|
18
|
+
findings.push({ id: ruleId + ':' + hash(a.id + '|' + occurrence).slice(0, 24), ruleId, ruleVersion: 1, category, severity: category === 'INFORMATIONAL' || category === 'INTENTIONAL_LTR' ? 'Info' : severity, confidence, title, sourceMechanism: 'mechanism' in a ? a.mechanism : 'typescript-structure', applications: a.path.startsWith('apps/') ? [a.path.split('/')[1]] : [], path: a.path, range: a.range, original: a.original, context: a.context, ownership, rationale, treatment, evidenceIds: refs.map(e => e.id).sort(), relatedLocations: refs.filter(e => e.id !== a.id).map(e => ({ path: e.path, range: e.range })), issueIds: policy.issueBindings.filter(b => b.ruleId === ruleId && b.path === a.path && a.context.includes(b.contextIncludes) && (!b.originalIncludes || a.original.includes(b.originalIncludes))).map(b => b.issueId).sort(), suggestion: exception ? null : suggestion, limitation, ...(exception ? { exceptionReason: exception.reason, originalCategory } : {}) });
|
|
19
|
+
return findings.at(-1);
|
|
20
|
+
}
|
|
21
|
+
for (const e of evidence) {
|
|
22
|
+
if (cssKey(e.property) === 'position' && plain(e.value) === 'fixed') {
|
|
23
|
+
const peers = evidence.filter(x => x.path === e.path && x.context === e.context);
|
|
24
|
+
const width = peers.find(x => cssKey(x.property) === 'width');
|
|
25
|
+
const gutters = width ? evidence.filter(x => /^margin-(left|right)$/.test(cssKey(x.property)) && plain(x.value) === plain(width.value)) : [];
|
|
26
|
+
if (width && gutters.length)
|
|
27
|
+
add('RTL.GEOMETRY.COUPLED', 'Fixed shell width and physical content reservation', e, 'MANUAL_REVIEW', 'Fixed region width equals a separate physical content margin; independently flipping either can desynchronize shell geometry.', 'Review anchor, gutter, border, mobile transform and resets together.', policy.ownership[e.mechanism] ?? 'unknown', [e, ...peers.filter(x => /^(left|right|width|border-right|transform)$/.test(cssKey(x.property))), ...gutters], 'High');
|
|
28
|
+
}
|
|
29
|
+
if (e.mechanism === 'html-root')
|
|
30
|
+
continue;
|
|
31
|
+
const overrides = policy.ownerOverrides?.filter(x => x.path === e.path && x.context === e.context) ?? [];
|
|
32
|
+
const owners = new Set(overrides.map(x => x.owner));
|
|
33
|
+
const p = cssKey(e.property), v = plain(e.value), owner = owners.size > 1 ? 'conflicting' : overrides[0]?.owner ?? policy.ownership[e.mechanism] ?? 'unknown';
|
|
34
|
+
if (owner === 'conflicting' && !findings.some(f => f.ruleId === 'RTL.OWNERSHIP.CONFLICT' && f.path === e.path && f.context === e.context))
|
|
35
|
+
add('RTL.OWNERSHIP.CONFLICT', 'Conflicting style owners', e, 'MANUAL_REVIEW', 'Multiple data-only policy entries claim different ownership for the same style context.', 'Resolve ownership before proposing logical conversion or RTL processing.', owner, [e], 'High');
|
|
36
|
+
const peers = evidence.filter(x => x.path === e.path && x.context === e.context);
|
|
37
|
+
const position = peers.find(x => cssKey(x.property) === 'position');
|
|
38
|
+
const dynamic = diagnostics.some(d => d.path === e.path && d.blocking && d.range.start.offset >= e.range.start.offset && d.range.end.offset <= e.range.end.offset);
|
|
39
|
+
if (/^(left|right)$/.test(p))
|
|
40
|
+
add('RTL.GEOMETRY.EDGE', 'Physical positioned edge', e, 'MANUAL_REVIEW', 'Physical edge is coupled to placement, containing block and clearance; logical replacement alone does not select the correct side.', 'Review anchor, companion gutter, breakpoints and collision clearance as one layout contract.', owner, [e, ...(position ? [position] : [])], 'High');
|
|
41
|
+
else if (/^(margin|padding|border)-(left|right)(-|$)/.test(p) || /^(border-top-left-radius|border-top-right-radius|border-bottom-left-radius|border-bottom-right-radius)$/.test(p) || (/^(text-align|float|clear)$/.test(p) && /^(left|right)$/.test(v))) {
|
|
42
|
+
const approval = policy.approvals.find(a => a.path === e.path && a.context === e.context && a.property === e.property && a.value === e.value && a.owner === owner && a.sourceDigest === hash(sources.get(e.path) ?? ''));
|
|
43
|
+
const expectedLogical = p.replace(/^(margin|padding|border)-(left|right)(.*)$/, (_, group, side, suffix) => `${group}-inline-${side === 'left' ? 'start' : 'end'}${suffix}`);
|
|
44
|
+
const safe = approval && cssKey(approval.logicalProperty) === expectedLogical && !evidence.some(x => cssKey(x.property) === 'writing-mode' && plain(x.value) !== 'horizontal-tb') && e.mechanism !== 'mui-sx' && !/^(inherit|initial|unset|revert|revert-layer)$/.test(v) && !/\b(var|env)\(/.test(v) && !dynamic && ['custom-css', 'custom-inline', 'custom-emotion-logical'].includes(owner) && /^(margin|padding|border)-(left|right)(-|$)/.test(p) && !diagnostics.some(d => d.blocking) && !peers.some(x => x !== e && cssKey(x.property) === p) && !position && !peers.some(x => /writing-mode|direction/.test(cssKey(x.property)));
|
|
45
|
+
add('RTL.CSS.PHYSICAL', 'Physical horizontal declaration', e, safe ? 'AUTO_CANDIDATE' : 'MANUAL_REVIEW', safe ? approval.reason : 'Physical syntax does not establish reading-start/end intent or styling ownership.', 'Review semantics, writing mode, cascade and owner before any conversion.', owner, [e], 'High', 'Minor', safe ? { property: approval.logicalProperty, value: e.value } : null);
|
|
46
|
+
}
|
|
47
|
+
else if (/^(margin|padding|inset|border-radius)$/.test(p)) {
|
|
48
|
+
const tokens = valueParser(v).nodes.filter(n => n.type !== 'space' && n.type !== 'comment');
|
|
49
|
+
const simple = tokens.every(n => n.type === 'word');
|
|
50
|
+
const words = tokens.map(n => valueParser.stringify(n));
|
|
51
|
+
const asymmetric = p === 'border-radius' ? words.length > 1 && new Set(words).size > 1 : words.length === 4 && words[1] !== words[3];
|
|
52
|
+
if (asymmetric || !simple && words.length > 0 && !/^[-\d.%pxemauto ]+$/.test(v))
|
|
53
|
+
add('RTL.CSS.SHORTHAND', 'Shorthand needs side/corner review', e, 'MANUAL_REVIEW', 'Shorthand may encode unequal physical sides, elliptical corners or unresolved values.', 'Review tokenized values and cascade; do not split functions or reverse corner order blindly.', owner, [e], simple ? 'High' : 'Medium');
|
|
54
|
+
}
|
|
55
|
+
else if ((p === 'transform' && /translateX\((?!0\))/i.test(v)) || (/^(transform-origin|background-position|box-shadow)$/.test(p) && /left|right|\d/.test(v)) || p === 'order' || p === 'flex-direction' && v === 'row-reverse' || /^grid-(column|row|area)/.test(p) && !/^auto$/.test(v) && !/^1\s*\/\s*-1$/.test(v))
|
|
56
|
+
add('RTL.GEOMETRY.ORDER', 'Directional geometry or explicit order', e, 'MANUAL_REVIEW', 'Transform/axis/order semantics require geometric and reading-order decisions.', 'Review spatial intent, focus order and companion positioning; no numeric sign reversal.', owner, [e], 'Medium');
|
|
57
|
+
}
|
|
58
|
+
// Generic syntax evidence: imports and JSX/data flow are inspected, never executed.
|
|
59
|
+
const themes = [], rtl = evidence.filter(e => e.mechanism === 'html-root' && e.property === 'dir' && e.value === 'rtl'), providers = [], caches = [], cacheChecks = new Map();
|
|
60
|
+
const entries = [...sources.entries()].filter(([p]) => /\.[jt]sx?$/.test(p));
|
|
61
|
+
for (const [path, text] of entries) {
|
|
62
|
+
const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, path.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
63
|
+
const runtimeProofs = analyzeRuntimeDirection(sf);
|
|
64
|
+
const provenThemes = new Set(runtimeProofs.flatMap(p => p.themeDirections));
|
|
65
|
+
const imports = new Map();
|
|
66
|
+
function importsVisit(n) { if (ts.isImportDeclaration(n) && ts.isStringLiteral(n.moduleSpecifier)) {
|
|
67
|
+
if (n.importClause?.name)
|
|
68
|
+
imports.set(n.importClause.name.text, n.moduleSpecifier.text);
|
|
69
|
+
if (n.importClause?.namedBindings && ts.isNamedImports(n.importClause.namedBindings))
|
|
70
|
+
for (const x of n.importClause.namedBindings.elements)
|
|
71
|
+
imports.set(x.name.text, n.moduleSpecifier.text + ':' + (x.propertyName?.text ?? x.name.text));
|
|
72
|
+
} ts.forEachChild(n, importsVisit); }
|
|
73
|
+
importsVisit(sf);
|
|
74
|
+
function ctx(n) { let p = n; while (p) {
|
|
75
|
+
if (ts.isFunctionDeclaration(p) && p.name)
|
|
76
|
+
return p.name.text;
|
|
77
|
+
if (ts.isVariableDeclaration(p) && ts.isIdentifier(p.name))
|
|
78
|
+
return p.name.text;
|
|
79
|
+
p = p.parent;
|
|
80
|
+
} return 'module'; }
|
|
81
|
+
function identity(n) { if (ts.isJsxText(n))
|
|
82
|
+
return 'JsxText:' + n.getText(sf).trim(); if (ts.isIdentifier(n) || ts.isStringLiteral(n) || ts.isNumericLiteral(n))
|
|
83
|
+
return ts.SyntaxKind[n.kind] + ':' + n.text; const parts = []; ts.forEachChild(n, x => { parts.push(identity(x)); }); return ts.SyntaxKind[n.kind] + '(' + parts.join('|') + ')'; }
|
|
84
|
+
function anchor(n, context = ctx(n)) { const a = { path, range: range(text, n.getStart(sf), n.end), original: n.getText(sf), context, id: hash(path + '|' + context + '|' + ts.SyntaxKind[n.kind] + '|' + identity(n)) }; return a; }
|
|
85
|
+
function isolated(n) { let p = n.parent; while (p && !ts.isFunctionDeclaration(p) && !ts.isVariableDeclaration(p)) {
|
|
86
|
+
if (ts.isJsxElement(p)) {
|
|
87
|
+
const o = p.openingElement;
|
|
88
|
+
if (o.tagName.getText(sf) === 'bdi' || o.attributes.properties.some(x => ts.isJsxAttribute(x) && x.name.getText(sf) === 'dir' && x.initializer && ts.isStringLiteral(x.initializer) && ['ltr', 'auto'].includes(x.initializer.text)))
|
|
89
|
+
return true;
|
|
90
|
+
const style = o.attributes.properties.find(x => ts.isJsxAttribute(x) && x.name.getText(sf) === 'style');
|
|
91
|
+
if (style && ts.isJsxAttribute(style) && style.initializer && ts.isJsxExpression(style.initializer) && style.initializer.expression && ts.isObjectLiteralExpression(style.initializer.expression) && style.initializer.expression.properties.some(x => ts.isPropertyAssignment(x) && x.name.getText(sf) === 'unicodeBidi' && ts.isStringLiteral(x.initializer) && x.initializer.text === 'isolate'))
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
p = p.parent;
|
|
95
|
+
} return false; }
|
|
96
|
+
function visit(n) {
|
|
97
|
+
for (const proof of runtimeProofs.filter(p => p.node === n)) {
|
|
98
|
+
const cacheAnchor = anchor(n, ctx(n) + (ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n) ? '/' + n.tagName.getText(sf) : ''));
|
|
99
|
+
caches.push(cacheAnchor);
|
|
100
|
+
if (!proof.supported)
|
|
101
|
+
cacheChecks.set(cacheAnchor, proof.reasons);
|
|
102
|
+
}
|
|
103
|
+
if (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && imports.get(n.expression.text)?.endsWith(':createTheme'))
|
|
104
|
+
for (const arg of n.arguments)
|
|
105
|
+
if (ts.isObjectLiteralExpression(arg))
|
|
106
|
+
for (const p of arg.properties)
|
|
107
|
+
if (ts.isPropertyAssignment(p) && p.name.getText(sf) === 'direction') {
|
|
108
|
+
if (ts.isStringLiteral(p.initializer) && p.initializer.text === 'ltr' && !provenThemes.has(p))
|
|
109
|
+
themes.push(anchor(p));
|
|
110
|
+
else if (!ts.isStringLiteral(p.initializer)) {
|
|
111
|
+
const a = anchor(p);
|
|
112
|
+
diagnostics.push({ path, range: a.range, code: 'RUNTIME_DIRECTION_UNKNOWN', message: 'Theme direction expression not statically resolved.', impact: 'DIRECTIONAL_UNSUPPORTED', blocking: true, rationale: 'Runtime direction cannot be safely correlated.' });
|
|
113
|
+
add('RTL.RUNTIME.DIRECTION_UNKNOWN', 'Dynamic runtime direction requires review', a, 'RUNTIME_CONFIG', 'Direction is supplied by an unresolved expression.', 'Review document/theme/cache synchronization without evaluating application code.', policy.generatedStyleOwner ?? 'unknown', [], 'Low');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.EqualsToken && ts.isPropertyAccessExpression(n.left) && n.left.getText(sf) === 'document.documentElement.dir') {
|
|
117
|
+
function options(x) { if (ts.isStringLiteral(x))
|
|
118
|
+
return [x.text]; if (ts.isParenthesizedExpression(x) || ts.isAsExpression(x))
|
|
119
|
+
return options(x.expression); if (ts.isConditionalExpression(x)) {
|
|
120
|
+
const a = options(x.whenTrue), b = options(x.whenFalse);
|
|
121
|
+
return a && b ? [...a, ...b] : undefined;
|
|
122
|
+
} return undefined; }
|
|
123
|
+
const values = options(n.right), a = anchor(n);
|
|
124
|
+
if (values?.includes('rtl'))
|
|
125
|
+
rtl.push(a);
|
|
126
|
+
if (!values) {
|
|
127
|
+
diagnostics.push({ path, range: a.range, code: 'RUNTIME_DIRECTION_UNKNOWN', message: 'Document direction expression not statically resolved.', impact: 'DIRECTIONAL_UNSUPPORTED', blocking: true, rationale: 'Potential output direction cannot be correlated safely.' });
|
|
128
|
+
add('RTL.RUNTIME.DIRECTION_UNKNOWN', 'Dynamic document direction requires review', a, 'RUNTIME_CONFIG', 'Direction output comes from an unresolved expression.', 'Review output values and runtime synchronization; do not infer direction from strings in a condition.', 'document-runtime', [], 'Low');
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n)) {
|
|
132
|
+
const name = n.tagName.getText(sf), binding = imports.get(name) ?? '';
|
|
133
|
+
const a = () => anchor(n, ctx(n) + '/' + name);
|
|
134
|
+
if (binding.endsWith(':ThemeProvider'))
|
|
135
|
+
providers.push(a());
|
|
136
|
+
if (binding.startsWith('@mui/icons-material') && /[/:](ArrowForward|ArrowBack|ChevronLeft|ChevronRight|KeyboardArrowLeft|KeyboardArrowRight|NavigateBefore|NavigateNext)(:|$)/.test(binding))
|
|
137
|
+
add('RTL.ICON.PROGRESSION', 'Directional icon requires semantic review', a(), 'MANUAL_REVIEW', 'Imported directional icon renders in JSX; navigation meaning and appropriate orientation need review.', 'Distinguish progression from trends/external-link conventions; coordinate MUI-owned roles before mirroring.', 'custom-icon', [], 'Medium');
|
|
138
|
+
if (binding === '@mui/material:Pagination')
|
|
139
|
+
add('RTL.RUNTIME.PAGINATION', 'Pagination direction depends on MUI theme', a(), 'RUNTIME_CONFIG', 'MUI supplies directional pagination roles through theme context, independently of HTML flow.', 'Verify synchronized theme/cache/document setup before adding custom icon swaps.', policy.generatedStyleOwner ?? 'unknown', [], 'Medium');
|
|
140
|
+
if (binding === '@mui/material:TableCell' && !n.attributes.properties.some(p => ts.isJsxAttribute(p) && p.name.getText(sf) === 'align'))
|
|
141
|
+
add('RTL.TABLE.ALIGNMENT', 'Table cell has no explicit alignment policy', a(), 'MANUAL_REVIEW', 'Generated default alignment and content-specific alignment policy are not declared at this cell.', 'Review text, numeric and token alignment with runtime configuration; absence of align alone is not a bug.', policy.generatedStyleOwner ?? 'unknown', [], 'Medium');
|
|
142
|
+
if (binding === '@mui/material:TextField')
|
|
143
|
+
add('RTL.FORM.DIRECTION', 'Field geometry delegates to runtime styling', a(), 'RUNTIME_CONFIG', 'MUI field labels/notches/helpers depend on theme and generated style processing.', 'Verify document/theme/cache coordination and native input behavior; do not patch vendor geometry.', policy.generatedStyleOwner ?? 'unknown', [], 'Medium');
|
|
144
|
+
if (name === 'svg' && ts.isJsxElement(n.parent)) {
|
|
145
|
+
const parent = n.parent;
|
|
146
|
+
let host = parent.parent;
|
|
147
|
+
if (!ts.isJsxElement(host))
|
|
148
|
+
host = parent;
|
|
149
|
+
const labels = [];
|
|
150
|
+
function check(x) { if (ts.isJsxAttribute(x) && x.name.getText(sf) === 'className' && x.initializer && ts.isStringLiteral(x.initializer)) {
|
|
151
|
+
const classNames = x.initializer.text.split(/\s+/);
|
|
152
|
+
for (const e of evidence)
|
|
153
|
+
if (e.mechanism === 'css' && classNames.some(c => e.context.endsWith('/.' + c)) && e.property === 'display' && e.value === 'flex')
|
|
154
|
+
labels.push(x);
|
|
155
|
+
} ts.forEachChild(x, check); }
|
|
156
|
+
check(host);
|
|
157
|
+
if (labels.length && parent.getText(sf).includes('<path')) {
|
|
158
|
+
const ar = a();
|
|
159
|
+
const refs = evidence.filter(e => labels.some(l => ts.isJsxAttribute(l) && l.initializer && ts.isStringLiteral(l.initializer) && e.context.endsWith('/.' + l.initializer.text)));
|
|
160
|
+
add('RTL.CHART.LABEL_FLOW', 'SVG geometry with separate flex labels', ar, 'MANUAL_REVIEW', 'Fixed SVG geometry and separate HTML flex labels can respond differently to document direction.', 'Review chronology, axis gutters, labels/data correspondence and accessible description together.', 'manual-chart', refs, 'Medium', 'Major');
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const classAttr = n.attributes.properties.find(p => ts.isJsxAttribute(p) && p.name.getText(sf) === 'className');
|
|
164
|
+
if (classAttr && ts.isJsxAttribute(classAttr) && classAttr.initializer && ts.isStringLiteral(classAttr.initializer)) {
|
|
165
|
+
const role = policy.roles.find(r => r.kind === 'brand' && r.path === path && classAttr.initializer && ts.isStringLiteral(classAttr.initializer) && classAttr.initializer.text.split(/\s+/).includes(r.className));
|
|
166
|
+
if (role && !n.attributes.properties.some(p => ts.isJsxAttribute(p) && p.name.getText(sf) === 'dir')) {
|
|
167
|
+
const refs = evidence.filter(e => e.mechanism === 'css' && e.context.endsWith('/.' + role.className) && e.property === 'display' && e.value === 'flex');
|
|
168
|
+
if (refs.length)
|
|
169
|
+
add('RTL.BRAND.ISLAND', 'Brand flex composition has no explicit direction island', a(), 'MANUAL_REVIEW', 'Reviewed brand role uses inherited flex flow with separate visual children and no local direction contract.', 'Preserve the approved wordmark composition as a reviewed island; do not mirror glyphs.', 'manual-brand', refs, 'Medium');
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if ((ts.isJsxText(n) && /[→←]/.test(n.getText(sf))) || (ts.isStringLiteral(n) && /[→←]/.test(n.text) && (ts.isCallExpression(n.parent) || ts.isJsxExpression(n.parent)) && (() => { let p = n.parent; while (p) {
|
|
174
|
+
if (ts.isJsxExpression(p))
|
|
175
|
+
return true;
|
|
176
|
+
p = p.parent;
|
|
177
|
+
} return false; })()))
|
|
178
|
+
add('RTL.ICON.LITERAL', 'Literal directional arrow in rendered-copy call', anchor(n), 'MANUAL_REVIEW', 'A literal arrow occurs in a copy/function call; its progression meaning and translated rendering need review.', 'Review copy and navigation semantics rather than replacing every arrow.', 'custom-copy', [], 'Medium');
|
|
179
|
+
if (ts.isJsxExpression(n) && n.expression && !isolated(n)) {
|
|
180
|
+
let candidate = false;
|
|
181
|
+
function token(x) { if (ts.isPropertyAccessExpression(x) && ['name', 'address', 'email', 'id'].includes(x.name.text))
|
|
182
|
+
candidate = true; if (ts.isCallExpression(x) && ts.isIdentifier(x.expression) && imports.get(x.expression.text)?.endsWith(':money'))
|
|
183
|
+
candidate = true; ts.forEachChild(x, token); }
|
|
184
|
+
token(n.expression);
|
|
185
|
+
// Only text children, not event handlers, attributes or JSX render branches.
|
|
186
|
+
const direct = ts.isPropertyAccessExpression(n.expression) && ['name', 'address', 'email', 'id'].includes(n.expression.name.text) || ts.isCallExpression(n.expression) && ts.isIdentifier(n.expression.expression) && imports.get(n.expression.expression.text)?.endsWith(':money');
|
|
187
|
+
if (candidate && direct && (ts.isJsxElement(n.parent) || ts.isJsxFragment(n.parent)) && !ts.isJsxElement(n.expression) && !ts.isConditionalExpression(n.expression) && !ts.isBinaryExpression(n.expression))
|
|
188
|
+
add('RTL.BIDI.ISOLATION', 'Unisolated token/content text sink', anchor(n), 'MANUAL_REVIEW', 'Known-name/token expression is rendered without an explicit bdi/dir ancestor; actual run direction and punctuation remain data-dependent.', 'Review opposite-direction token isolation or auto-direction for human text; preserve canonical storage and copying.', 'manual-content', [], 'Medium');
|
|
189
|
+
}
|
|
190
|
+
if (ts.isNewExpression(n) && n.expression.getText(sf) === 'Intl.NumberFormat' && n.arguments?.[0] && ts.isStringLiteral(n.arguments[0]))
|
|
191
|
+
add('RTL.RUNTIME.LOCALE', 'Fixed locale formatter', anchor(n), 'RUNTIME_CONFIG', 'Formatting uses a fixed display locale; direction and locale formatting are separate contracts.', 'Approve locale display policy separately from canonical currency/date values and bidi isolation.', 'locale-runtime', [], 'High');
|
|
192
|
+
ts.forEachChild(n, visit);
|
|
193
|
+
}
|
|
194
|
+
visit(sf);
|
|
195
|
+
}
|
|
196
|
+
for (const e of evidence.filter(e => e.mechanism === 'html-root' && e.property === 'dir'))
|
|
197
|
+
add('RTL.DOCUMENT.INITIAL', 'Initial HTML direction', e, 'INFORMATIONAL', 'Initial HTML direction is a source fact, not the client runtime direction.', 'Preserve approved default English markup; evaluate runtime direction separately.', 'document-runtime', [e], 'High', 'Info');
|
|
198
|
+
for (const a of rtl.filter(a => a.context !== 'html'))
|
|
199
|
+
add('RTL.DOCUMENT.RUNTIME', 'Document-level RTL assignment exists', a, 'INFORMATIONAL', 'Document root direction can switch to RTL; body-mounted portals inherit root direction unless overridden.', 'Verify portal computed direction independently; do not report a wrapper-only portal failure.', 'document-runtime', [], 'High', 'Info');
|
|
200
|
+
if (rtl.length && themes.length) {
|
|
201
|
+
for (const a of themes) {
|
|
202
|
+
const f = add('RTL.RUNTIME.MISMATCH', 'RTL document capability with fixed LTR theme', a, 'RUNTIME_CONFIG', 'Analyzed source assigns document RTL while createTheme direction is fixed LTR. These are separate direction channels.', 'Review reachable provider synchronization; MUI theme alone does not rewrite generated physical styles.', policy.generatedStyleOwner ?? 'unknown', [], 'High', 'Major');
|
|
203
|
+
f.relatedLocations.push(...rtl.map(a => ({ path: a.path, range: a.range })));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (rtl.length && providers.length && !caches.length) {
|
|
207
|
+
for (const a of providers)
|
|
208
|
+
add('RTL.RUNTIME.CACHE', 'No owned Emotion cache found in analyzed provider scope', a, 'RUNTIME_CONFIG', 'The analyzed provider/import scope contains no CacheProvider despite document RTL capability; transitive cache packages do not establish configured RTL processing.', 'Review compatible LTR/RTL style processing and custom-style ownership; absence is a scoped inference.', policy.generatedStyleOwner ?? 'unknown', [], 'Medium', 'Minor', null, 'External providers, re-exported cache wrappers and unscanned configuration may invalidate this absence inference.');
|
|
209
|
+
}
|
|
210
|
+
for (const [a, reasons] of cacheChecks) {
|
|
211
|
+
diagnostics.push({ path: a.path, range: a.range, code: 'CACHE_CONFIGURATION_UNRESOLVED', message: 'CacheProvider configuration unresolved: ' + reasons.join(' '), impact: 'DIRECTIONAL_UNSUPPORTED', blocking: true, rationale: 'Cache presence alone cannot establish generated RTL processing or ownership.' });
|
|
212
|
+
add('RTL.RUNTIME.CACHE_UNVERIFIED', 'Emotion cache direction pipeline needs verification', a, 'RUNTIME_CONFIG', 'CacheProvider presence does not prove RTL plugin compatibility or exemption behavior.', 'Review cache creation/plugins and ownership as a separate configuration contract.', policy.generatedStyleOwner ?? 'unknown', [], 'Low');
|
|
213
|
+
}
|
|
214
|
+
return findings.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.range.start.offset - b.range.start.offset || a.ruleId.localeCompare(b.ruleId, 'en'));
|
|
215
|
+
}
|
|
@@ -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
|
+
}
|