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.
- package/LICENSE +21 -0
- package/README.md +53 -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 +38 -0
- package/dist/structured-markdown.js +36 -0
- package/dist/tailwind.js +21 -0
- package/dist/typescript.js +191 -0
- package/package.json +26 -4
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { approvedPreviewForSource } from './preview-manifest.js';
|
|
2
|
+
import { classifyEligibility } from './eligibility.js';
|
|
3
|
+
export const severityDisplayLabel = (severity) => ({ Major: 'High Priority', Minor: 'Low Priority', Info: 'Informational' }[severity] ?? severity);
|
|
4
|
+
const sort = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
5
|
+
const breakdown = (values) => { const counts = new Map(); for (const value of values)
|
|
6
|
+
counts.set(value, (counts.get(value) ?? 0) + 1); return [...counts].sort((a, b) => sort(a[0], b[0])).map(([name, count]) => ({ name, count })); };
|
|
7
|
+
const findingSort = (a, b) => sort(a.path, b.path) || a.line - b.line || a.column - b.column || sort(a.id, b.id);
|
|
8
|
+
function mapFinding(f, ref, sourceText) { const eligibility = classifyEligibility(f, !ref?.missingEvidenceIds.length, sourceText); const reviewClassification = eligibility.eligibility === 'AUTOMATED_ELIGIBLE' ? 'Automated / Codemod Eligible' : eligibility.eligibility === 'ASSISTED' ? 'Assisted' : 'Manual'; return { id: f.id, ruleId: f.ruleId, ruleVersion: f.ruleVersion, category: f.category, severity: f.severity, confidence: f.confidence, title: f.title, sourceMechanism: f.sourceMechanism, path: f.path, line: f.range.start.line, column: f.range.start.column, owner: f.ownership, applications: f.applications.slice().sort(sort), rationale: f.rationale, treatment: f.treatment, limitation: f.limitation, evidenceIds: f.evidenceIds.slice(), missingEvidenceIds: ref?.missingEvidenceIds.slice() ?? [], duplicateEvidenceIds: ref?.duplicateEvidenceIds.slice() ?? [], relatedLocations: f.relatedLocations.slice().sort((a, b) => sort(a.path, b.path) || a.range.start.offset - b.range.start.offset).map(x => `${x.path}:${x.range.start.line}:${x.range.start.column}`), issueIds: f.issueIds.slice().sort(sort), suggestion: f.suggestion ? { property: f.suggestion.property, value: f.suggestion.value } : null, previewMappingId: approvedPreviewForSource(f.path)?.id ?? null, reviewStatus: f.id === 'RTL.ICON.PROGRESSION:237172da962fe4d0605ddd83' ? 'Needs Manual Investigation' : 'Not Reviewed', reviewClassification, eligibility: eligibility.eligibility, eligibilityReason: eligibility.reason, eligibilityEvidence: eligibility.evidence, eligibilityTransformationId: eligibility.transformationId, eligibilityBlockers: eligibility.blockers, ...(f.exceptionReason ? { exceptionReason: f.exceptionReason } : {}), ...(f.originalCategory ? { originalCategory: f.originalCategory } : {}) }; }
|
|
9
|
+
export function toDashboardData(report, snippets) { const refs = new Map(report.evidenceReferences.map(ref => [ref.findingId, ref])); const findings = report.findings.slice().sort((a, b) => sort(a.path, b.path) || a.range.start.offset - b.range.start.offset || sort(a.id, b.id)).map(f => mapFinding(f, refs.get(f.id), snippets?.sourceTextByPath?.[f.path])); const actionable = findings.filter(f => !['INFORMATIONAL', 'INTENTIONAL_LTR'].includes(f.category)); const queue = { critical: [], major: [], minor: [], runtimeConfig: [], informational: [], intentionalLtr: [] }; for (const f of findings) {
|
|
10
|
+
const key = f.category === 'INFORMATIONAL' ? 'informational' : f.category === 'INTENTIONAL_LTR' ? 'intentionalLtr' : f.category === 'RUNTIME_CONFIG' ? 'runtimeConfig' : f.severity.toLowerCase();
|
|
11
|
+
(queue[key] ??= []).push(f);
|
|
12
|
+
} for (const values of Object.values(queue))
|
|
13
|
+
values.sort(findingSort); const byPath = new Map(); for (const f of findings)
|
|
14
|
+
byPath.set(f.path, [...(byPath.get(f.path) ?? []), f]); const root = { name: 'Workspace', path: '', folders: new Map(), files: [], findingCount: findings.length }; for (const [path, fs] of byPath) {
|
|
15
|
+
const parts = path.split('/');
|
|
16
|
+
let folder = root;
|
|
17
|
+
parts.slice(0, -1).forEach((name, index) => { const childPath = parts.slice(0, index + 1).join('/'); let child = folder.folders.get(name); if (!child) {
|
|
18
|
+
child = { name, path: childPath, folders: new Map(), files: [], findingCount: 0 };
|
|
19
|
+
folder.folders.set(name, child);
|
|
20
|
+
} child.findingCount += fs.length; folder = child; });
|
|
21
|
+
folder.files.push({ name: parts.at(-1), path, findingCount: fs.length, findingIds: fs.map(f => f.id).sort(sort) });
|
|
22
|
+
} const freeze = (f) => ({ name: f.name, path: f.path, findingCount: f.findingCount, folders: [...f.folders.values()].sort((a, b) => sort(a.name, b.name)).map(freeze), files: f.files.sort((a, b) => sort(a.name, b.name) || sort(a.path, b.path)) }); const direct = findings.flatMap(f => f.applications); const sharedOwnership = null; const sharedImpact = null; const unresolved = null; const refsList = [...refs.values()]; return { viewModelVersion: 1, kind: report.kind, schemaVersion: report.schemaVersion, inputDigest: report.inputDigest, policyDigest: report.policyDigest, complete: report.complete, filesAnalyzed: report.files.length, skippedPaths: report.skipped.slice().sort(sort), findings: findings.length, actionableFindings: actionable.length, uniqueAffectedFiles: report.metrics.uniqueAffectedFiles, diagnostics: report.diagnostics.length, blockingDiagnostics: report.diagnostics.filter(d => d.blocking).length, breakdowns: { severity: breakdown(findings.map(f => f.severity)), category: breakdown(findings.map(f => f.category)), rule: breakdown(findings.map(f => f.ruleId)), confidence: breakdown(findings.map(f => f.confidence)), application: breakdown(direct) }, files: breakdown(findings.map(f => f.path)), owners: breakdown(findings.map(f => f.owner)), warnings: { unresolvedReachability: findings.filter(f => f.applications.length === 0).length, missingEvidence: refsList.reduce((n, r) => n + r.missingEvidenceIds.length, 0), duplicateEvidence: refsList.reduce((n, r) => n + r.duplicateEvidenceIds.length, 0) }, diagnosticsDetail: report.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 => ({ path: d.path, line: d.range.start.line, column: d.range.start.column, code: d.code, impact: d.impact ?? 'none', blocking: Boolean(d.blocking), message: d.message, rationale: d.rationale ?? '' })), queue, sourceEmbeddingEnabled: Boolean(snippets), explorer: { root: freeze(root), initialFindingId: actionable[0]?.id ?? findings[0]?.id ?? null }, scopeBreakdown: { directApplications: breakdown(direct), sharedLibraryOwnership: sharedOwnership, sharedLibraryImpact: sharedImpact, unresolvedReachability: unresolved }, ...(snippets ? { sourcePrivacyWarning: 'Embedded source may contain sensitive information; review and protect this dashboard accordingly.', sourceSnippets: { sources: snippets.sources, findings: snippets.findings, embeddedBytes: snippets.embeddedBytes } } : {}) }; }
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { dashboardClientSource } from './dashboard-client.js';
|
|
2
|
+
import { severityDisplayLabel, toDashboardData } from './dashboard-data.js';
|
|
3
|
+
const escapeJson = (v) => v.replace(/[<>&\u2028\u2029]/g, c => ({ '<': '\\u003c', '>': '\\u003e', '&': '\\u0026', '\u2028': '\\u2028', '\u2029': '\\u2029' }[c] ?? c));
|
|
4
|
+
const css = `:root{
|
|
5
|
+
color-scheme:dark;
|
|
6
|
+
--bg:#060d1a;--nav:#0a1426;--surface:#0e1a2e;--surface-hi:#14243c;--surface-soft:#101f35;
|
|
7
|
+
--line:#263c5d;--line-soft:#1c304e;--text:#f4f7ff;--muted:#9aaac1;--dim:#70819b;
|
|
8
|
+
--purple:#9a63ff;--purple-deep:#4e1d9d;--purple-glow:#b989ff;--red:#ff4564;--amber:#f4b72f;--blue:#42a4ff;--green:#35d995;
|
|
9
|
+
--code:#040a13;--focus:#c9a9ff;--r-sm:8px;--r-md:12px;--r-lg:15px;
|
|
10
|
+
font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif
|
|
11
|
+
}
|
|
12
|
+
:where(.app){width:100%;max-width:100vw;min-width:0}:where(.top),:where(.nav),:where(.tools),:where(.search-wrap){min-width:0}
|
|
13
|
+
.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media(prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important;transition-duration:.01ms!important;animation-duration:.01ms!important}}
|
|
14
|
+
:root{--space-1:4px;--space-2:8px;--space-3:12px;--space-4:16px;--space-5:20px;--space-6:24px;--text-sm:12px;--text-md:14px;--text-lg:18px;--surface-raised:#14243a;--surface-panel:#0f1d31;--border-strong:#395477;--status-ok:#3fe0a0;--status-warn:#ffd166;--status-bad:#ff7188}.card,.scope,.project{background:var(--surface-raised);box-shadow:0 4px 14px #0003}.workspace{background:var(--border-strong);box-shadow:0 8px 24px #0004}.head{font-size:var(--text-sm);color:#c2cee0}.finding strong{font-size:var(--text-md);font-weight:750}.finding small,.file,.meta,.filter-control,.filter-summary{font-size:var(--text-sm)}.details{font-size:var(--text-md)}.details p,.review-panel p,.review-workspace p,.validation-panel p,.audit-history p{color:#c0ccdd}.details h3{font-size:var(--text-sm);color:#aebed3}.actions button,.finding-filters>button{font-size:var(--text-sm);min-height:38px}.actions button{background:#5f35b5;border-color:#a98ae8;box-shadow:none}.actions button:hover:not(:disabled){background:#7447cf}.actions button:disabled{opacity:.48}.review-state,.apply-ready,.validation-state{color:var(--status-ok);font-weight:750}.review-blocked,.apply-blocked,.preview-unavailable{color:var(--status-warn)}.review-diff{padding:var(--space-4);border:1px solid var(--border-strong);border-radius:var(--r-sm);background:#070e19;color:#e9eef8;line-height:1.55;white-space:pre-wrap;overflow:auto}.screenshot-preview{display:inline-flex;vertical-align:top;flex-direction:column;gap:var(--space-2);width:min(220px,100%);margin:var(--space-2)}.screenshot-preview img{border:1px solid var(--border-strong);border-radius:var(--r-sm);background:#080f1b}.screenshot-preview figcaption{font-size:var(--text-sm);color:#c0ccdd}.audit-history details,.archived-evidence details,.validation-panel details{border:1px solid var(--line);border-radius:var(--r-sm);margin:var(--space-2) 0;background:#132238}.audit-history summary,.archived-evidence summary,.validation-panel summary{padding:var(--space-3);font-size:var(--text-sm);font-weight:750}.audit-grid,.evidence-grid{gap:var(--space-2);font-size:var(--text-sm)}.line.hit{box-shadow:inset 3px 0 #ffd166}.mobile-back{background:#29466f!important;border-color:#6d8fbd!important}
|
|
15
|
+
@media(max-width:800px){.app{grid-template-rows:auto auto auto auto 1fr}.top{flex-wrap:wrap;min-height:118px;padding:10px 14px}.brand{min-width:0;flex:1;font-size:17px}.nav{order:3;width:100%;overflow:auto}.nav button{min-height:42px}.tools{width:100%;margin-left:0}.tools input{flex:1;width:auto}.finding-filters{display:flex;padding:0 10px 10px;align-items:stretch}.filter-control{flex:1 1 calc(50% - 8px);min-width:140px}.filter-control select,.finding-filters>button{width:100%;min-height:44px}.finding-filters>button{flex:1 1 100%}.filter-summary{width:100%;margin:0}.summary{grid-template-columns:repeat(2,1fr);padding:10px}.scope-row{padding:0 10px 10px}.scope{align-items:stretch;flex-wrap:wrap}.scope select{min-width:100%;min-height:44px}.projects{display:none}.workspace{display:flex;flex-direction:column;margin:0 10px 10px;border-radius:12px}.workspace>.pane:nth-child(1),.workspace>.pane:nth-child(2){display:none}.workspace>.pane:nth-child(3){order:1;height:420px}.workspace>.pane:nth-child(5){order:2;height:auto;min-height:520px}.workspace>.pane:nth-child(4){order:3;height:420px}.pane{width:100%}}
|
|
16
|
+
*{box-sizing:border-box}html,body{min-width:0;overflow-x:hidden}body{margin:0;background:radial-gradient(900px 420px at 52% -12%,#1b3155 0%,var(--bg) 64%);color:var(--text);line-height:1.4}button,input,select{font:inherit;max-width:100%}button{cursor:pointer}button:disabled{cursor:not-allowed}button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--focus);outline-offset:2px}
|
|
17
|
+
.app{min-height:100vh;display:grid;grid-template-rows:72px auto auto 1fr;gap:0}.top{display:flex;align-items:center;gap:22px;padding:10px 26px;border-bottom:1px solid var(--line-soft);background:linear-gradient(180deg,#0d192c,#091426);box-shadow:0 8px 26px #0005}.brand{position:relative;min-width:360px;padding-left:51px;font-size:20px;font-weight:850;letter-spacing:-.02em;white-space:nowrap}.brand:before{content:'RTL';position:absolute;left:0;top:-1px;display:grid;place-items:center;width:39px;height:39px;border-radius:10px;background:linear-gradient(145deg,#a855f7,#4c1d95);box-shadow:0 0 22px #8b5cf655;color:#fff;letter-spacing:0}.brand small{display:block;margin-top:2px;color:var(--muted);font-size:11px;font-weight:500;letter-spacing:0}.nav{display:flex;align-items:center;gap:7px}.nav button{border:1px solid transparent;border-radius:10px;background:transparent;color:#b0bdd0;padding:11px 15px;font-size:14px;font-weight:800;white-space:nowrap;transition:.15s ease}.nav button:not(:disabled):hover{background:#1b2b47;color:#fff;border-color:var(--line)}.nav .active{background:linear-gradient(180deg,#8447ed,#4e1da0);color:#fff;border-color:#bf92ff;box-shadow:0 0 24px #8b5cf677,inset 0 1px #e2cdff}.nav .disabled{opacity:.42}.tools{display:flex;align-items:center;gap:12px;margin-left:auto}.search-wrap{display:flex;align-items:center;border:1px solid #334b70;border-radius:10px;background:#07111f;padding:0 10px;box-shadow:inset 0 1px #ffffff08}.search-wrap span{color:var(--muted);font-size:19px}.tools input{width:190px;border:0;outline:0;background:transparent;color:var(--text);padding:10px 7px}.tools input::placeholder{color:#8090a7}.status{color:var(--green);font-size:11px;font-weight:900;letter-spacing:.04em;white-space:nowrap}.status.warn{color:var(--amber)}
|
|
18
|
+
.summary{display:grid;grid-template-columns:1.35fr .85fr .9fr .9fr .9fr .95fr 1.75fr;gap:10px;padding:14px 18px 12px}.card{min-height:82px;border:1px solid var(--line);border-radius:var(--r-md);background:linear-gradient(145deg,#152640,#0d182b);padding:13px 15px;box-shadow:0 8px 26px #0003,inset 0 1px #ffffff08}.workspace-card{display:flex;align-items:center;gap:13px;position:relative}.workspace-icon{font-size:32px;color:#bd77ff;text-shadow:0 0 16px #9a63ff99}.workspace-card strong{font-size:18px}.workspace-card span{display:block}.workspace-secondary{display:block!important;margin-top:3px;color:var(--dim)!important;font-size:10px!important}.workspace-status{display:inline-block!important;margin-top:5px;border-radius:99px;padding:3px 9px;background:#0d6a4b;color:#d9fff0!important;font-size:10px!important;font-weight:800}.card strong{display:block;font-size:27px;line-height:1.05;letter-spacing:-.02em}.card span{color:var(--muted);font-size:11px}.card.green{border-color:#197c55;background:linear-gradient(145deg,#12372f,#0d1d2b)}.card.blue{border-color:#225f99}.card.red{border-color:#933047;background:linear-gradient(145deg,#341629,#111a2b)}.severity-card{min-height:82px}.severity-card strong{font-size:24px}.severity-card span{font-size:11px}.severity-card.red{border-color:#8b2945}.severity-card.amber{border-color:#836020;background:linear-gradient(145deg,#342a1b,#151e2c)}.severity-card.blue{border-color:#225d96;background:linear-gradient(145deg,#122d4c,#101d2f)}.severity-chart{display:flex;align-items:center;justify-content:center;gap:18px;padding:8px 14px}.donut{position:relative;width:82px;height:82px;flex:0 0 auto;border-radius:50%;background:conic-gradient(var(--red) 0 var(--major),var(--amber) var(--major) var(--minor),var(--blue) var(--minor) 100%);display:grid;place-items:center;box-shadow:0 0 20px #0006}.donut:after{content:'';position:absolute;width:53px;height:53px;border-radius:50%;background:#101d31;box-shadow:inset 0 0 0 1px #ffffff0b}.legend{font-size:11px;line-height:1.95;min-width:125px}.legend i{display:inline-block;width:9px;height:9px;border-radius:50%;margin-right:7px}.legend .r{background:var(--red);box-shadow:0 0 7px var(--red)}.legend .a{background:var(--amber);box-shadow:0 0 7px var(--amber)}.legend .b{background:var(--blue);box-shadow:0 0 7px var(--blue)}
|
|
19
|
+
.scope-row{display:grid;grid-template-columns:1.1fr 2.2fr;gap:10px;padding:0 18px 13px}.scope,.project{border:1px solid var(--line);border-radius:var(--r-md);background:linear-gradient(145deg,#14243b,#0d182a);box-shadow:0 7px 22px #0003}.scope{display:flex;align-items:center;gap:14px;padding:12px 15px}.scope-icon{font-size:29px;color:#c07bff;text-shadow:0 0 12px #9a63ff88}.scope h2{margin:0;font-size:16px}.scope p{margin:2px 0;color:var(--muted);font-size:11px}.scope select{flex:1;min-width:190px;background:#07111f;color:var(--text);border:1px solid var(--purple);border-radius:9px;padding:10px;box-shadow:0 0 0 2px #8b5cf622}.projects{display:flex;gap:8px;overflow:auto}.project{min-width:145px;padding:10px 13px;border-color:transparent;color:var(--text);text-align:left}.project:not(:disabled):hover{border-color:#8558df}.project.active{background:linear-gradient(180deg,#7137c9,#421b8c);border-color:#b99cff;box-shadow:0 0 18px #8b5cf655}.project strong,.project span{display:block}.project strong{font-size:13px}.project span{color:var(--muted);font-size:10px}.project:disabled{opacity:.58}
|
|
20
|
+
.workspace{min-height:0;display:grid;grid-template-columns:205px 235px 300px minmax(430px,1fr) 320px;gap:1px;background:var(--line);margin:0 18px 17px;border:1px solid var(--line);border-radius:var(--r-lg);overflow:hidden;box-shadow:0 12px 34px #0004}.pane{min-width:0;min-height:0;background:var(--surface)}.head{height:45px;padding:0 14px;display:flex;align-items:center;background:linear-gradient(180deg,#172840,#142239);border-bottom:1px solid var(--line);font-size:10px;font-weight:900;letter-spacing:.1em;color:#a7b5c9}.scroll{height:calc(100% - 45px);overflow:auto}.side{padding:10px;background:linear-gradient(180deg,#122139,#0e1b2e)}.side button{display:block;width:100%;margin-bottom:5px;padding:11px;border:1px solid transparent;border-radius:9px;background:transparent;color:#b6c2d4;text-align:left;font-size:13px;font-weight:750}.side button.active{background:linear-gradient(180deg,#7137c9,#421b8c);color:#fff;border-color:#bd91ff;box-shadow:0 0 15px #8b5cf655}.side button.disabled{opacity:.35}.tree{padding:9px}.folder>summary{cursor:pointer;padding:6px;color:#aebbd0;list-style:none;font-weight:800}.folder>summary::-webkit-details-marker{display:none}.folder>summary:before{content:'▸';display:inline-block;width:17px;color:#8799b3}.folder[open]>summary:before{content:'▾'}.file,.finding{display:flex;width:100%;gap:8px;align-items:center;text-align:left;background:transparent;color:var(--text);border:1px solid transparent;border-radius:8px;padding:8px}.file:hover,.file.selected,.finding:hover,.finding.selected{background:#29466f;border-color:#9562ed;box-shadow:inset 3px 0 #c098ff}.file{font:12px ui-monospace,SFMono-Regular,Menlo,monospace}.count{margin-left:auto;color:#9fb0c8}.finding-list{padding:9px}.finding{display:block;margin-bottom:8px}.finding strong{display:block;font-size:13px;line-height:1.28}.finding small{display:block;margin-top:5px;color:var(--muted);font-size:10px}.code{height:calc(100% - 45px);display:flex;flex-direction:column}.meta{padding:10px 14px;border-bottom:1px solid var(--line);color:#aab8cc;background:#0c1829;font:12px ui-monospace,SFMono-Regular,Menlo,monospace}.code-scroll{overflow:auto;flex:1;background:var(--code);padding:17px 0}.line{display:grid;grid-template-columns:58px 1fr;font:13px/1.8 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre;color:#e6ebf5}.no{color:#657892;text-align:right;padding-right:15px;border-right:1px solid #1c2d45}.text{padding:0 17px}.line.hit{background:linear-gradient(90deg,#4c3716,#3d2d15 75%,transparent);box-shadow:inset 3px 0 #e5a82f}.details{padding:18px;background:linear-gradient(180deg,#101e32,#0d1829)}.details h2{margin:0 0 15px;font-size:19px;line-height:1.25}.details h3{margin:17px 0 4px;color:#91a2ba;font-size:10px;text-transform:uppercase;letter-spacing:.08em}.actions{display:flex;gap:7px;flex-wrap:wrap}.actions button{background:linear-gradient(180deg,#7440d1,#4f209c);border:1px solid #a477f5;border-radius:7px;color:#fff;padding:8px 10px;font-size:11px;font-weight:750;box-shadow:0 5px 12px #0003}.empty{padding:22px;color:var(--muted)}.rtl-value{unicode-bidi:isolate;direction:auto}
|
|
21
|
+
.finding-filters{display:flex;align-items:end;gap:8px;flex-wrap:wrap;min-width:0;padding:0 18px 12px}.finding-filters strong{width:100%;font-size:12px;color:#c5d2e6}.filter-control{display:flex;flex-direction:column;gap:4px;min-width:0;color:var(--muted);font-size:10px;font-weight:750}.filter-control select,.finding-filters>button{min-width:0;min-height:38px;background:#07111f;color:var(--text);border:1px solid var(--line);border-radius:8px;padding:7px 9px}.filter-control select{max-width:100%}.finding-filters>button{color:#fff;background:#253b5d}.filter-summary{align-self:center;color:var(--muted);font-size:10px;margin-left:auto;overflow-wrap:anywhere}.mobile-back{display:none}
|
|
22
|
+
@media(max-width:1450px){.brand{min-width:300px}.nav button{padding:10px 10px}.summary{grid-template-columns:1.3fr .8fr .85fr .85fr .85fr .9fr 1.5fr}.workspace{grid-template-columns:185px 215px 270px minmax(360px,1fr) 290px}}
|
|
23
|
+
@media(max-width:1350px){.workspace{grid-template-columns:185px 270px minmax(320px,1fr) 270px}.workspace>.pane:nth-child(2){display:none}.finding-filters{display:grid;grid-template-columns:repeat(5,minmax(0,1fr)) minmax(180px,1fr);align-items:end}.finding-filters strong{grid-column:1/-1}.filter-summary{margin-left:0}}
|
|
24
|
+
@media(max-width:1100px){.summary{grid-template-columns:repeat(4,1fr)}.severity-chart{grid-column:span 2}.scope-row{grid-template-columns:1fr}.workspace{grid-template-columns:175px 205px minmax(300px,1fr) 270px}.workspace>.pane:nth-child(2){display:none}.tools input{width:130px}.finding-filters{padding-left:12px;padding-right:12px}}
|
|
25
|
+
@media(max-width:760px){.app{grid-template-rows:auto auto auto auto 1fr}.top{flex-wrap:wrap;min-height:118px;padding:10px 14px}.brand{min-width:0;flex:1;font-size:17px}.nav{order:3;width:100%;overflow:auto}.nav button{min-height:42px}.tools{width:100%;margin-left:0}.tools input{flex:1;width:auto}.finding-filters{display:flex;padding:0 10px 10px;align-items:stretch}.filter-control{flex:1 1 calc(50% - 8px);min-width:140px}.filter-control select,.finding-filters>button{width:100%;min-height:44px}.finding-filters>button{flex:1 1 100%}.filter-summary{width:100%;margin:0}.summary{grid-template-columns:repeat(2,1fr);padding:10px}.summary .card{min-height:72px;padding:10px}.summary .card strong{font-size:21px}.severity-chart{grid-column:auto}.scope-row{padding:0 10px 10px}.scope{align-items:stretch;flex-wrap:wrap}.scope select{min-width:100%;min-height:44px}.projects{display:none}.workspace{display:flex;flex-direction:column;margin:0 10px 10px;border-radius:12px}.workspace>.pane:nth-child(1){display:none}.workspace>.pane:nth-child(2){display:none}.workspace>.pane:nth-child(3){order:1;height:420px}.workspace>.pane:nth-child(5){order:2;height:auto;min-height:520px}.workspace>.pane:nth-child(4){order:3;height:420px}.pane{width:100%}.head{min-height:45px}.scroll{height:calc(100% - 45px)}.details{padding:14px}.details h2{font-size:18px;overflow-wrap:anywhere}.details h3{margin-top:14px}.mobile-back{display:inline-flex!important;align-items:center;min-height:44px;margin-bottom:10px;background:#253b5d!important;border-color:#5778a9!important}.actions button,.actions a{min-height:44px}.review-diff,.code-scroll,.meta,.validation-results,.evidence-grid,.audit-grid{overflow-wrap:anywhere;word-break:break-word}.review-diff{white-space:pre-wrap;max-width:100%;overflow:auto}.screenshot-preview img{max-width:100%;height:auto}.details dialog{max-width:calc(100vw - 24px)}}
|
|
26
|
+
`;
|
|
27
|
+
export function dashboardHtml(report, includeArtifactLinks = false, snippets) { const data = escapeJson(JSON.stringify(toDashboardData(report, snippets))), links = includeArtifactLinks ? '<nav aria-label="Report artifacts"><a href="rtl-report.json">JSON</a> <a href="rtl-report.md">Markdown</a> <a href="rtl-report-structured.md">Structured Markdown</a></nav>' : ''; return `<!doctype html><html lang="en" dir="ltr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>RTL Migration Analyzer v3 — Code Explorer</title><style>${css}.rtl-value{unicode-bidi:isolate;direction:auto}</style></head><body><div id="dashboard" aria-label="RTL code explorer"></div>${links}<script type="application/json" id="rtl-dashboard-data">${data}</script><script>${dashboardClientSource.replace('__SEVERITY_LABELS__', JSON.stringify({ Major: severityDisplayLabel('Major'), Minor: severityDisplayLabel('Minor'), Info: severityDisplayLabel('Info') }))}</script></body></html>\n`; }
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { lstat, readdir, readFile, realpath } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
const excludedDirectories = new Set(['node_modules', '.git', '.nx', 'dist', 'build', 'out', 'coverage', '.next', '.cache', 'test-results', 'playwright-report', '.vite', '.turbo']);
|
|
4
|
+
const supported = /\.(css|scss|tsx?|jsx?|html)$/;
|
|
5
|
+
const sourceLike = /\.(css|scss|sass|less|styl|tsx?|jsx?|html)$/;
|
|
6
|
+
const compareNames = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
|
|
7
|
+
async function walk(root, relative, files, skipped) {
|
|
8
|
+
for (const entry of (await readdir(join(root, relative), { withFileTypes: true })).sort(compareNames)) {
|
|
9
|
+
const path = relative ? `${relative}/${entry.name}` : entry.name;
|
|
10
|
+
if (entry.isSymbolicLink()) {
|
|
11
|
+
skipped.push(path);
|
|
12
|
+
continue;
|
|
13
|
+
}
|
|
14
|
+
if (entry.isDirectory()) {
|
|
15
|
+
if (!excludedDirectories.has(entry.name))
|
|
16
|
+
await walk(root, path, files, skipped);
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
if (/^rtl-report(?:-|\.)/.test(entry.name) || entry.name === 'rtl-report-dashboard.html')
|
|
20
|
+
continue;
|
|
21
|
+
if (supported.test(path) && !path.endsWith('.stories.tsx')) {
|
|
22
|
+
files.add(path);
|
|
23
|
+
}
|
|
24
|
+
else if (sourceLike.test(path) && !path.endsWith('.stories.tsx')) {
|
|
25
|
+
skipped.push(path);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async function nxDiscovery(root) {
|
|
30
|
+
const files = new Set();
|
|
31
|
+
const skipped = [];
|
|
32
|
+
for (const group of ['apps', 'libs']) {
|
|
33
|
+
if ((await lstat(join(root, group))).isSymbolicLink())
|
|
34
|
+
throw new Error('Symlink project group not permitted');
|
|
35
|
+
}
|
|
36
|
+
for (const group of ['apps', 'libs'])
|
|
37
|
+
for (const dir of (await readdir(join(root, group))).sort()) {
|
|
38
|
+
const base = `${group}/${dir}`;
|
|
39
|
+
if (!(await lstat(join(root, base))).isDirectory())
|
|
40
|
+
continue;
|
|
41
|
+
const metadata = JSON.parse(await readFile(join(root, base, 'project.json'), 'utf8'));
|
|
42
|
+
if (!metadata.sourceRoot.startsWith(`${base}/`) || metadata.sourceRoot.includes('..'))
|
|
43
|
+
throw new Error('Invalid sourceRoot');
|
|
44
|
+
if ((await lstat(join(root, metadata.sourceRoot))).isSymbolicLink())
|
|
45
|
+
throw new Error('Symlink sourceRoot not permitted');
|
|
46
|
+
await walk(root, metadata.sourceRoot, files, skipped);
|
|
47
|
+
if (group === 'apps') {
|
|
48
|
+
if ((await lstat(join(root, base, 'index.html'))).isSymbolicLink())
|
|
49
|
+
throw new Error('Symlink HTML not permitted');
|
|
50
|
+
files.add(`${base}/index.html`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return { root, files: [...files].sort(), skipped: skipped.sort() };
|
|
54
|
+
}
|
|
55
|
+
export async function discover(rootInput) {
|
|
56
|
+
const root = await realpath(rootInput);
|
|
57
|
+
const stat = await lstat(root);
|
|
58
|
+
if (!stat.isDirectory())
|
|
59
|
+
throw new Error('Scan root must be a directory');
|
|
60
|
+
const apps = await lstat(join(root, 'apps')).catch(() => undefined);
|
|
61
|
+
const libs = await lstat(join(root, 'libs')).catch(() => undefined);
|
|
62
|
+
if (apps || libs) {
|
|
63
|
+
if (!apps?.isDirectory() || !libs?.isDirectory())
|
|
64
|
+
throw new Error('Incomplete Nx workspace: apps/ and libs/ are both required');
|
|
65
|
+
return nxDiscovery(root);
|
|
66
|
+
}
|
|
67
|
+
const files = new Set();
|
|
68
|
+
const skipped = [];
|
|
69
|
+
await walk(root, '', files, skipped);
|
|
70
|
+
return { root, files: [...files].sort(), skipped: skipped.sort() };
|
|
71
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { BIDI_TRANSFORMATION_ID, proposeBidiIsolation } from './codemod.js';
|
|
2
|
+
// Deliberately empty until a transformation implementation and its preconditions are verified.
|
|
3
|
+
export const verifiedTransformationStrategies = { 'RTL.BIDI.ISOLATION:invoice-id': { preconditions: ['exact InvoiceTable.tsx finding range', 'direct i.id JSX expression', 'no bdi or dir ancestor'], transformationId: BIDI_TRANSFORMATION_ID } };
|
|
4
|
+
export function classifyEligibility(finding, evidenceComplete = true, sourceText) {
|
|
5
|
+
if (!evidenceComplete)
|
|
6
|
+
return { eligibility: 'MANUAL', reason: 'Required evidence is incomplete or stale.', evidence: finding.evidenceIds, transformationId: null, blockers: ['INCOMPLETE_OR_STALE_EVIDENCE'] };
|
|
7
|
+
if (finding.ruleId === 'RTL.BIDI.ISOLATION' && sourceText) {
|
|
8
|
+
try {
|
|
9
|
+
const proposal = proposeBidiIsolation(finding, sourceText);
|
|
10
|
+
return { eligibility: 'AUTOMATED_ELIGIBLE', reason: 'The verified bidi-isolation transformation matches the exact supported AST shape and bounded source range.', evidence: finding.evidenceIds, transformationId: proposal.transformationId, blockers: [] };
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
return { eligibility: 'ASSISTED', reason: 'A bounded bidi-isolation proposal exists, but the source does not satisfy the verified transformation preconditions.', evidence: finding.evidenceIds, transformationId: BIDI_TRANSFORMATION_ID, blockers: [error instanceof Error ? error.message : 'TRANSFORMATION_PRECONDITION_FAILED'] };
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
if (finding.ruleId === 'RTL.BIDI.ISOLATION' && finding.path === 'apps/invoicing/src/components/InvoiceTable.tsx')
|
|
17
|
+
return { eligibility: 'ASSISTED', reason: 'A bounded bidi-isolation proposal is possible, but rendered punctuation and product semantics still require human review.', evidence: finding.evidenceIds, transformationId: 'bidi-isolate-auto', blockers: ['HUMAN_SEMANTIC_REVIEW_REQUIRED', 'NO_VERIFIED_CODEMOD_IMPLEMENTATION'] };
|
|
18
|
+
return { eligibility: 'MANUAL', reason: 'Semantic intent, runtime behavior, or styling ownership is not established by static evidence.', evidence: finding.evidenceIds, transformationId: null, blockers: ['SEMANTIC_OR_RUNTIME_INTENT_UNPROVEN'] };
|
|
19
|
+
}
|
package/dist/html.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { parse } from "parse5";
|
|
2
|
+
import { fact, range } from "./model.js";
|
|
3
|
+
import { extractTailwind } from './tailwind.js';
|
|
4
|
+
import { extractBootstrap } from './bootstrap.js';
|
|
5
|
+
export function extractHtml(path, text) {
|
|
6
|
+
const evidence = [];
|
|
7
|
+
const diagnostics = [];
|
|
8
|
+
const doc = parse(text, { sourceCodeLocationInfo: true, onParseError: e => { if (e.code !== 'missing-doctype')
|
|
9
|
+
diagnostics.push({ path, code: 'HTML_PARSE', message: e.code, range: range(text, e.startOffset, e.endOffset) }); } });
|
|
10
|
+
function walk(n) {
|
|
11
|
+
if ('tagName' in n && n.tagName === 'html') {
|
|
12
|
+
for (const attr of n.attrs.filter(a => ['dir', 'lang'].includes(a.name))) {
|
|
13
|
+
const loc = n.sourceCodeLocation?.attrs?.[attr.name];
|
|
14
|
+
if (loc)
|
|
15
|
+
evidence.push(fact(path, text, 'html-root', 'html', attr.name, attr.value, loc.startOffset, loc.endOffset, 'initial-document-attribute'));
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
if ('tagName' in n) {
|
|
19
|
+
for (const attr of n.attrs.filter(a => a.name === 'class' || a.name === 'className')) {
|
|
20
|
+
const loc = n.sourceCodeLocation?.attrs?.[attr.name];
|
|
21
|
+
if (loc) {
|
|
22
|
+
const segment = text.slice(loc.startOffset, loc.endOffset);
|
|
23
|
+
const valueOffset = loc.startOffset + segment.indexOf(attr.value);
|
|
24
|
+
evidence.push(...extractTailwind(path, text, attr.value, valueOffset, `${n.tagName}`));
|
|
25
|
+
evidence.push(...extractBootstrap(path, text, attr.value, valueOffset, `${n.tagName}`));
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if ('childNodes' in n)
|
|
30
|
+
n.childNodes.forEach(walk);
|
|
31
|
+
}
|
|
32
|
+
walk(doc);
|
|
33
|
+
return { evidence, diagnostics };
|
|
34
|
+
}
|
package/dist/model.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
export const hash = (s) => createHash("sha256").update(s).digest("hex");
|
|
3
|
+
export function range(text, start, end) {
|
|
4
|
+
const point = (offset) => { const lines = text.slice(0, offset).split(/\r\n|\r|\n/); return { offset, line: lines.length, column: lines.at(-1).length + 1 }; };
|
|
5
|
+
return { start: point(start), end: point(end) };
|
|
6
|
+
}
|
|
7
|
+
export function fact(path, text, mechanism, context, property, value, start, end, semantics = "css", tokens) {
|
|
8
|
+
return { id: hash(`${path}|${mechanism}|${context}|${property}|${start}`).slice(0, 24), path, mechanism, context, property, value, original: text.slice(start, end), range: range(text, start, end), semantics, ...(tokens ? { tokens } : {}) };
|
|
9
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { hash, range } from './model.js';
|
|
2
|
+
import { detect } from './rules.js';
|
|
3
|
+
import { findingIdPattern, policyLocations, policyPath, ruleIds } from './policy-validation.js';
|
|
4
|
+
/** Audit policy against the unexcepted source catalog, never against a suppressed result. */
|
|
5
|
+
export function auditPolicy(policy, text, evidence, sources, findings, coverage) {
|
|
6
|
+
const locations = policyLocations(text), diagnostics = [];
|
|
7
|
+
function diagnostic(pointer, code, message, blocking) {
|
|
8
|
+
diagnostics.push({ path: policyPath, range: locations.get(pointer) ?? range(text, 0, 0), code,
|
|
9
|
+
message: `${blocking ? 'BLOCKING' : 'WARNING'} ${pointer}: ${message}`, blocking,
|
|
10
|
+
...(blocking ? { impact: 'DIRECTIONAL_UNSUPPORTED' } : {}),
|
|
11
|
+
rationale: blocking ? 'This record cannot authorize a safe policy decision; analysis is incomplete.' : 'Informational association is unmatched; it cannot establish calibrated coverage.' });
|
|
12
|
+
}
|
|
13
|
+
const contextExists = (path, context) => evidence.some(e => e.path === path && e.context === context) || findings.some(f => f.path === path && f.context === context);
|
|
14
|
+
function unsupported(path, pointer, blocking) {
|
|
15
|
+
if (coverage.some(d => d.path === path && d.blocking && d.code !== 'DYNAMIC_VALUE')) {
|
|
16
|
+
diagnostic(pointer, 'POLICY_UNSUPPORTED', 'source coverage is incomplete; record applicability cannot be established', blocking);
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
const key = (property) => property.replace(/[A-Z]/g, c => '-' + c.toLowerCase());
|
|
22
|
+
policy.approvals.forEach((a, i) => {
|
|
23
|
+
const p = `/approvals/${i}`;
|
|
24
|
+
if (unsupported(a.path, p, true))
|
|
25
|
+
return;
|
|
26
|
+
const matches = evidence.filter(e => e.path === a.path && e.context === a.context && e.property === a.property && e.value === a.value);
|
|
27
|
+
if (matches.length !== 1 || !sources.has(a.path) || a.sourceDigest !== hash(sources.get(a.path))) {
|
|
28
|
+
diagnostic(p, 'POLICY_STALE_APPROVAL', 'exact declaration/value or whole-file source pin no longer matches uniquely', true);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
const e = matches[0], override = policy.ownerOverrides?.find(o => o.path === e.path && o.context === e.context);
|
|
32
|
+
const owner = override?.owner ?? policy.ownership[e.mechanism] ?? 'unknown';
|
|
33
|
+
const expected = key(a.property).replace(/^(margin|padding|border)-(left|right)(.*)$/, (_, group, side, suffix) => `${group}-inline-${side === 'left' ? 'start' : 'end'}${suffix}`);
|
|
34
|
+
if (a.owner !== owner || !['custom-css', 'custom-inline', 'custom-emotion-logical'].includes(owner)) {
|
|
35
|
+
diagnostic(p, 'POLICY_CONFLICT', 'approval owner does not establish the declared source pipeline', true);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (key(a.logicalProperty) !== expected || !/^(margin|padding|border)-(left|right)(-|$)/.test(key(a.property)) || e.mechanism === 'mui-sx') {
|
|
39
|
+
diagnostic(p, 'POLICY_UNSUPPORTED_APPROVAL', 'logical equivalent or source mechanism is not a bounded supported candidate', true);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (policy.exceptions.some(x => x.ruleId === 'RTL.CSS.PHYSICAL' && x.path === e.path && x.context === e.context && x.originalDigest === hash(e.original))) {
|
|
43
|
+
diagnostic(p, 'POLICY_CONFLICT', 'the same declaration has both a semantic approval and an exception', true);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
// Reuse, rather than weaken or duplicate, the existing conservative candidate contract.
|
|
47
|
+
const admitted = detect(evidence, sources, { ...policy, approvals: [a], exceptions: [] }, coverage.map(d => ({ ...d })))
|
|
48
|
+
.some(f => f.category === 'AUTO_CANDIDATE' && f.evidenceIds.includes(e.id));
|
|
49
|
+
if (!admitted)
|
|
50
|
+
diagnostic(p, 'POLICY_UNSUPPORTED_APPROVAL', 'existing conservative admission safeguards do not support this declaration', true);
|
|
51
|
+
});
|
|
52
|
+
policy.exceptions.forEach((x, i) => {
|
|
53
|
+
const p = `/exceptions/${i}`, blocking = x.category !== 'INFORMATIONAL' || !['RTL.DOCUMENT.INITIAL', 'RTL.DOCUMENT.RUNTIME'].includes(x.ruleId);
|
|
54
|
+
if (unsupported(x.path, p, blocking))
|
|
55
|
+
return;
|
|
56
|
+
const matches = findings.filter(f => f.ruleId === x.ruleId && f.path === x.path && f.context === x.context && hash(f.original) === x.originalDigest);
|
|
57
|
+
if (matches.length !== 1)
|
|
58
|
+
diagnostic(p, blocking ? 'POLICY_STALE_EXCEPTION' : 'POLICY_STALE_INFORMATIONAL', 'exact finding anchor/declaration no longer matches uniquely', blocking);
|
|
59
|
+
});
|
|
60
|
+
policy.dynamicExceptions.forEach((x, i) => {
|
|
61
|
+
const p = `/dynamicExceptions/${i}`;
|
|
62
|
+
if (unsupported(x.path, p, true))
|
|
63
|
+
return;
|
|
64
|
+
const matches = evidence.filter(e => e.path === x.path && e.property === x.property && hash(e.value) === x.valueDigest);
|
|
65
|
+
if (!matches.length || !sources.has(x.path) || hash(sources.get(x.path)) !== x.sourceDigest) {
|
|
66
|
+
diagnostic(p, 'POLICY_STALE_DYNAMIC_EXCEPTION', 'expression or whole-file source pin no longer matches', true);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (!matches.some(e => coverage.some(d => d.path === e.path && d.code === 'DYNAMIC_VALUE' && d.range.start.offset >= e.range.start.offset && d.range.end.offset <= e.range.end.offset))) {
|
|
70
|
+
diagnostic(p, 'POLICY_STALE_DYNAMIC_EXCEPTION', 'record does not match an extracted dynamic-value diagnostic', true);
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
policy.ownerOverrides?.forEach((x, i) => {
|
|
74
|
+
const p = `/ownerOverrides/${i}`;
|
|
75
|
+
if (unsupported(x.path, p, true))
|
|
76
|
+
return;
|
|
77
|
+
if (!contextExists(x.path, x.context))
|
|
78
|
+
diagnostic(p, 'POLICY_STALE_OVERRIDE', 'source ownership context no longer exists', true);
|
|
79
|
+
else {
|
|
80
|
+
const mechanisms = evidence.filter(e => e.path === x.path && e.context === x.context).map(e => e.mechanism);
|
|
81
|
+
const compatible = (m) => x.owner === 'unknown' || (m === 'css' ? x.owner === 'custom-css' : m === 'react-inline' ? x.owner === 'custom-inline' : m === 'html-root' ? x.owner === 'document-runtime' : ['custom-emotion-review', 'custom-emotion-logical'].includes(x.owner));
|
|
82
|
+
if (!mechanisms.length || !mechanisms.every(compatible))
|
|
83
|
+
diagnostic(p, 'POLICY_CONFLICT', 'override does not establish a compatible extracted style mechanism', true);
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
policy.issueBindings.forEach((b, i) => {
|
|
87
|
+
const p = `/issueBindings/${i}`;
|
|
88
|
+
if (unsupported(b.path, p, false))
|
|
89
|
+
return;
|
|
90
|
+
if (!findings.some(f => f.ruleId === b.ruleId && f.path === b.path && f.context.includes(b.contextIncludes) && (!b.originalIncludes || f.original.includes(b.originalIncludes))))
|
|
91
|
+
diagnostic(p, 'POLICY_STALE_INFORMATIONAL', 'reference binding has no supported source finding; no issue coverage can be inferred', false);
|
|
92
|
+
});
|
|
93
|
+
policy.roles.forEach((role, i) => {
|
|
94
|
+
// A role must yield the existing role rule, not merely name a source file containing that string.
|
|
95
|
+
const p = `/roles/${i}`;
|
|
96
|
+
if (unsupported(role.path, p, false))
|
|
97
|
+
return;
|
|
98
|
+
if (!findings.some(f => f.ruleId === 'RTL.BRAND.ISLAND' && f.path === role.path && (f.original.match(/className\s*=\s*(['"])(.*?)\1/)?.[2].split(/\s+/).includes(role.className) ?? false)))
|
|
99
|
+
diagnostic(p, 'POLICY_STALE_INFORMATIONAL', 'brand association has no matched source rule; review role applicability', false);
|
|
100
|
+
});
|
|
101
|
+
const ids = new Set();
|
|
102
|
+
for (const f of findings) {
|
|
103
|
+
if (!findingIdPattern.test(f.id) || !f.id.startsWith(f.ruleId + ':') || !ruleIds.has(f.ruleId) || ids.has(f.id)) {
|
|
104
|
+
diagnostics.push({ path: f.path, range: f.range, code: 'POLICY_FINDING_ID_INVALID', message: 'BLOCKING: invalid, unsupported or duplicate generated finding identity', impact: 'SOURCE_FAILURE', blocking: true, rationale: 'Policy decisions cannot rely on ambiguous finding identities.' });
|
|
105
|
+
}
|
|
106
|
+
ids.add(f.id);
|
|
107
|
+
}
|
|
108
|
+
return diagnostics;
|
|
109
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
2
|
+
import { range } from './model.js';
|
|
3
|
+
export const policyPath = 'rtl-scanner.config.json';
|
|
4
|
+
export const mechanisms = ['css', 'emotion-template', 'mui-sx', 'mui-theme', 'react-inline', 'html-root'];
|
|
5
|
+
const owners = ['custom-css', 'custom-inline', 'custom-emotion-review', 'custom-emotion-logical', 'mui-generated', 'document-runtime', 'unknown'];
|
|
6
|
+
export const ruleIds = new Set([
|
|
7
|
+
'RTL.CSS.PHYSICAL', 'RTL.CSS.SHORTHAND', 'RTL.GEOMETRY.EDGE', 'RTL.GEOMETRY.COUPLED', 'RTL.GEOMETRY.ORDER',
|
|
8
|
+
'RTL.OWNERSHIP.CONFLICT', 'RTL.RUNTIME.MISMATCH', 'RTL.RUNTIME.CACHE', 'RTL.RUNTIME.CACHE_UNVERIFIED',
|
|
9
|
+
'RTL.RUNTIME.DIRECTION_UNKNOWN', 'RTL.RUNTIME.PAGINATION', 'RTL.RUNTIME.LOCALE', 'RTL.FORM.DIRECTION',
|
|
10
|
+
'RTL.TABLE.ALIGNMENT', 'RTL.CHART.LABEL_FLOW', 'RTL.ICON.PROGRESSION', 'RTL.ICON.LITERAL',
|
|
11
|
+
'RTL.BIDI.ISOLATION', 'RTL.BRAND.ISLAND', 'RTL.DOCUMENT.INITIAL', 'RTL.DOCUMENT.RUNTIME',
|
|
12
|
+
]);
|
|
13
|
+
export const findingIdPattern = /^RTL\.[A-Z_]+(?:\.[A-Z_]+)*:[a-f0-9]{24}$/;
|
|
14
|
+
export class PolicyError extends Error {
|
|
15
|
+
diagnostic;
|
|
16
|
+
constructor(diagnostic) {
|
|
17
|
+
super(`Invalid scanner policy: ${diagnostic.path}:${diagnostic.range.start.line}:${diagnostic.range.start.column} ${diagnostic.code}: ${diagnostic.message}`);
|
|
18
|
+
this.diagnostic = diagnostic;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const pointerPart = (s) => s.replace(/~/g, '~0').replace(/\//g, '~1');
|
|
22
|
+
export function policyLocations(text) {
|
|
23
|
+
const sf = ts.parseJsonText(policyPath, text);
|
|
24
|
+
const locations = new Map();
|
|
25
|
+
function walk(n, pointer) {
|
|
26
|
+
locations.set(pointer, range(text, n.getStart(sf), n.end));
|
|
27
|
+
if (ts.isObjectLiteralExpression(n)) {
|
|
28
|
+
const seen = new Set();
|
|
29
|
+
for (const p of n.properties)
|
|
30
|
+
if (ts.isPropertyAssignment(p) && ts.isStringLiteral(p.name)) {
|
|
31
|
+
const child = `${pointer}/${pointerPart(p.name.text)}`;
|
|
32
|
+
if (seen.has(p.name.text))
|
|
33
|
+
throw new PolicyError({ path: policyPath, range: range(text, p.getStart(sf), p.end), code: 'POLICY_DUPLICATE', message: `BLOCKING ${child}: duplicate JSON member`, blocking: true, impact: 'SOURCE_FAILURE', rationale: 'JSON member overwrite is ambiguous; no policy decisions are applied.' });
|
|
34
|
+
seen.add(p.name.text);
|
|
35
|
+
walk(p.initializer, child);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
else if (ts.isArrayLiteralExpression(n))
|
|
39
|
+
n.elements.forEach((e, i) => walk(e, `${pointer}/${i}`));
|
|
40
|
+
}
|
|
41
|
+
const statement = sf.statements[0];
|
|
42
|
+
if (statement && ts.isExpressionStatement(statement))
|
|
43
|
+
walk(statement.expression, '');
|
|
44
|
+
return locations;
|
|
45
|
+
}
|
|
46
|
+
export function validatePolicy(input, text) {
|
|
47
|
+
const locations = policyLocations(text);
|
|
48
|
+
const fail = (pointer, message, code = 'POLICY_INVALID') => {
|
|
49
|
+
const parent = pointer.slice(0, pointer.lastIndexOf('/'));
|
|
50
|
+
throw new PolicyError({ path: policyPath, range: locations.get(pointer) ?? locations.get(parent) ?? range(text, 0, 0), code, message: `BLOCKING ${pointer || '/'}: ${message}`, blocking: true, impact: 'SOURCE_FAILURE', rationale: 'Policy input is invalid, conflicting or unsupported; no policy decisions are applied.' });
|
|
51
|
+
};
|
|
52
|
+
function object(value, pointer, required, optional = []) {
|
|
53
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
54
|
+
fail(pointer, 'expected object');
|
|
55
|
+
const obj = value;
|
|
56
|
+
for (const key of Object.keys(obj).sort())
|
|
57
|
+
if (![...required, ...optional].includes(key))
|
|
58
|
+
fail(`${pointer}/${pointerPart(key)}`, 'unknown field');
|
|
59
|
+
for (const key of required)
|
|
60
|
+
if (!Object.hasOwn(obj, key))
|
|
61
|
+
fail(`${pointer}/${key}`, 'required field missing');
|
|
62
|
+
return obj;
|
|
63
|
+
}
|
|
64
|
+
const str = (v, p) => { if (typeof v !== 'string' || !v.trim() || v.length > 4096 || v.includes('\0'))
|
|
65
|
+
fail(p, 'expected nonempty bounded string'); return v; };
|
|
66
|
+
const enumValue = (v, p, values) => { const s = str(v, p); if (!values.includes(s))
|
|
67
|
+
fail(p, 'unsupported enum value'); return s; };
|
|
68
|
+
const pathValue = (v, p) => {
|
|
69
|
+
const s = str(v, p);
|
|
70
|
+
if (/^[\/\\]|^[A-Za-z]:|\\|[\r\n]/.test(s) || s.split('/').some(x => !x || x === '.' || x === '..'))
|
|
71
|
+
fail(p, 'expected normalized repository-relative POSIX path');
|
|
72
|
+
};
|
|
73
|
+
const digest = (v, p) => { if (!/^[a-f0-9]{64}$/.test(str(v, p)))
|
|
74
|
+
fail(p, 'expected lowercase SHA-256 digest'); };
|
|
75
|
+
const rule = (v, p) => { if (!ruleIds.has(str(v, p)))
|
|
76
|
+
fail(p, 'rule is not supported by this scanner', 'POLICY_UNSUPPORTED'); };
|
|
77
|
+
const top = object(input, '', ['schemaVersion', 'generatedStyleOwner', 'ownership', 'approvals', 'exceptions', 'issueBindings', 'dynamicExceptions', 'roles'], ['ownerOverrides']);
|
|
78
|
+
if (top.schemaVersion !== 1)
|
|
79
|
+
fail('/schemaVersion', 'only schemaVersion 1 is supported', 'POLICY_UNSUPPORTED');
|
|
80
|
+
enumValue(top.generatedStyleOwner, '/generatedStyleOwner', ['mui-generated', 'unknown']);
|
|
81
|
+
const ownership = object(top.ownership, '/ownership', [], [...mechanisms]);
|
|
82
|
+
for (const [k, v] of Object.entries(ownership)) {
|
|
83
|
+
enumValue(v, `/ownership/${k}`, owners);
|
|
84
|
+
const allowed = k === 'css' ? ['custom-css', 'unknown'] : k === 'react-inline' ? ['custom-inline', 'unknown'] : k === 'html-root' ? ['document-runtime', 'unknown'] : ['custom-emotion-review', 'custom-emotion-logical', 'unknown'];
|
|
85
|
+
enumValue(v, `/ownership/${k}`, allowed);
|
|
86
|
+
}
|
|
87
|
+
const shapes = {
|
|
88
|
+
approvals: [['path', 'context', 'property', 'value', 'owner', 'logicalProperty', 'reason', 'reviewedBy', 'sourceDigest'], []],
|
|
89
|
+
exceptions: [['ruleId', 'path', 'context', 'category', 'reason', 'reviewedBy', 'originalDigest'], []],
|
|
90
|
+
issueBindings: [['ruleId', 'path', 'contextIncludes', 'issueId'], ['originalIncludes']],
|
|
91
|
+
dynamicExceptions: [['path', 'property', 'valueDigest', 'sourceDigest', 'reason'], []],
|
|
92
|
+
roles: [['kind', 'path', 'className'], []],
|
|
93
|
+
ownerOverrides: [['path', 'context', 'owner', 'reason'], []],
|
|
94
|
+
};
|
|
95
|
+
const identities = {
|
|
96
|
+
approvals: ['path', 'context', 'property', 'value'], exceptions: ['ruleId', 'path', 'context', 'originalDigest'],
|
|
97
|
+
issueBindings: ['ruleId', 'path', 'contextIncludes', 'originalIncludes', 'issueId'],
|
|
98
|
+
dynamicExceptions: ['path', 'property', 'valueDigest'], roles: ['kind', 'path', 'className'], ownerOverrides: ['path', 'context'],
|
|
99
|
+
};
|
|
100
|
+
for (const [name, [required, optional]] of Object.entries(shapes)) {
|
|
101
|
+
if (name === 'ownerOverrides' && !Object.hasOwn(top, name))
|
|
102
|
+
continue;
|
|
103
|
+
const records = top[name];
|
|
104
|
+
if (!Array.isArray(records) || records.length > 10000)
|
|
105
|
+
fail(`/${name}`, 'expected bounded array');
|
|
106
|
+
const seen = new Map();
|
|
107
|
+
for (let i = 0; i < records.length; i++) {
|
|
108
|
+
const p = `/${name}/${i}`, entry = object(records[i], p, required, optional);
|
|
109
|
+
for (const [key, v] of Object.entries(entry))
|
|
110
|
+
str(v, `${p}/${key}`);
|
|
111
|
+
pathValue(entry.path, `${p}/path`);
|
|
112
|
+
for (const key of ['sourceDigest', 'originalDigest', 'valueDigest'])
|
|
113
|
+
if (key in entry)
|
|
114
|
+
digest(entry[key], `${p}/${key}`);
|
|
115
|
+
if ('ruleId' in entry)
|
|
116
|
+
rule(entry.ruleId, `${p}/ruleId`);
|
|
117
|
+
if ('owner' in entry)
|
|
118
|
+
enumValue(entry.owner, `${p}/owner`, owners);
|
|
119
|
+
if ('category' in entry)
|
|
120
|
+
enumValue(entry.category, `${p}/category`, ['INTENTIONAL_LTR', 'INFORMATIONAL']);
|
|
121
|
+
if (name === 'roles')
|
|
122
|
+
enumValue(entry.kind, `${p}/kind`, ['brand']);
|
|
123
|
+
if (name === 'dynamicExceptions')
|
|
124
|
+
enumValue(entry.property, `${p}/property`, ['background']);
|
|
125
|
+
if (name === 'issueBindings' && !/^RTL-0[1-9]$/.test(entry.issueId))
|
|
126
|
+
fail(`${p}/issueId`, 'unsupported reference issue ID');
|
|
127
|
+
const identity = JSON.stringify(identities[name].map(k => entry[k] ?? null));
|
|
128
|
+
const prior = seen.get(identity);
|
|
129
|
+
if (prior) {
|
|
130
|
+
const conflict = name === 'ownerOverrides' && prior.owner !== entry.owner || name === 'exceptions' && prior.category !== entry.category || name === 'approvals' && (prior.owner !== entry.owner || prior.logicalProperty !== entry.logicalProperty) || name === 'dynamicExceptions' && prior.sourceDigest !== entry.sourceDigest;
|
|
131
|
+
fail(p, conflict ? 'conflicting policy records' : 'duplicate policy record', conflict ? 'POLICY_CONFLICT' : 'POLICY_DUPLICATE');
|
|
132
|
+
}
|
|
133
|
+
seen.set(identity, entry);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return input;
|
|
137
|
+
}
|
package/dist/policy.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { readFile, lstat } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { range } from './model.js';
|
|
4
|
+
import { PolicyError, policyPath, validatePolicy } from './policy-validation.js';
|
|
5
|
+
export const emptyPolicy = { schemaVersion: 1, generatedStyleOwner: 'unknown', ownership: {}, approvals: [], exceptions: [], issueBindings: [], dynamicExceptions: [], roles: [] };
|
|
6
|
+
const sourceTexts = new WeakMap();
|
|
7
|
+
export const policySourceText = (policy) => sourceTexts.get(policy) ?? JSON.stringify(policy, null, 2);
|
|
8
|
+
export async function loadPolicy(root) {
|
|
9
|
+
let text;
|
|
10
|
+
try {
|
|
11
|
+
if ((await lstat(join(root, policyPath))).isSymbolicLink())
|
|
12
|
+
throw new PolicyError({ path: policyPath, range: range('', 0, 0), code: 'POLICY_INVALID_PATH', message: 'BLOCKING /: symlink policy file not permitted', impact: 'SOURCE_FAILURE', blocking: true, rationale: 'Policy input must remain inside the read-only repository scope.' });
|
|
13
|
+
text = await readFile(join(root, policyPath), 'utf8');
|
|
14
|
+
}
|
|
15
|
+
catch (e) {
|
|
16
|
+
if (e.code === 'ENOENT')
|
|
17
|
+
return emptyPolicy;
|
|
18
|
+
throw e;
|
|
19
|
+
}
|
|
20
|
+
if (text.length > 1_000_000)
|
|
21
|
+
throw new PolicyError({ path: policyPath, range: range(text, 0, 0), code: 'POLICY_INVALID', message: 'BLOCKING /: policy exceeds size limit', impact: 'SOURCE_FAILURE', blocking: true, rationale: 'Policy input size is bounded.' });
|
|
22
|
+
let input;
|
|
23
|
+
try {
|
|
24
|
+
input = JSON.parse(text);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
throw new PolicyError({ path: policyPath, range: range(text, 0, 0), code: 'POLICY_INVALID_JSON', message: 'BLOCKING /: invalid JSON', impact: 'SOURCE_FAILURE', blocking: true, rationale: 'Policy JSON cannot be interpreted; no policy decisions are applied.' });
|
|
28
|
+
}
|
|
29
|
+
const policy = validatePolicy(input, text);
|
|
30
|
+
sourceTexts.set(policy, text);
|
|
31
|
+
return policy;
|
|
32
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
function freezeDeep(value) {
|
|
2
|
+
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
3
|
+
for (const child of Object.values(value))
|
|
4
|
+
freezeDeep(child);
|
|
5
|
+
Object.freeze(value);
|
|
6
|
+
}
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
function clone(value) {
|
|
10
|
+
return JSON.parse(JSON.stringify(value));
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Adapt the canonical report without changing its shape, ordering, or bytes.
|
|
14
|
+
* Renderers must not mutate the scan result through this view.
|
|
15
|
+
*/
|
|
16
|
+
export function toSchemaV2Presentation(report) {
|
|
17
|
+
const evidence = clone(report.evidence);
|
|
18
|
+
const findings = clone(report.findings);
|
|
19
|
+
const evidenceById = new Map();
|
|
20
|
+
for (const item of evidence)
|
|
21
|
+
evidenceById.set(item.id, [...(evidenceById.get(item.id) ?? []), item]);
|
|
22
|
+
const evidenceReferences = findings.map((finding) => {
|
|
23
|
+
const evidenceForFinding = [];
|
|
24
|
+
const missingEvidenceIds = [];
|
|
25
|
+
const duplicateEvidenceIds = [];
|
|
26
|
+
const seen = new Set();
|
|
27
|
+
for (const id of finding.evidenceIds) {
|
|
28
|
+
const matches = evidenceById.get(id) ?? [];
|
|
29
|
+
if (seen.has(id))
|
|
30
|
+
duplicateEvidenceIds.push(id);
|
|
31
|
+
seen.add(id);
|
|
32
|
+
if (!matches.length)
|
|
33
|
+
missingEvidenceIds.push(id);
|
|
34
|
+
else
|
|
35
|
+
evidenceForFinding.push(matches[0]);
|
|
36
|
+
if (matches.length > 1)
|
|
37
|
+
duplicateEvidenceIds.push(id);
|
|
38
|
+
}
|
|
39
|
+
return { findingId: finding.id, evidenceIds: [...finding.evidenceIds], evidence: evidenceForFinding, missingEvidenceIds, duplicateEvidenceIds };
|
|
40
|
+
});
|
|
41
|
+
const presentation = {
|
|
42
|
+
schemaVersion: report.schemaVersion,
|
|
43
|
+
kind: report.kind,
|
|
44
|
+
policyDigest: report.policyDigest,
|
|
45
|
+
inputDigest: report.inputDigest,
|
|
46
|
+
files: clone(report.files), skipped: clone(report.skipped), evidence, diagnostics: clone(report.diagnostics), findings,
|
|
47
|
+
metrics: clone(report.metrics), complete: report.complete,
|
|
48
|
+
};
|
|
49
|
+
freezeDeep(evidenceReferences);
|
|
50
|
+
Object.defineProperty(presentation, 'evidenceReferences', { value: evidenceReferences, enumerable: false, writable: false, configurable: false });
|
|
51
|
+
return freezeDeep(presentation);
|
|
52
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const PREVIEW_MANIFEST_VERSION = 1;
|
|
2
|
+
export const PREVIEW_COMPANION_ORIGIN = 'http://127.0.0.1:4318';
|
|
3
|
+
export const previewManifest = { version: PREVIEW_MANIFEST_VERSION, mappings: [{ id: 'invoicing-invoice-table', source: 'apps/invoicing/src/components/InvoiceTable.tsx', application: 'invoicing', owningRoute: '/invoices', routes: { ltr: '/invoices', rtl: '/invoices?demo=unmigrated-rtl&lang=ar' } }] };
|
|
4
|
+
const mappingById = new Map(previewManifest.mappings.map((mapping) => [mapping.id, mapping]));
|
|
5
|
+
export function approvedPreviewForSource(source) { return previewManifest.mappings.find((mapping) => mapping.source === source) ?? null; }
|
|
6
|
+
export function validatedPreviewRoute(mappingId, mode) {
|
|
7
|
+
const mapping = mappingById.get(mappingId);
|
|
8
|
+
if (!mapping || (mode !== 'ltr' && mode !== 'rtl'))
|
|
9
|
+
return null;
|
|
10
|
+
const selectedMode = mode;
|
|
11
|
+
const route = mapping.routes[selectedMode];
|
|
12
|
+
if (!route.startsWith(mapping.owningRoute) || (selectedMode === 'rtl' && route !== '/invoices?demo=unmigrated-rtl&lang=ar'))
|
|
13
|
+
return null;
|
|
14
|
+
return { mapping, mode: selectedMode, route };
|
|
15
|
+
}
|