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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ahmed Fouad
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,54 @@
|
|
|
1
|
-
#
|
|
1
|
+
# RTL Analyzer CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Standalone CLI packaging for RTL Analyzer. The CLI performs read-only RTL risk scans and can emit JSON, Markdown, structured Markdown, or a self-contained dashboard HTML report.
|
|
4
|
+
|
|
5
|
+
## Build and pack
|
|
6
|
+
|
|
7
|
+
From a fresh checkout, install the repository dependencies, then build and pack the standalone package:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm ci
|
|
11
|
+
npm run build --prefix packages/rtl-analyzer
|
|
12
|
+
cd packages/rtl-analyzer
|
|
13
|
+
npm pack --dry-run
|
|
14
|
+
npm pack
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The package `prepack` hook rebuilds `dist/` automatically, so packing cannot silently use a missing or stale CLI build. The tarball contains only the compiled scanner/reporting runtime, this README, and the MIT license.
|
|
18
|
+
|
|
19
|
+
## Confirmed syntax coverage
|
|
20
|
+
|
|
21
|
+
The standalone CLI supports the following tested patterns. These are syntax-level results, not claims of complete framework compatibility:
|
|
22
|
+
|
|
23
|
+
| Area | Status | Tested scope |
|
|
24
|
+
| --- | --- | --- |
|
|
25
|
+
| React inline JSX/TSX styles | Verified | Static object properties including physical margins, padding, and text alignment. |
|
|
26
|
+
| Emotion `styled` templates | Verified | Static tagged templates imported from `@emotion/styled`. |
|
|
27
|
+
| Emotion `css` prop | Verified | `@emotion/react` tagged templates and static object expressions. |
|
|
28
|
+
| MUI `sx` | Partial | Supported MUI imports and aliases such as `ml` and `pr`; wrapper semantics remain conservative. |
|
|
29
|
+
| MUI `styled` templates | Verified | Static tagged templates imported from `@mui/material/styles`. |
|
|
30
|
+
| Vanilla CSS/HTML | Verified | Tested physical declarations and HTML direction attributes. |
|
|
31
|
+
| CSS Modules | Verified | Physical declarations in discovered `.module.css` files. |
|
|
32
|
+
| Tailwind utilities | Partial | Static class strings recognize `ml-*`, `mr-*`, `pl-*`, `pr-*`, `left-*`, `right-*`, `border-l-*`, `border-r-*`, `text-left`, `text-right`, and identifiable `rtl:`/`ltr:` variants. Dynamic composition is not evaluated. |
|
|
33
|
+
| Bootstrap 4 directional utilities | Partial | Static class strings recognize Bootstrap 4 `float-left/right`, responsive `float-{sm,md,lg,xl}-left/right`, `text-{sm,md,lg,xl}-left/right`, and `border-left/right[-0]`. Shared physical classes such as `ml-*` remain framework-neutral; Bootstrap version and runtime semantics are not inferred. |
|
|
34
|
+
| SCSS/Sass | Unsupported with diagnostic | Files are skipped and reported through `SOURCE_COVERAGE`. |
|
|
35
|
+
|
|
36
|
+
MUI `styled` object syntax is unsupported. Tailwind responsive/state prefixes and arbitrary values are covered only when the final utility is statically identifiable; dynamic `clsx`, `classnames`, and template expressions are intentionally not guessed. Next.js `app/`, `src/app/`, `pages/`, and `src/pages/` layouts can be discovered as ordinary files, but this does not certify Next.js-specific behavior.
|
|
37
|
+
|
|
38
|
+
Bootstrap support is limited to the listed Bootstrap 4 physical utility forms. Bootstrap 5 logical utilities such as `ms-*`, `me-*`, `ps-*`, and `pe-*`, custom classes, project configuration, and dynamic class composition are not interpreted.
|
|
39
|
+
|
|
40
|
+
To verify the tarball in an independent disposable project:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
npm run rtl:cli:package:smoke
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The smoke test installs with `npm install --ignore-scripts`, checks `--help` and `--version`, scans a disposable project in JSON, Markdown, and Dashboard formats, and checks that installed files contain no source-checkout paths.
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
npm install rtl-analyzer
|
|
50
|
+
rtl-analyzer --help
|
|
51
|
+
rtl-analyzer scan . --format json
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Candidate Preview and Apply/Rollback are not included in this standalone CLI milestone.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { fact } from './model.js';
|
|
2
|
+
const utilities = {
|
|
3
|
+
'float-left': 'float',
|
|
4
|
+
'float-right': 'float',
|
|
5
|
+
'text-left': 'text-align',
|
|
6
|
+
'text-right': 'text-align',
|
|
7
|
+
'border-left': 'border-left',
|
|
8
|
+
'border-right': 'border-right',
|
|
9
|
+
};
|
|
10
|
+
export function extractBootstrap(path, text, value, valueStart, context) {
|
|
11
|
+
const evidence = [];
|
|
12
|
+
for (const match of value.matchAll(/\S+/g)) {
|
|
13
|
+
const token = match[0];
|
|
14
|
+
const utility = token;
|
|
15
|
+
const key = utility.match(/^(?:float|border)-(?:left|right)(?:-0)?$|^(?:float|text)-(?:sm|md|lg|xl)-(?:left|right)$/)?.[0];
|
|
16
|
+
if (!key)
|
|
17
|
+
continue;
|
|
18
|
+
const base = key.replace(/^(?:float|text)-(?:sm|md|lg|xl)-/, (key.startsWith('float-') ? 'float-' : 'text-')).replace(/-0$/, '');
|
|
19
|
+
if (!utilities[base])
|
|
20
|
+
continue;
|
|
21
|
+
const property = utilities[base];
|
|
22
|
+
const normalized = property === 'text-align' ? base.endsWith('left') ? 'left' : 'right' : token;
|
|
23
|
+
const start = valueStart + match.index;
|
|
24
|
+
evidence.push(fact(path, text, 'css', `${context}/.${token}`, property, normalized, start, start + token.length, 'bootstrap-utility', [token]));
|
|
25
|
+
}
|
|
26
|
+
return evidence;
|
|
27
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { exitCode } from './coverage.js';
|
|
2
|
+
import { scan } from './scan.js';
|
|
3
|
+
import { json, markdown } from './report.js';
|
|
4
|
+
import { publishReports } from './report-publisher.js';
|
|
5
|
+
import { publishArtifacts } from './report-publisher.js';
|
|
6
|
+
import { toSchemaV2Presentation } from './presentation-adapter.js';
|
|
7
|
+
import { structuredMarkdown } from './structured-markdown.js';
|
|
8
|
+
import { dashboardHtml } from './dashboard-html.js';
|
|
9
|
+
import { extractSourceSnippets } from './source-snippets.js';
|
|
10
|
+
import { pathToFileURL } from 'node:url';
|
|
11
|
+
const defaultDependencies = { scan, json, markdown, publishReports, publishArtifacts, extractSourceSnippets };
|
|
12
|
+
export async function runCli(argv, io, dependencies = defaultDependencies) {
|
|
13
|
+
let root = process.cwd();
|
|
14
|
+
let format = 'json';
|
|
15
|
+
let gate = false;
|
|
16
|
+
let outputDir;
|
|
17
|
+
let embedSource = false;
|
|
18
|
+
try {
|
|
19
|
+
const args = argv.filter(a => { if (a === '--fail-on-findings') {
|
|
20
|
+
gate = true;
|
|
21
|
+
return false;
|
|
22
|
+
} return true; });
|
|
23
|
+
for (let i = 0; i < args.length; i += 2) {
|
|
24
|
+
const key = args[i], value = args[i + 1];
|
|
25
|
+
if (key === '--embed-source-snippets') {
|
|
26
|
+
if (value && !value.startsWith('--'))
|
|
27
|
+
throw new Error('Flag --embed-source-snippets does not take a value');
|
|
28
|
+
embedSource = true;
|
|
29
|
+
i--;
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
if (!value || value.startsWith('--'))
|
|
33
|
+
throw new Error('Missing option value');
|
|
34
|
+
if (key === '--root')
|
|
35
|
+
root = value;
|
|
36
|
+
else if (key === '--output-dir')
|
|
37
|
+
outputDir = value;
|
|
38
|
+
else if (key === '--format' && ['json', 'markdown', 'markdown-structured', 'dashboard'].includes(value))
|
|
39
|
+
format = value;
|
|
40
|
+
else
|
|
41
|
+
throw new Error('Unknown option or format');
|
|
42
|
+
}
|
|
43
|
+
if (embedSource && (!outputDir || format !== 'dashboard'))
|
|
44
|
+
throw new Error('--embed-source-snippets requires --format dashboard and --output-dir');
|
|
45
|
+
const r = await dependencies.scan(root);
|
|
46
|
+
const jsonBytes = dependencies.json(r);
|
|
47
|
+
const markdownBytes = dependencies.markdown(r);
|
|
48
|
+
const needsPresentation = ['markdown-structured', 'dashboard'].includes(format);
|
|
49
|
+
const presentation = needsPresentation ? toSchemaV2Presentation(r) : undefined;
|
|
50
|
+
const structuredBytes = needsPresentation ? structuredMarkdown(presentation) : '';
|
|
51
|
+
const snippets = embedSource ? await (dependencies.extractSourceSnippets ?? extractSourceSnippets)(root, r.findings) : undefined;
|
|
52
|
+
const dashboardBytes = format === 'dashboard' ? dashboardHtml(presentation, Boolean(outputDir), snippets) : '';
|
|
53
|
+
if (outputDir) {
|
|
54
|
+
if (format === 'markdown-structured' && dependencies.publishArtifacts)
|
|
55
|
+
await dependencies.publishArtifacts(root, outputDir, [{ name: 'rtl-report.json', contents: jsonBytes }, { name: 'rtl-report.md', contents: markdownBytes }, { name: 'rtl-report-structured.md', contents: structuredBytes }]);
|
|
56
|
+
else if (format === 'dashboard' && dependencies.publishArtifacts)
|
|
57
|
+
await dependencies.publishArtifacts(root, outputDir, [{ name: 'rtl-report.json', contents: jsonBytes }, { name: 'rtl-report.md', contents: markdownBytes }, { name: 'rtl-report-structured.md', contents: structuredBytes }, { name: 'rtl-report-dashboard.html', contents: dashboardBytes }]);
|
|
58
|
+
else
|
|
59
|
+
await dependencies.publishReports(root, outputDir, jsonBytes, markdownBytes);
|
|
60
|
+
}
|
|
61
|
+
io.writeStdout(format === 'markdown' ? markdownBytes : format === 'markdown-structured' ? structuredBytes : format === 'dashboard' ? dashboardBytes : jsonBytes);
|
|
62
|
+
const findings = r.findings.filter((f) => !['INFORMATIONAL', 'INTENTIONAL_LTR'].includes(f.category)).length;
|
|
63
|
+
const code = exitCode(r.complete, findings, gate);
|
|
64
|
+
if (outputDir)
|
|
65
|
+
io.writeStderr(`RTL scan: ${r.complete ? 'complete' : 'incomplete'}; files=${r.files.length}; findings=${findings}; output=${outputDir}`);
|
|
66
|
+
return code;
|
|
67
|
+
}
|
|
68
|
+
catch (e) {
|
|
69
|
+
io.writeStderr(e instanceof Error ? e.message : String(e ?? 'Scan failed'));
|
|
70
|
+
return 2;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
74
|
+
const io = { writeStdout: (s) => process.stdout.write(s), writeStderr: (s) => console.error(s) };
|
|
75
|
+
process.exitCode = await runCli(process.argv.slice(2), io);
|
|
76
|
+
}
|
package/dist/codemod.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { REVIEW_SOURCE } from './review-session.js';
|
|
4
|
+
import { applyReviewPatch } from './review-session.js';
|
|
5
|
+
export const BIDI_TRANSFORMATION_ID = 'bidi-isolate-auto';
|
|
6
|
+
export class TransformationRejected extends Error {
|
|
7
|
+
code;
|
|
8
|
+
constructor(code) {
|
|
9
|
+
super(code);
|
|
10
|
+
this.code = code;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
const sha = (value) => createHash('sha256').update(value).digest('hex');
|
|
14
|
+
function hasIsolation(node) {
|
|
15
|
+
for (let parent = node.parent; parent; parent = parent.parent) {
|
|
16
|
+
if (ts.isJsxElement(parent) || ts.isJsxSelfClosingElement(parent)) {
|
|
17
|
+
const opening = ts.isJsxElement(parent) ? parent.openingElement : parent;
|
|
18
|
+
const tag = opening.tagName.getText();
|
|
19
|
+
if (tag === 'bdi' || opening.attributes.properties.some(p => ts.isJsxAttribute(p) && p.name.getText() === 'dir'))
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
export function proposeBidiIsolation(finding, source) {
|
|
26
|
+
if (finding.id !== 'RTL.BIDI.ISOLATION:741d2ce2aec3a86cf2db37ea' || finding.path !== REVIEW_SOURCE)
|
|
27
|
+
throw new TransformationRejected('UNSUPPORTED_FINDING_IDENTITY');
|
|
28
|
+
const file = ts.createSourceFile(REVIEW_SOURCE, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
29
|
+
let target;
|
|
30
|
+
function visit(node) { if (ts.isJsxExpression(node) && node.getStart(file) === finding.range.start.offset && node.end === finding.range.end.offset)
|
|
31
|
+
target = node; ts.forEachChild(node, visit); }
|
|
32
|
+
visit(file);
|
|
33
|
+
if (!target)
|
|
34
|
+
throw new TransformationRejected('UNSUPPORTED_AST_RANGE');
|
|
35
|
+
if (!target.expression || !ts.isPropertyAccessExpression(target.expression) || target.expression.name.text !== 'id')
|
|
36
|
+
throw new TransformationRejected('AMBIGUOUS_TOKEN_EXPRESSION');
|
|
37
|
+
if (hasIsolation(target))
|
|
38
|
+
throw new TransformationRejected('ALREADY_ISOLATED');
|
|
39
|
+
if (!target.parent || !(ts.isJsxElement(target.parent) || ts.isJsxFragment(target.parent)))
|
|
40
|
+
throw new TransformationRejected('UNSUPPORTED_WRAPPER');
|
|
41
|
+
const original = source.slice(finding.range.start.offset, finding.range.end.offset);
|
|
42
|
+
if (original !== '{i.id}')
|
|
43
|
+
throw new TransformationRejected('SOURCE_RANGE_MISMATCH');
|
|
44
|
+
return { transformationId: BIDI_TRANSFORMATION_ID, reason: 'Direct invoice ID property access in JSX; wrap the exact expression in auto-direction bidi isolation.', patch: { findingId: finding.id, path: REVIEW_SOURCE, startOffset: finding.range.start.offset, endOffset: finding.range.end.offset, expectedSha256: sha(original), replacement: '<bdi dir="auto">{i.id}</bdi>' } };
|
|
45
|
+
}
|
|
46
|
+
export async function dryRunBidiIsolation(session, finding, source) {
|
|
47
|
+
const proposal = proposeBidiIsolation(finding, source);
|
|
48
|
+
const candidate = await applyReviewPatch(session, proposal.patch);
|
|
49
|
+
return { proposal, candidate };
|
|
50
|
+
}
|
|
51
|
+
export function analyzeBidiIsolation(finding, source) {
|
|
52
|
+
return proposeBidiIsolation(finding, source);
|
|
53
|
+
}
|
package/dist/coverage.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
2
|
+
import { hash } from './model.js';
|
|
3
|
+
const presentation = new Set(['color', 'bgcolor', 'backgroundColor', 'borderColor', 'fill', 'stroke', 'fontSize', 'fontWeight', 'opacity']);
|
|
4
|
+
export function classifyDiagnostics(diagnostics, evidence, sources, policy) {
|
|
5
|
+
return diagnostics.map(d => {
|
|
6
|
+
let blocking = true, impact = 'DIRECTIONAL_UNSUPPORTED', rationale = 'Unresolved styling may contain directional declarations; safe classification is incomplete.';
|
|
7
|
+
if (d.code.endsWith('_PARSE') || d.code === 'SOURCE_COVERAGE') {
|
|
8
|
+
impact = 'SOURCE_FAILURE';
|
|
9
|
+
rationale = 'Source/parser coverage failed.';
|
|
10
|
+
}
|
|
11
|
+
else if (d.code === 'DYNAMIC_VALUE') {
|
|
12
|
+
const e = evidence.find(e => e.path === d.path && e.range.start.offset <= d.range.start.offset && e.range.end.offset >= d.range.end.offset);
|
|
13
|
+
const exception = e ? policy.dynamicExceptions.find(x => x.path === e.path && x.property === e.property && x.valueDigest === hash(e.value) && x.sourceDigest === hash(sources.get(e.path) ?? '')) : undefined;
|
|
14
|
+
if (e && (presentation.has(e.property) || exception)) {
|
|
15
|
+
blocking = false;
|
|
16
|
+
impact = 'NONBLOCKING_DYNAMIC';
|
|
17
|
+
rationale = exception ? exception.reason + ' Source and expression fingerprints match the data-only review exception.' : 'Dynamic presentation value does not block the current directional rules; expression is retained and not evaluated.';
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
else if (d.code === 'UNRESOLVED_SX_OWNER') {
|
|
21
|
+
const raw = (sources.get(d.path) ?? '').slice(d.range.start.offset, d.range.end.offset);
|
|
22
|
+
const sf = ts.createSourceFile('fragment.tsx', `<X ${raw}/>`, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
23
|
+
let safe = false;
|
|
24
|
+
function visit(n) { if (ts.isJsxAttribute(n) && n.name.getText(sf) === 'sx' && n.initializer && ts.isJsxExpression(n.initializer) && n.initializer.expression && ts.isObjectLiteralExpression(n.initializer.expression))
|
|
25
|
+
safe = n.initializer.expression.properties.every(p => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && presentation.has(p.name.text) && (ts.isNumericLiteral(p.initializer) || ts.isStringLiteral(p.initializer))); ts.forEachChild(n, visit); }
|
|
26
|
+
visit(sf);
|
|
27
|
+
if (safe) {
|
|
28
|
+
blocking = false;
|
|
29
|
+
impact = 'NONBLOCKING_DYNAMIC';
|
|
30
|
+
rationale = 'Unknown component owner, but the entire literal sx object contains only non-directional presentation keys.';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return { ...d, impact, blocking, rationale };
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
export const exitCode = (complete, findings, gate) => !complete ? 2 : gate && findings > 0 ? 1 : 0;
|
package/dist/css.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import postcss from "postcss";
|
|
2
|
+
import scss from "postcss-scss";
|
|
3
|
+
import valueParser from "postcss-value-parser";
|
|
4
|
+
import { fact, range } from "./model.js";
|
|
5
|
+
export function extractCss(path, original, fragment = original, base = 0, mechanism = "css", context = "stylesheet") {
|
|
6
|
+
const evidence = [], diagnostics = [];
|
|
7
|
+
try {
|
|
8
|
+
const root = postcss.parse(fragment, { from: undefined });
|
|
9
|
+
root.walkDecls(d => {
|
|
10
|
+
const start = base + d.source.start.offset, end = base + d.source.end.offset;
|
|
11
|
+
const parents = [];
|
|
12
|
+
let p = d.parent;
|
|
13
|
+
while (p && p.type !== "root") {
|
|
14
|
+
parents.unshift(p.type === "rule" ? p.selector : p.type === "atrule" ? `@${p.name} ${p.params}` : 'container');
|
|
15
|
+
p = p.parent;
|
|
16
|
+
}
|
|
17
|
+
evidence.push(fact(path, original, mechanism, `${context}/${parents.join("/")}`, d.prop, d.value, start, end, "css", valueParser(d.value).nodes.map(n => valueParser.stringify(n))));
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
diagnostics.push({ path, code: "CSS_PARSE", message: "CSS fragment could not be parsed; coverage incomplete.", range: range(original, base, base + fragment.length) });
|
|
22
|
+
}
|
|
23
|
+
return { evidence, diagnostics };
|
|
24
|
+
}
|
|
25
|
+
export function extractScss(path, original) {
|
|
26
|
+
const evidence = [], diagnostics = [];
|
|
27
|
+
const coverage = (message, start, end) => diagnostics.push({ path, code: 'SOURCE_COVERAGE', message, range: range(original, start, end) });
|
|
28
|
+
if (/@(?:use|forward|import)\b/.test(original))
|
|
29
|
+
coverage('SCSS imports are not resolved; coverage is incomplete.', 0, original.length);
|
|
30
|
+
if (/#\{/.test(original))
|
|
31
|
+
coverage('SCSS interpolation is not evaluated; coverage is incomplete.', 0, original.length);
|
|
32
|
+
if (/@(?:mixin|include)\b/.test(original))
|
|
33
|
+
coverage('SCSS mixins are not expanded; coverage is incomplete.', 0, original.length);
|
|
34
|
+
try {
|
|
35
|
+
const root = scss.parse(original, { from: undefined });
|
|
36
|
+
root.walkDecls(d => {
|
|
37
|
+
if (/#\{/.test(original))
|
|
38
|
+
return;
|
|
39
|
+
let parent = d.parent, insideMixin = false;
|
|
40
|
+
while (parent && parent.type !== 'root') {
|
|
41
|
+
if (parent.type === 'atrule' && parent.name === 'mixin')
|
|
42
|
+
insideMixin = true;
|
|
43
|
+
parent = parent.parent;
|
|
44
|
+
}
|
|
45
|
+
if (insideMixin || /#\{/.test(d.toString()))
|
|
46
|
+
return;
|
|
47
|
+
const start = d.source.start.offset, end = d.source.end.offset;
|
|
48
|
+
const parents = [];
|
|
49
|
+
let p = d.parent;
|
|
50
|
+
while (p && p.type !== 'root') {
|
|
51
|
+
parents.unshift(p.type === 'rule' ? p.selector : p.type === 'atrule' ? `@${p.name} ${p.params}` : 'container');
|
|
52
|
+
p = p.parent;
|
|
53
|
+
}
|
|
54
|
+
evidence.push(fact(path, original, 'css', `stylesheet/${parents.join('/')}`, d.prop, d.value, start, end, 'scss-css', valueParser(d.value).nodes.map(n => valueParser.stringify(n))));
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
coverage('SCSS source could not be parsed; coverage is incomplete.', 0, original.length);
|
|
59
|
+
}
|
|
60
|
+
return { evidence, diagnostics };
|
|
61
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
export const dashboardClientSource = [
|
|
2
|
+
`(()=>{const d=JSON.parse(document.getElementById('rtl-dashboard-data').textContent),companionOrigin=window.__RTL_COMPANION_ORIGIN__||'http://127.0.0.1:4318',r=document.getElementById('dashboard'),el=(t,x='',c='')=>{const n=document.createElement(t);`,
|
|
3
|
+
`if(c)n.className=c;`,
|
|
4
|
+
`if(x!==undefined)n.textContent=String(x);`,
|
|
5
|
+
`return n},severityLabel=x=>(__SEVERITY_LABELS__[x]??x),b=x=>{const n=el('bdi',x);`,
|
|
6
|
+
`n.dir='auto';`,
|
|
7
|
+
`return n},all=Object.values(d.queue).flat().sort((a,z)=>a.path<z.path?-1:a.path>z.path?1:a.line-z.line||a.column-z.column),by=new Map(all.map(f=>[f.id,f])),sn=new Map((d.sourceSnippets?.sources||[]).map(x=>[x.id,x])),rf=new Map((d.sourceSnippets?.findings||[]).map(x=>[x.findingId,x])),s={file:null,finding:null,app:'all',q:'',severity:'all',status:'all',eligibility:'all',category:'all',sort:'path'},app=el('div','','app'),top=el('header','','top'),brand=el('div','RTL Migration Analyzer v3','brand');`,
|
|
8
|
+
`brand.append(el('small','Analyze · Explore · Fix · Migrate to RTL'));`,
|
|
9
|
+
`top.append(brand);`,
|
|
10
|
+
`const nav=el('nav','','nav');`,
|
|
11
|
+
`['▥ Overview','</> Code Explorer','⚠ Findings','∿ Diagnostics','▤ Rules','▤ Reports'].forEach((x,i)=>{const q=el('button',x,i===1?'active':'disabled');`,
|
|
12
|
+
`q.type='button';`,
|
|
13
|
+
`if(i!==1){q.disabled=true;`,
|
|
14
|
+
`q.title='Coming soon'}nav.append(q)});`,
|
|
15
|
+
`top.append(nav);`,
|
|
16
|
+
`const tools=el('div','','tools'),sw=el('div','','search-wrap');`,
|
|
17
|
+
`sw.append(el('span','⌕'));`,
|
|
18
|
+
`const search=el('input');`,
|
|
19
|
+
`search.placeholder='Search findings';`,
|
|
20
|
+
`search.setAttribute('aria-label','Search findings');`,
|
|
21
|
+
`sw.append(search);`,
|
|
22
|
+
`tools.append(sw);`,
|
|
23
|
+
`const filters=el('section','','finding-filters'),filterTitle=el('strong','Findings: search and filters'),filterSummary=el('span','','filter-summary'),makeSelect=(label,values,key)=>{const wrap=el('label','', 'filter-control'),select=el('select');wrap.append(el('span',label),select);values.forEach(x=>select.append(new Option(x[1],x[0])));select.value=s[key];select.onchange=()=>{s[key]=select.value;writeUrl();refresh()};filters.append(wrap);return select};`,
|
|
24
|
+
`filters.append(filterTitle);`,
|
|
25
|
+
`const severityFilter=makeSelect('Severity',[['all','All severities'],['Major','Major'],['Minor','Minor'],['Info','Info']], 'severity'),statusFilter=makeSelect('Review status',[['all','All review statuses'],['Not Reviewed','Not Reviewed'],['Needs Manual Investigation','Needs Manual Investigation'],['Candidate Proposed','Candidate Proposed'],['Validation Failed','Validation Failed'],['Ready for Review','Ready for Review'],['Approved','Approved'],['Rejected','Rejected']], 'status'),eligibilityFilter=makeSelect('Codemod eligibility',[['all','All eligibility'],['MANUAL','Manual'],['ASSISTED','Assisted'],['AUTOMATED_ELIGIBLE','Automated eligible']], 'eligibility'),categoryFilter=makeSelect('Rule category',[['all','All categories'],...([...new Set(all.map(f=>f.category))].sort().map(x=>[x,x]))], 'category'),sortFilter=makeSelect('Sort by',[['path','File path'],['severity','Severity'],['status','Review status'],['rule','Rule ID']], 'sort');`,
|
|
26
|
+
`const clear=el('button','Clear filters');clear.type='button';clear.onclick=()=>{s.q='';search.value='';s.app='all';s.severity=s.status=s.eligibility=s.category='all';s.sort='path';sel.value='all';severityFilter.value=statusFilter.value=eligibilityFilter.value=categoryFilter.value='all';sortFilter.value='path';writeUrl();refresh()};filters.append(clear,filterSummary);`,
|
|
27
|
+
`app.append(filters);`,
|
|
28
|
+
`top.append(tools,el('span',d.complete?'SCAN COMPLETE':'SCAN INCOMPLETE','status '+(d.complete?'':'warn')));`,
|
|
29
|
+
`const rescan=el('section','','rescan-panel'),rescanButton=el('button','Rescan authoritative report'),rescanState=el('p','No rescan submitted','rescan-state'),rescanHistory=el('div','','rescan-history'),showRescan=x=>{if(!x)return;rescanState.textContent='Rescan persisted: '+x.reconciliation.length+' findings reconciled';rescanHistory.replaceChildren(...x.reconciliation.map(y=>el('p',y.findingId+' · '+y.status+' · '+y.confidence)))};fetch(companionOrigin+'/review/rescan').then(r=>r.ok?r.json():Promise.reject()).then(x=>showRescan(x.scans?.[0])).catch(()=>{});rescanButton.onclick=()=>{rescanButton.disabled=true;const findings=Object.values(d.queue).flat(),manifest={scanId:crypto.randomUUID?.()||String(Date.now()),inputDigest:d.inputDigest,policyDigest:d.policyDigest,timestamp:new Date().toISOString(),sourceCoverage:{complete:d.complete,filesAnalyzed:d.filesAnalyzed,filesExpected:d.filesAnalyzed},findings};fetch(companionOrigin+'/review/rescan',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({project:'invoicing',manifest})}).then(r=>r.ok?r.json():r.json().then(x=>Promise.reject(new Error(x.error||'RESCAN_FAILED')))).then(showRescan).catch(e=>{rescanState.textContent=e.message}).finally(()=>{rescanButton.disabled=false})};rescan.append(el('h2','Durable Rescan'),rescanState,rescanButton,rescanHistory);app.append(rescan);`,
|
|
30
|
+
`const progress=el('section','','migration-progress'),progressBody=el('div','','progress-body');progress.append(el('h2','Migration Progress'),progressBody);const renderProgress=x=>{progressBody.replaceChildren(el('p','Total current findings: '+x.totalFindings),el('p','Validated: '+x.validated+' · Outstanding: '+x.outstanding),el('p','Progress: '+x.progressPercent+'%'),el('p','Recommendations: '+Object.entries(x.recommendationDistribution).map(([k,v])=>k+' '+v).join(' · ')),el('p','Lifecycle: '+Object.entries(x.lifecycleDistribution).map(([k,v])=>k+' '+v).join(' · ')),el('p','Rescan: '+Object.entries(x.reconciliationDistribution).map(([k,v])=>k+' '+v).join(' · ')),...x.findings.map(f=>el('p',f.findingId+' · '+f.recommendation+' · '+f.lifecycle+' · '+f.reconciliation+' · evidence '+f.evidenceCount)))};fetch(companionOrigin+'/review/progress').then(r=>r.ok?r.json():Promise.reject()).then(renderProgress).catch(()=>progressBody.append(el('p','Progress unavailable; companion required')));app.append(progress);`,
|
|
31
|
+
`app.append(top);`,
|
|
32
|
+
`const sv=d.breakdowns.severity||[],major=sv.find(x=>x.name==='Major')?.count||0,minor=sv.find(x=>x.name==='Minor')?.count||0,info=sv.find(x=>x.name==='Info')?.count||0,rawTotal=major+minor+info,total=rawTotal||1,pct=x=>Math.round(x/total*100),sum=el('section','','summary'),wc=el('div','','card workspace-card');`,
|
|
33
|
+
`wc.append(el('span','◈','workspace-icon'),el('div'));`,
|
|
34
|
+
`wc.lastChild.append(el('strong','Workspace'),el('span',d.filesAnalyzed+' files analyzed · '+d.findings+' findings'),el('span',d.uniqueAffectedFiles+' affected files · '+d.diagnostics+' diagnostics · '+d.blockingDiagnostics+' blocking','workspace-secondary'),el('b',d.complete?'✓ Scan complete':'! Scan incomplete','workspace-status'));`,
|
|
35
|
+
`sum.append(wc);`,
|
|
36
|
+
`[['Total findings',d.findings,'']].forEach(x=>{const c=el('div','','card '+x[2]);`,
|
|
37
|
+
`c.append(el('strong',x[1]),el('span',x[0]));`,
|
|
38
|
+
`sum.append(c)});`,
|
|
39
|
+
`[['⚠','High Priority','Major',major,'red'],['△','Low Priority','Minor',minor,'amber'],['ⓘ','Informational','Info',info,'blue']].forEach(x=>{const c=el('div','','card severity-card '+x[4]);c.setAttribute('aria-label',x[1]+' ('+x[2]+'): '+x[3]+' findings');c.append(el('strong',x[0]+' '+x[3]),el('span',x[1]+' · '+x[2]));sum.append(c)});`,
|
|
40
|
+
`const actionCard=el('div','','card green');actionCard.append(el('strong',d.actionableFindings),el('span','Actionable findings'));sum.append(actionCard);`,
|
|
41
|
+
`const chart=el('div','','card severity-chart'),donut=el('div','','donut');`,
|
|
42
|
+
`donut.style.setProperty('--major',(major/total*100)+'%');`,
|
|
43
|
+
`donut.style.setProperty('--minor',((major+minor)/total*100)+'%');`,
|
|
44
|
+
`donut.setAttribute('role','img');donut.setAttribute('aria-label','Severity distribution: '+major+' Major, '+minor+' Minor, '+info+' Info; '+rawTotal+' total findings');donut.style.position='relative';`,
|
|
45
|
+
`const totalText=el('strong',String(rawTotal));totalText.style.position='absolute';totalText.style.inset='18px 0 auto';totalText.style.textAlign='center';totalText.style.fontSize='16px';const totalLabel=el('span','Total Findings');totalLabel.style.position='absolute';totalLabel.style.top='37px';totalLabel.style.left='0';totalLabel.style.right='0';totalLabel.style.textAlign='center';totalLabel.style.fontSize='7px';donut.append(totalText,totalLabel);`,
|
|
46
|
+
`chart.append(donut);`,
|
|
47
|
+
`const lg=el('div','','legend');`,
|
|
48
|
+
`[['r','Major',major],['a','Minor',minor],['b','Info',info]].forEach(x=>{const p=el('div');`,
|
|
49
|
+
`p.append(el('i','',x[0]),el('span',severityLabel(x[1])+' · '+x[2]+' · '+pct(x[2])+'%'));`,
|
|
50
|
+
`lg.append(p)});`,
|
|
51
|
+
`chart.append(lg);`,
|
|
52
|
+
`sum.append(chart);`,
|
|
53
|
+
`app.append(sum);`,
|
|
54
|
+
`const sr=el('section','','scope-row'),scope=el('div','','scope');`,
|
|
55
|
+
`scope.append(el('span','◎','scope-icon'),el('div'));`,
|
|
56
|
+
`scope.children[1].append(el('h2','Analysis Scope'),el('p','Choose what to explore'));`,
|
|
57
|
+
`const sel=el('select');`,
|
|
58
|
+
`[['all','Entire Workspace'],...(d.scopeBreakdown?.directApplications||[]).map(x=>[x.name,x.name])].forEach(x=>sel.append(new Option(x[1],x[0])));`,
|
|
59
|
+
`scope.append(sel);`,
|
|
60
|
+
`const projects=el('div','','projects');`,
|
|
61
|
+
`const scopeCards=[...(d.scopeBreakdown?.directApplications||[]).map(x=>({name:x.name,count:x.count,kind:'Direct application'})),{name:'Shared library ownership',count:d.scopeBreakdown?.sharedLibraryOwnership??'Not available',kind:'Ownership'}, {name:'Shared library impact',count:d.scopeBreakdown?.sharedLibraryImpact??'Not available',kind:'Impact'}, {name:'Unresolved reachability',count:d.scopeBreakdown?.unresolvedReachability??'Not available',kind:'Unknown attribution'}];`,
|
|
62
|
+
`scopeCards.forEach(x=>{const q=el('button','','project');`,
|
|
63
|
+
`q.type='button';q.disabled=x.kind!=='Direct application';q.setAttribute('aria-label',x.kind+': '+x.name+' '+x.count+' findings; counts are not additive and may overlap; attribution is not verified for unavailable dimensions');q.append(el('strong',x.name),el('span',x.kind+' · '+x.count+' findings'));`,
|
|
64
|
+
`q.onclick=()=>{if(x.kind!=='Direct application')return;sel.value=x.name;`,
|
|
65
|
+
`s.app=x.name;`,
|
|
66
|
+
`writeUrl();refresh()};`,
|
|
67
|
+
`projects.append(q)});`,
|
|
68
|
+
`sr.append(scope,projects);`,
|
|
69
|
+
`app.append(sr);`,
|
|
70
|
+
`const wr=el('main','','workspace'),side=el('section','','pane'),tp=el('section','','pane'),fp=el('section','','pane'),sp=el('section','','pane'),dp=el('section','','pane'),sideBody=el('div','','side'),tree=el('div','','scroll tree'),finds=el('div','','scroll finding-list'),meta=el('div','','meta'),code=el('div','','code-scroll'),details=el('div','','scroll details');`,
|
|
71
|
+
`['Code Explorer','Findings','Diagnostics','Rules & Heuristics','Reports'].forEach((x,i)=>{const q=el('button',x,i===0?'active':'disabled');`,
|
|
72
|
+
`q.type='button';`,
|
|
73
|
+
`q.disabled=i!==0;`,
|
|
74
|
+
`sideBody.append(q)});`,
|
|
75
|
+
`side.append(el('div','NAVIGATION','head'),sideBody);`,
|
|
76
|
+
`tp.append(el('div','PROJECT EXPLORER','head'),tree);`,
|
|
77
|
+
`fp.append(el('div','FINDINGS','head'),finds);`,
|
|
78
|
+
`const cw=el('div','','code');`,
|
|
79
|
+
`cw.append(meta,code);`,
|
|
80
|
+
`sp.append(el('div','SOURCE PREVIEW','head'),cw);`,
|
|
81
|
+
`dp.append(el('div','FINDING DETAILS','head'),details);`,
|
|
82
|
+
`wr.append(side,tp,fp,sp,dp);`,
|
|
83
|
+
`app.append(wr);`,
|
|
84
|
+
`const srLive=el('div','','sr-only');srLive.setAttribute('role','status');srLive.setAttribute('aria-live','polite');srLive.setAttribute('aria-atomic','true');app.append(srLive);r.append(app);document.addEventListener('keydown',e=>{const q=document.querySelector('dialog[open]');if(!q||e.key!=='Tab')return;const focus=[...q.querySelectorAll('button:not(:disabled),input:not(:disabled),textarea:not(:disabled),select:not(:disabled),a[href]')];if(!focus.length)return;const first=focus[0],last=focus[focus.length-1];if(e.shiftKey&&document.activeElement===first){e.preventDefault();last.focus()}else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first.focus()}});`,
|
|
85
|
+
`const match=()=>all.filter(f=>(s.app==='all'||f.applications.includes(s.app))&&(s.severity==='all'||f.severity===s.severity)&&(s.status==='all'||f.reviewStatus===s.status)&&(s.eligibility==='all'||f.eligibility===s.eligibility)&&(s.category==='all'||f.category===s.category)&&(!s.q||[f.id,f.ruleId,f.path,f.title,f.owner].some(x=>String(x).toLowerCase().includes(s.q.toLowerCase())))),sortRows=rows=>rows.slice().sort((a,z)=>s.sort==='severity'?({Major:0,Minor:1,Info:2}[a.severity]??9)-({Major:0,Minor:1,Info:2}[z.severity]??9)||a.path.localeCompare(z.path):s.sort==='status'?a.reviewStatus.localeCompare(z.reviewStatus)||a.path.localeCompare(z.path):s.sort==='rule'?a.ruleId.localeCompare(z.ruleId)||a.path.localeCompare(z.path):a.path.localeCompare(z.path)||a.line-z.line||a.column-z.column),vis=()=>sortRows(match()).filter(f=>!s.file||f.path===s.file);`,
|
|
86
|
+
`const previewOrigin='http://127.0.0.1:4318',previewState={available:false,checked:false};`,
|
|
87
|
+
`function treeRender(){tree.replaceChildren();`,
|
|
88
|
+
`const walk=(f,p)=>{f.folders.forEach(c=>{const z=document.createElement('details');`,
|
|
89
|
+
`z.open=true;`,
|
|
90
|
+
`z.className='folder';`,
|
|
91
|
+
`z.append(el('summary',c.name+' ('+c.findingCount+')'));`,
|
|
92
|
+
`walk(c,z);`,
|
|
93
|
+
`p.append(z)});`,
|
|
94
|
+
`f.files.forEach(x=>{if(!match().some(f=>f.path===x.path))return;`,
|
|
95
|
+
`const q=el('button','','file'+(s.file===x.path?' selected':''));`,
|
|
96
|
+
`q.type='button';`,
|
|
97
|
+
`q.append(el('span','▣'),b(x.name),el('span',x.findingCount,'count'));`,
|
|
98
|
+
`q.onclick=()=>selectFile(x.path);`,
|
|
99
|
+
`p.append(q)})};`,
|
|
100
|
+
`walk(d.explorer.root,tree)}function listRender(){finds.replaceChildren();`,
|
|
101
|
+
`const rows=vis(),matching=match();filterSummary.textContent=matching.length+' matching of '+all.length+' findings · '+all.filter(f=>!['INFORMATIONAL','INTENTIONAL_LTR'].includes(f.category)).length+' actionable · '+all.filter(f=>f.reviewStatus!=='Not Reviewed').length+'/'+all.length+' reviewed';`,
|
|
102
|
+
`if(!rows.length){finds.append(el('p','No findings match this scope.','empty'));`,
|
|
103
|
+
`return}rows.forEach(f=>{const q=el('button','','finding'+(s.finding?.id===f.id?' selected':''));`,
|
|
104
|
+
`q.type='button';`,
|
|
105
|
+
`q.append(el('strong',f.title),el('small',f.ruleId+' · '+f.path+':'+f.line+':'+f.column));`,
|
|
106
|
+
`q.onclick=()=>select(f.id);`,
|
|
107
|
+
`finds.append(q)})}function source(f){code.replaceChildren();`,
|
|
108
|
+
`meta.replaceChildren();`,
|
|
109
|
+
`if(!f){code.append(el('p','Select a finding to inspect source.','empty'));`,
|
|
110
|
+
`return}meta.append(b(f.path+':'+f.line+':'+f.column));`,
|
|
111
|
+
`if(!d.sourceEmbeddingEnabled){code.append(el('p','Source preview unavailable. Regenerate with --embed-source-snippets.','empty'));`,
|
|
112
|
+
`return}const x=rf.get(f.id),w=x?.available?sn.get(x.sourceId):null;`,
|
|
113
|
+
`if(!w){code.append(el('p','Source preview unavailable: '+(x?.reason||'UNAVAILABLE'),'empty'));`,
|
|
114
|
+
`return}w.lines.forEach(l=>{const q=el('div','','line'+(l.highlighted?' hit':''));`,
|
|
115
|
+
`q.append(el('span',l.number,'no'),el('span',l.text,'text'));`,
|
|
116
|
+
`code.append(q)})}let reviewSession=null;function reviewPanel(f){const box=el('div','','review-panel'),state=el('span','Offline assessment: '+f.reviewStatus,'review-state');box.append(el('strong','Finding Review'),el('p','Embedded offline assessment (not persisted). Persisted decisions require the local companion.'),state);const start=el('button','Propose Candidate');start.onclick=()=>{const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};fetch(previewOrigin+'/review/sessions',{method:'POST'}).then(r=>r.ok?r.json():r.json().then(x=>Promise.reject(new Error(x.error||'CANDIDATE_SESSION_FAILED')))).then(x=>{reviewSession=x;state.textContent='Candidate session proposed';start.disabled=true;box.append(el('p','Candidate session '+x.id+' created on '+x.candidateOrigin+'.','review-note'));return fetch(previewOrigin+'/review/records',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({...identity,status:'Candidate Proposed',reviewerNotes:'',evidenceReferences:[],candidateSessionId:x.id})}).then(r=>r.ok?r.json():r.json().then(y=>Promise.reject(new Error(y.error||'CANDIDATE_REVIEW_PERSIST_FAILED')))).then(()=>{window.dispatchEvent(new Event('review-record-updated'));const runtime=el('button','Start Candidate Preview');runtime.onclick=()=>fetch(previewOrigin+'/review/sessions/'+encodeURIComponent(x.id)+'/runtime/start',{method:'POST'}).then(r=>r.ok?r.json():Promise.reject()).then(info=>{if(info.runtime?.status!=='healthy')throw new Error();runtime.disabled=true;['ltr','rtl'].forEach(mode=>{const q=el('button','Open Candidate '+mode.toUpperCase()+' Preview');q.onclick=()=>window.open(info.urls[mode],'_blank','noopener,noreferrer');box.append(q)})}).catch(()=>{state.textContent='Candidate runtime unavailable';previewUnavailable(box)});box.append(runtime)}).catch(error=>{state.textContent=error.message;start.disabled=false})}).catch(error=>{state.textContent=error.message;previewUnavailable(box)});};box.append(start);return box}function decisionPanel(f){const box=el('section','','decision-panel'),identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion},recommendation=f.eligibility==='AUTOMATED_ELIGIBLE'?'Automated':f.eligibility==='ASSISTED'?'Assisted':'Manual',state=el('p','Loading persisted decision…','empty'),select=document.createElement('select'),reason=el('textarea'),save=el('button','Save Migration Decision');box.append(el('h3','Migration Treatment Decision'),el('p','Recommendation: '+recommendation),el('p','Rationale: '+f.eligibilityReason),el('p','Blockers: '+(f.eligibilityBlockers.join('; ')||'None')),state);['Automated','Assisted','Manual'].forEach(x=>select.append(new Option(x,x)));reason.placeholder='Override reason (required when changing the recommendation)';box.append(select,reason,save);let sourceDigest='';const url=previewOrigin+'/review/decisions?'+new URLSearchParams(identity);fetch(url).then(r=>r.json()).then(x=>{sourceDigest=x.sourceDigest||'';if(x.decision){select.value=x.decision.selectedTreatment;reason.value=x.decision.overrideReason||'';state.textContent='Saved '+x.decision.selectedTreatment+' decision at '+x.decision.timestamp}else{select.value=recommendation;state.textContent='No saved decision'}}).catch(()=>{state.textContent='Decision persistence unavailable';save.disabled=true});save.onclick=()=>{const selected=select.value;if(selected!==recommendation&&!reason.value.trim()){state.textContent='Override reason is required';return}if(selected==='Automated'&&recommendation!=='Automated'){state.textContent='Automated is blocked by eligibility';return}save.disabled=true;fetch(previewOrigin+'/review/decisions',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({...identity,sourceDigest,recommendation,recommendationRationale:f.eligibilityReason,eligibilityConstraints:f.eligibilityBlockers,blockers:f.eligibilityBlockers,selectedTreatment:selected,...(selected!==recommendation?{overrideReason:reason.value.trim()}:{})})}).then(r=>r.ok?r.json():r.json().then(y=>Promise.reject(new Error(y.error||'DECISION_FAILED')))).then(x=>{state.textContent='Saved '+x.decision.selectedTreatment+' decision at '+x.decision.timestamp;save.disabled=false}).catch(e=>{state.textContent=e.message;save.disabled=false})};return box}function detail(f){details.replaceChildren();`,
|
|
117
|
+
`function reviewWorkspace(f){const box=el('section','','review-workspace'),evidence=el('div','','review-evidence'),candidate=el('div','','candidate-evidence'),notes=el('textarea'),refs=el('input'),actions=el('div','','actions'),live=el('p','','review-live');box.append(el('h3','Review Workspace'),el('p','The persisted companion record is authoritative when available. Approval is a review decision only; it never modifies source.'),evidence,candidate,el('h3','Decision'),notes,refs,actions,live);notes.placeholder='Reviewer notes';refs.placeholder='Evidence references, comma-separated';live.setAttribute('aria-live','polite');const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};const recordUrl=previewOrigin+'/review/records?'+new URLSearchParams(identity);let current=null;const blocked=message=>{const p=el('p',message,'review-blocked');actions.append(p)};const save=status=>{const evidenceReferences=refs.value.split(',').map(x=>x.trim()).filter(Boolean);if(status==='Rejected'&&!notes.value.trim()){live.textContent='Rejected decisions require reviewer notes';return}if((status==='Ready for Review'||status==='Approved')&&(!notes.value.trim()||!evidenceReferences.length)){live.textContent='Ready for Review and Approval require reviewer notes and evidence references';return}if(status==='Approved'&&!window.confirm('Approve this review decision? Approval does not modify source files.'))return;if(status==='Rejected'&&!window.confirm('Reject this review decision? The source remains unchanged.'))return;actions.querySelectorAll('button').forEach(b=>b.disabled=true);fetch(previewOrigin+'/review/records',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({...identity,status,reviewerNotes:notes.value,evidenceReferences,...(reviewSession?.id?{candidateSessionId:reviewSession.id}:{})})}).then(r=>r.ok?r.json():r.json().then(x=>Promise.reject(new Error(x.error||'REVIEW_FAILED')))).then(x=>{current=x.record;renderRecord(x.record);live.textContent='Review state updated'}).catch(error=>{live.textContent=error.message;load()})};const renderRecord=record=>{current=record||null;actions.replaceChildren();evidence.replaceChildren(el('h3','Review Status'));if(record){evidence.append(el('p','Persisted review status: '+record.status,'review-state'),el('p','Last updated: '+record.timestamp),el('p','Reviewer notes: '+(record.reviewerNotes||'None')),el('p','Evidence readiness: '+(record.evidenceReferences?.length?'Evidence references present':'No evidence references')));notes.value=record.reviewerNotes||'';refs.value=(record.evidenceReferences||[]).join(', ')}else{evidence.append(el('p','No persisted review decision for this report identity.','empty'),el('p','Embedded offline assessment (not persisted): '+f.reviewStatus));notes.value='';refs.value=''}const status=record?.status||'Not Reviewed';const add=(label,next,enabled=true)=>{const b=el('button',label);b.disabled=!enabled;b.onclick=()=>save(next);actions.append(b)};if(status==='Not Reviewed'){add('Start Investigation','Needs Manual Investigation');add('Mark Verified Correct','Verified Correct')}if(status==='Needs Manual Investigation'){add('Mark Verified Correct','Verified Correct');add('Reject','Rejected')}if(status==='Candidate Proposed'||status==='Validation Failed'){const ready=!!notes.value.trim()&&!!refs.value.split(',').map(x=>x.trim()).filter(Boolean).length;add('Mark Ready for Review','Ready for Review',ready);if(!ready)blocked('Mark Ready for Review blocked: add reviewer notes and at least one evidence reference.');add('Request Manual Investigation','Needs Manual Investigation')}if(status==='Ready for Review'){const ready=!!notes.value.trim()&&!!refs.value.split(',').map(x=>x.trim()).filter(Boolean).length;add('Approve','Approved',ready);if(!ready)blocked('Approve blocked: add reviewer notes and at least one evidence reference.');add('Reject','Rejected')}if(status==='Approved'){add('Reject','Rejected')}if(status==='Rejected'){add('Start Investigation','Needs Manual Investigation')}};const load=()=>fetch(recordUrl).then(r=>r.ok?r.json():Promise.reject()).then(x=>{renderRecord(x.record);if(x.record?.candidateSessionId){const sid=encodeURIComponent(x.record.candidateSessionId);fetch(previewOrigin+'/review/sessions/'+sid).then(r=>r.ok?r.json():Promise.reject()).then(session=>{candidate.replaceChildren(el('h3','Candidate Evidence'),el('p','Session '+session.id+' · runtime '+(session.runtime?.status||'not started')));if(session.runtime?.status==='healthy'){['ltr','rtl'].forEach(mode=>{const q=el('button','Open Candidate '+mode.toUpperCase()+' Preview');q.onclick=()=>window.open((mode==='ltr'?session.candidateOrigin+'/invoices':session.candidateOrigin+'/invoices?demo=unmigrated-rtl&lang=ar'),'_blank','noopener,noreferrer');candidate.append(q)});fetch(previewOrigin+'/review/sessions/'+sid+'/diff').then(r=>r.ok?r.json():Promise.reject()).then(info=>candidate.append(el('pre',info.diff,'review-diff'))).catch(()=>candidate.append(el('p','Candidate diff unavailable.','empty')))}else candidate.append(el('p','Candidate runtime is not healthy; live preview unavailable. Archived evidence remains available separately.','empty'))}).catch(()=>candidate.append(el('p','Candidate session unavailable or stale; archived evidence may still be available.','empty')))}}).catch(()=>{evidence.replaceChildren(el('h3','Review Status'),el('p','Companion unavailable. Embedded offline assessment is shown; no persisted decision is available.','preview-unavailable'));actions.replaceChildren();notes.disabled=true;refs.disabled=true});load();return box}function detail(f){details.replaceChildren();}`,
|
|
118
|
+
`function recoverEvidence(f,box){const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};fetch(previewOrigin+'/review/evidence?'+new URLSearchParams(identity)).then(r=>r.ok?r.json():Promise.reject()).then(x=>{const archive=el('section','','archived-evidence');archive.append(el('h3','Archived Evidence · Evidence Details'),el('p','Archived evidence is immutable and does not require a live candidate runtime.'));if(!x.snapshots?.length){archive.append(el('p','No archived evidence is available for this report identity.','empty'));box.append(archive);return}x.snapshots.forEach(s=>{const item=el('details');item.append(el('summary','Snapshot '+s.snapshotId+' · '+s.decision+' · '+s.timestamp));const grid=el('dl','evidence-grid');[['Finding',s.findingId],['Source',s.sourcePath],['Report identity',s.inputDigest+' / '+s.policyDigest],['Patch identity',s.candidatePatchIdentity.path+' · '+s.candidatePatchIdentity.expectedSha256],['Original hash',s.originalSourceSha256],['Candidate hash',s.candidateSourceSha256],['Integrity',s.integritySha256]].forEach(([k,v])=>{grid.append(el('dt',k),el('dd',v))});item.append(grid,el('h4','Archived Code Diff'),el('pre',s.codeDiff,'review-diff'));const validation=el('div','', 'validation-results');validation.append(el('h4','Archived Validation'),el('h4','Browser/DOM evidence'),el('p','Scanner before: '+(s.scannerBefore.findingPresent?'finding present':'finding absent')+' · after: '+(s.scannerAfter.findingPresent?'finding present':'finding absent')),el('p','DOM assertions: '+(s.browserDomValidation.join('; ')||'None recorded')),el('p','Screenshots: '+(s.screenshotReferences.length?s.screenshotReferences.join(', '):'No screenshot artifacts recorded')),s.screenshotReferences.length?s.screenshotReferences.map((reference,index)=>{const url=previewOrigin+'/review/evidence/'+encodeURIComponent(s.snapshotId)+'/screenshot/'+encodeURIComponent(reference)+'?'+new URLSearchParams(identity);const card=el('figure','', 'screenshot-preview');const image=document.createElement('img');image.src=url;image.alt=(reference.includes('original')?'Original ':'Candidate ')+(reference.includes('rtl')?'RTL':'LTR')+' validation screenshot';image.loading='lazy';const caption=el('figcaption',image.alt+' · '+reference);const open=el('a','Open larger preview');open.href=url;open.target='_blank';open.rel='noopener noreferrer';card.append(image,caption,open);return card}):el('p','No screenshot previews are available.','empty'));item.append(validation);archive.append(item)});box.append(archive)}).catch(()=>{const archive=el('section','','archived-evidence');archive.append(el('h3','Archived Evidence · Evidence Details'),el('p','Archived evidence is unavailable or stale for this report identity.','preview-unavailable'));box.append(archive)})}`,
|
|
119
|
+
`function controlledApplyPanel(f){const box=el('section','','controlled-apply');box.append(el('h3','Controlled Apply & Rollback'),el('p','Apply is a separate, explicit action. Review approval alone never modifies source.'));const status=el('p','Checking server-side eligibility…','empty'),evidence=el('div','','apply-evidence'),actions=el('div','','actions'),live=el('p','','apply-live');live.setAttribute('aria-live','polite');box.append(status,evidence,actions,live);const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};const showDialog=(title,message,confirmText,run)=>{const dialog=document.createElement('dialog');dialog.append(el('h3',title),el('p',message));const cancel=el('button','Cancel'),confirm=el('button',confirmText),row=el('div','','actions');row.append(cancel,confirm);dialog.append(row);cancel.onclick=()=>dialog.close();confirm.onclick=async()=>{confirm.disabled=true;cancel.disabled=true;dialog.close();await run()};document.body.append(dialog);dialog.addEventListener('close',()=>dialog.remove(),{once:true});dialog.showModal();confirm.focus()};const renderAudit=()=>fetch(previewOrigin+'/review/audit?sourcePath='+encodeURIComponent(f.path)).then(r=>r.ok?r.json():Promise.reject()).then(x=>{if(!x.events?.length)return;const history=el('section','','audit-history');history.append(el('h4','Audit History'),el('p','Durable operation history; reviewer identity is not inferred.'));[...x.events].sort((a,b)=>Date.parse(a.timestamp)-Date.parse(b.timestamp)).forEach(e=>{const item=el('details');item.append(el('summary',e.type+' · '+e.timestamp));const grid=el('dl','audit-grid');[['Operation',e.type],['Result',e.reason?'Failed':'Recorded'],['Source hash',e.sourceSha256],['Resulting hash',e.resultingSha256||'Not recorded'],['Details',e.reason||'None']].forEach(([k,v])=>{grid.append(el('dt',k),el('dd',v))});history.append(item)});box.append(history)}).catch(()=>{box.append(el('p','Audit history unavailable.','preview-unavailable'))});fetch(previewOrigin+'/review/apply/eligibility?'+new URLSearchParams(identity)).then(r=>r.ok?r.json():Promise.reject()).then(info=>{status.textContent=info.ready?'Ready to Apply':'Blocked: '+(info.reason||'Unavailable');status.className=info.ready?'apply-ready':'apply-blocked';if(!info.evidence){evidence.append(el('p','No approved immutable evidence is available. Apply remains disabled.','empty'));return}const e=info.evidence;evidence.append(el('p','Target: '+info.sourcePath),el('p','Finding: '+info.findingId),el('p','Original hash: '+e.originalSourceSha256),el('p','Candidate hash: '+e.candidateSourceSha256),el('h4','Approved Diff'),el('pre',e.codeDiff,'review-diff'));if(info.ready){const apply=el('button','Apply Change');apply.onclick=()=>showDialog('Confirm Controlled Apply','This will modify '+info.sourcePath+' in the original checkout. Confirm only after reviewing the exact diff above.','Confirm Apply',async()=>{status.textContent='Applying';live.textContent='Applying controlled patch…';try{const r=await fetch(previewOrigin+'/review/apply',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({identity,confirmation:'APPLY_CONFIRMED'})});const x=await r.json();if(!r.ok)throw new Error(x.error||'APPLY_FAILED');status.textContent='Applied to Source';live.textContent='Applied successfully';const rollback=el('button','Rollback Change');rollback.onclick=()=>showDialog('Confirm Rollback','This restores the backed-up original source. If the file changed after apply, rollback will be rejected as a conflict.','Confirm Rollback',async()=>{const rr=await fetch(previewOrigin+'/review/rollback',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(x.receipt)});const rx=await rr.json();if(!rr.ok){status.textContent=rx.error==='ROLLBACK_CONFLICT'?'Recovery required':'Rollback failed';live.textContent=rx.error||'ROLLBACK_FAILED';renderAudit();return}status.textContent='Rolled Back';live.textContent='Rolled back successfully';rollback.disabled=true;renderAudit()});actions.append(rollback);renderAudit()}catch(error){status.textContent=error.message==='ROLLBACK_CONFLICT'?'Recovery required':'Apply failed';live.textContent=error.message}});actions.append(apply)}}).catch(()=>{status.textContent='Controlled Apply unavailable offline';status.className='apply-blocked'});renderAudit();fetch(previewOrigin+'/review/rollback/eligibility?'+new URLSearchParams(identity)).then(r=>r.ok?r.json():Promise.reject()).then(info=>{if(!info.eligible)return;const rollback=el('button','Rollback Change');rollback.onclick=()=>showDialog('Confirm Rollback','This restores the backed-up original source. If the file changed after apply, rollback will be rejected as a conflict.','Confirm Rollback',async()=>{const rr=await fetch(previewOrigin+'/review/rollback',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(info.receipt)});const rx=await rr.json();if(!rr.ok){status.textContent=rx.error==='ROLLBACK_CONFLICT'?'Recovery required':'Rollback failed';live.textContent=rx.error||'ROLLBACK_FAILED';renderAudit();return}status.textContent='Rolled Back';live.textContent='Rolled back successfully';rollback.disabled=true;renderAudit()});actions.append(rollback)}).catch(()=>{});return box}`,
|
|
120
|
+
`function codemodPanel(f){const box=el('section','','codemod-panel');box.append(el('h3','Codemod Dry Run'),el('p','Analysis is read-only. Candidate application is isolated and never changes the original checkout.'));const state=el('p','Not analyzed','empty');const output=el('div','','codemod-output');const actions=el('div','','actions');const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};const finding={...f};const dialog=(run)=>{const q=document.createElement('dialog');q.append(el('h3','Confirm Candidate Apply'),el('p','This writes only to the isolated candidate session. It does not modify the original checkout or approve the review.'));const cancel=el('button','Cancel'),confirm=el('button','Apply to Candidate');const row=el('div','','actions');row.append(cancel,confirm);q.append(row);cancel.onclick=()=>q.close();confirm.onclick=async()=>{confirm.disabled=true;cancel.disabled=true;q.close();await run()};document.body.append(q);q.addEventListener('close',()=>q.remove(),{once:true});q.showModal();confirm.focus()};const analyze=el('button','Analyze Transformation');analyze.onclick=()=>{state.textContent='Analyzing…';fetch(previewOrigin+'/review/codemod/analyze',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({finding})}).then(r=>r.ok?r.json():r.json().then(x=>Promise.reject(new Error(x.error||'ANALYSIS_FAILED')))).then(x=>{state.textContent='Analyzed: '+x.transformationId;output.replaceChildren(el('p','Source hash: '+x.sourceSha256),el('p','Transformation: '+x.transformationId),el('p',x.reason),el('pre',JSON.stringify(x.patch,null,2),'review-diff'));const apply=el('button','Apply to Candidate');apply.onclick=()=>dialog(async()=>{state.textContent='Applying to candidate…';fetch(previewOrigin+'/review/sessions/'+encodeURIComponent(reviewSession?.id||'')+'/codemod/apply',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({finding,confirmation:'CANDIDATE_APPLY_CONFIRMED',sourceSha256:x.sourceSha256})}).then(r=>r.ok?r.json():r.json().then(y=>Promise.reject(new Error(y.error||'CANDIDATE_APPLY_FAILED')))).then(y=>{state.textContent='Candidate-applied patch';output.append(el('p','Candidate hash: '+y.candidateSha256));const diff=el('pre','','review-diff');fetch(previewOrigin+'/review/sessions/'+encodeURIComponent(y.id)+'/diff').then(r=>r.json()).then(z=>{diff.textContent=z.diff;output.append(diff)});}).catch(error=>{state.textContent=error.message==='STALE_SOURCE'?'Stale source':'Candidate apply failed: '+error.message})});actions.append(apply)}).catch(error=>{state.textContent=error.message==='STALE_SOURCE'?'Stale source':'Unsupported or blocked: '+error.message})};box.append(state,output,actions,analyze);return box}`,
|
|
121
|
+
`function validationPanel(f){const box=el('section','','validation-panel');box.append(el('h3','Validation Results'),el('p','Current validation is distinct from archived evidence and review decisions.'));const state=el('p','Idle','validation-state'),output=el('div','','validation-output'),run=el('button','Run Validation'),archive=el('button','Archive Evidence');archive.disabled=true;const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};const section=(title,content)=>{const q=el('details');q.open=true;q.append(el('summary',title),content);return q};run.onclick=()=>{if(!reviewSession?.id){state.textContent='Unavailable: create a candidate session first';return}state.textContent='Running';run.disabled=true;output.replaceChildren(el('p','Validation job running…','empty'));Promise.all([fetch(previewOrigin+'/review/codemod/analyze',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({finding:f})}),fetch(previewOrigin+'/review/sessions/'+encodeURIComponent(reviewSession.id))]).then(async([a,s])=>{const analyzed=await a.json(),session=await s.json();if(!a.ok||!analyzed.patch)throw new Error(analyzed.error||'ANALYSIS_FAILED');return fetch(previewOrigin+'/review/sessions/'+encodeURIComponent(session.id)+'/validate',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({finding:f,patch:analyzed.patch})})}).then(r=>r.ok?r.json():r.json().then(x=>Promise.reject(new Error(x.error||'VALIDATION_FAILED')))).then(x=>{const v=x.result;state.textContent=v.state;const scanner=el('div'); scanner.append(el('p','Completed: '+v.finishedAt));scanner.append(el('p','Scanner before: '+(v.scannerBefore.findingPresent?'finding present':'finding absent')+' · '+v.scannerBefore.resultDigest),el('p','Scanner after: '+(v.scannerAfter.findingPresent?'finding present':'finding absent')+' · '+v.scannerAfter.resultDigest));const browser=el('div');browser.append(el('p','Environment: '+v.environment.node+' · '+v.environment.viewport+' · '+v.environment.locale+' · '+v.environment.timezone),el('p','Original/Candidate LTR and RTL: '+(v.browserDomValidation.filter(x=>x.includes('ltr')||x.includes('rtl')).join('; ')||'No route results recorded')),el('p','DOM: '+(v.browserDomValidation.join('; ')||'None recorded')),el('p','Browser errors: '+(v.browserErrors.join('; ')||'None recorded')),el('p','Screenshots: '+(v.screenshotReferences.length?v.screenshotReferences.join(', '):'No screenshot artifacts recorded')));const identityView=el('dl','validation-identity');[['Job',v.jobId],['Original source hash',v.originalSourceSha256],['Candidate source hash',v.candidateSourceSha256],['Patch path',v.patch.path],['Patch range',v.patch.startOffset+'–'+v.patch.endOffset]].forEach(([k,val])=>{identityView.append(el('dt',k),el('dd',val))});output.replaceChildren(section('Scanner before / after',scanner),section('Browser, DOM and screenshots',browser),section('Source and patch identity',identityView));archive.disabled=v.state!=='Passed';archive.onclick=()=>fetch(previewOrigin+'/review/evidence',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({...identity,candidatePatchIdentity:{path:v.patch.path,expectedSha256:v.patch.expectedSha256,replacementSha256:null},originalSourceSha256:v.originalSourceSha256,candidateSourceSha256:v.candidateSourceSha256,codeDiff:'Validation result '+v.jobId,scannerBefore:v.scannerBefore,scannerAfter:v.scannerAfter,browserDomValidation:v.browserDomValidation,screenshotReferences:v.screenshotReferences,timestamp:v.finishedAt,decision:'Ready for Review',patch:v.patch})}).then(r=>{state.textContent=r.ok?'Evidence Archived':'Archive Failed'})}).catch(error=>{state.textContent=error.message;run.disabled=false;output.replaceChildren(el('p','Validation failed: '+error.message,'preview-unavailable'))})};box.append(state,output,run,archive);return box}`,
|
|
122
|
+
`if(!f){details.append(el('p','Select a finding to view details.','empty'));`,
|
|
123
|
+
`return}details.append(el('h2',f.title));`,
|
|
124
|
+
`const a=el('div','','actions'),back=el('button','← Back to Findings','mobile-back');back.type='button';back.onclick=()=>{document.querySelector('.finding-list')?.scrollIntoView({behavior:'smooth'});document.querySelector('.finding-list .finding.selected')?.focus()};const ordered=vis(),at=ordered.findIndex(x=>x.id===f.id),prev=el('button','Previous finding'),next=el('button','Next finding');prev.disabled=at<=0;next.disabled=at<0||at>=ordered.length-1;prev.onclick=()=>select(ordered[at-1].id);next.onclick=()=>select(ordered[at+1].id);a.append(back,prev,next);`,
|
|
125
|
+
`[['Copy relative path',f.path],['Copy location',f.path+':'+f.line+':'+f.column]].forEach(x=>{const q=el('button',x[0]);`,
|
|
126
|
+
`q.onclick=()=>navigator.clipboard?.writeText(x[1]);`,
|
|
127
|
+
`a.append(q)});`,
|
|
128
|
+
`details.append(a);details.append(el('section','Codemod Eligibility: '+f.eligibility,'eligibility-panel'));details.append(el('p',f.eligibilityReason,'eligibility-reason'));if(f.eligibilityTransformationId)details.append(el('p','Transformation: '+f.eligibilityTransformationId));if(f.eligibilityBlockers.length)details.append(el('p','Blockers: '+f.eligibilityBlockers.join(', '),'eligibility-blockers'));details.append(decisionPanel(f));details.append(reviewPanel(f));const workspace=reviewWorkspace(f);details.append(workspace);recoverEvidence(f,workspace);if(f.eligibilityTransformationId==='bidi-isolate-auto'){details.append(codemodPanel(f));details.append(validationPanel(f))}details.append(controlledApplyPanel(f));`,
|
|
129
|
+
`if(f.previewMappingId){const box=el('div','','preview-box');box.append(el('strong','Owning Route Preview'),el('p','Open the real Invoicing application route.'));const buttons=el('div','','actions');[['Open LTR Preview','ltr'],['Open RTL Preview','rtl']].forEach(x=>{const q=el('button',x[0]);q.disabled=!previewState.available;q.title=previewState.available?'Open validated preview':'Local preview unavailable';q.onclick=()=>fetch(previewOrigin+'/mappings/'+encodeURIComponent(f.previewMappingId)+'/preview?mode='+x[1]).then(r=>r.ok?r.json():Promise.reject()).then(info=>window.open(info.url,'_blank','noopener,noreferrer')).catch(()=>previewUnavailable(box));buttons.append(q)});box.append(buttons);details.append(box);if(!previewState.available)previewUnavailable(box)}`,
|
|
130
|
+
`[['Rule',f.ruleId],['Severity',severityLabel(f.severity)+' ('+f.severity+')'],['Category',f.category],['Confidence',f.confidence],['Location',f.path+':'+f.line+':'+f.column],['Owner',f.owner],['Rationale',f.rationale],['Treatment',f.treatment],['Limitation',f.limitation]].forEach(x=>details.append(el('h3',x[0]),b(x[1])))}function select(id){const f=by.get(id);`,
|
|
131
|
+
`if(!f)return;`,
|
|
132
|
+
`s.file=f.path;`,
|
|
133
|
+
`s.finding=f;`,
|
|
134
|
+
`treeRender();`,
|
|
135
|
+
`listRender();`,
|
|
136
|
+
`source(f);writeUrl();`,
|
|
137
|
+
`detail(f)}function selectFile(path){s.file=path;`,
|
|
138
|
+
`const f=vis()[0]||null;`,
|
|
139
|
+
`s.finding=f;`,
|
|
140
|
+
`treeRender();`,
|
|
141
|
+
`listRender();`,
|
|
142
|
+
`source(f);`,
|
|
143
|
+
`detail(f)}function refresh(){const a=vis();srLive.textContent=a.length+' findings available';`,
|
|
144
|
+
`if(!a.length){s.finding=null;`,
|
|
145
|
+
`treeRender();`,
|
|
146
|
+
`listRender();`,
|
|
147
|
+
`source(null);`,
|
|
148
|
+
`detail(null);`,
|
|
149
|
+
`return}if(!s.finding||!a.some(f=>f.id===s.finding.id)){s.finding=null;select(a[0].id)}`,
|
|
150
|
+
`else{treeRender();`,
|
|
151
|
+
`listRender()}}sel.onchange=()=>{s.app=sel.value;`,
|
|
152
|
+
`writeUrl();refresh()};`,
|
|
153
|
+
`const writeUrl=()=>{const p=new URLSearchParams();if(s.q)p.set('q',s.q);if(s.app!=='all')p.set('app',s.app);if(s.severity!=='all')p.set('severity',s.severity);if(s.status!=='all')p.set('status',s.status);if(s.eligibility!=='all')p.set('eligibility',s.eligibility);if(s.category!=='all')p.set('category',s.category);if(s.sort!=='path')p.set('sort',s.sort);if(s.finding?.id)p.set('finding',s.finding.id);const next='?'+p.toString();if(location.search!==next)history.pushState(null,'',next)};`,
|
|
154
|
+
`const readUrl=()=>{const p=new URLSearchParams(location.search);s.q=p.get('q')||'';s.app=p.get('app')||'all';s.severity=p.get('severity')||'all';s.status=p.get('status')||'all';s.eligibility=p.get('eligibility')||'all';s.category=p.get('category')||'all';s.sort=p.get('sort')||'path';search.value=s.q;sel.value=s.app;severityFilter.value=s.severity;statusFilter.value=s.status;eligibilityFilter.value=s.eligibility;categoryFilter.value=s.category;sortFilter.value=s.sort;return p.get('finding')};`,
|
|
155
|
+
`search.oninput=()=>{s.q=search.value;writeUrl();refresh()};`,
|
|
156
|
+
`window.onpopstate=()=>{const id=readUrl();if(id&&by.has(id)){s.finding=by.get(id);s.file=s.finding.path}refresh()};`,
|
|
157
|
+
`const requested=readUrl();setTimeout(()=>{if(requested&&by.has(requested))select(requested);else if(d.explorer.initialFindingId)select(d.explorer.initialFindingId);else refresh()},0);`,
|
|
158
|
+
`function previewUnavailable(box){if(!box.querySelector('.preview-unavailable')){const n=el('p','Local preview unavailable. Start the optional companion to enable owning-route previews.','preview-unavailable');box.append(n)}}fetch(previewOrigin+'/health').then(r=>r.ok?r.json():Promise.reject()).then(()=>{previewState.available=true;previewState.checked=true;if(s.finding)detail(s.finding)}).catch(()=>{previewState.checked=true;if(s.finding)detail(s.finding)});`,
|
|
159
|
+
`document.addEventListener('input',event=>{const target=event.target;if(!(target instanceof HTMLTextAreaElement||target instanceof HTMLInputElement))return;const panel=target.closest('.review-workspace');if(!panel)return;const notes=panel.querySelector('textarea')?.value.trim()||'';const refs=panel.querySelector('input')?.value.split(',').map(x=>x.trim()).filter(Boolean)||[];const ready=!!notes&&refs.length>0;panel.querySelectorAll('button').forEach(button=>{if(button.textContent==='Mark Ready for Review')button.disabled=!ready;if(button.textContent==='Approve')button.disabled=!ready})});`,
|
|
160
|
+
`function lifecyclePanel(f){const box=el('section','','lifecycle-panel'),state=el('p','Loading lifecycle…','lifecycle-state'),history=el('div','','lifecycle-history');box.append(el('h3','Implementation Lifecycle'),state,history);const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};const load=()=>fetch(previewOrigin+'/review/lifecycle?'+new URLSearchParams(identity)).then(r=>r.ok?r.json():Promise.reject()).then(x=>{state.textContent='State: '+x.lifecycle;history.replaceChildren(el('p','Persisted decisions: '+(x.decision?'Yes':'No')),el('p','Manual changes: '+(x.manualChanges?.length||0)),el('p','Source hash: '+(x.sourceSha256||'Unavailable')))}).catch(()=>{state.textContent='Lifecycle unavailable; companion required'});load();return box}`,
|
|
161
|
+
`function manualPanel(f){const box=el('section','','manual-workflow'),state=el('p','No manual implementation registered','manual-state'),before=document.createElement('textarea'),after=document.createElement('textarea'),register=el('button','Register Manual Change'),history=el('div','','manual-history');before.placeholder='Before source';after.placeholder='After source';box.append(el('h3','Manual Implementation'),state,before,after,register,history);const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};const load=()=>fetch(previewOrigin+'/review/manual-changes?'+new URLSearchParams(identity)).then(r=>r.json()).then(x=>{history.replaceChildren(...(x.changes||[]).map(c=>el('pre','Before/After · '+c.timestamp+'\\n'+c.beforeText+'\\n---\\n'+c.afterText,'manual-diff')));if(x.changes?.length)state.textContent='Manual change validated and persisted'}).catch(()=>{state.textContent='Manual history unavailable'});register.onclick=()=>{register.disabled=true;fetch(previewOrigin+'/review/manual-changes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({...identity,beforeText:before.value,afterText:after.value})}).then(r=>r.ok?r.json():r.json().then(x=>Promise.reject(new Error(x.error||'MANUAL_CHANGE_FAILED')))).then(()=>{state.textContent='Manual change registered and validated';load()}).catch(e=>{state.textContent=e.message;register.disabled=false})};load();return box}`,
|
|
162
|
+
`function controlledApplyPanel(f){const box=el('section','','controlled-apply'),status=el('p','Checking server-side eligibility…','empty'),evidence=el('div','','apply-evidence'),actions=el('div','','actions'),live=el('p','','apply-live');const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};box.append(el('h3','Controlled Apply & Rollback'),el('p','Apply is a separate, explicit action. Review approval alone never modifies source.'),status,evidence,actions,live);const audit=()=>fetch(previewOrigin+'/review/audit?sourcePath='+encodeURIComponent(f.path)).then(r=>r.json()).then(x=>{box.querySelector('.audit-history')?.remove();if(!x.events?.length)return;const h=el('section','','audit-history');h.append(el('h4','Audit History'));x.events.forEach(e=>h.append(el('p',e.type+' · '+(e.resultingSha256||e.sourceSha256))));box.append(h)});const refresh=()=>fetch(previewOrigin+'/review/apply/eligibility?'+new URLSearchParams(identity)).then(r=>r.json()).then(info=>{status.textContent=info.ready?'Ready to Apply':'Blocked: '+(info.reason||'Unavailable');status.className=info.ready?'apply-ready':'apply-blocked';evidence.replaceChildren();actions.replaceChildren();if(!info.evidence||!info.ready)return;const e=info.evidence;evidence.append(el('p','Original hash: '+e.originalSourceSha256),el('p','Candidate hash: '+e.candidateSourceSha256),el('pre',e.codeDiff,'review-diff'));const apply=el('button','Apply Change');apply.onclick=()=>{if(!window.confirm('Confirm Apply'))return;fetch(previewOrigin+'/review/apply',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({identity,confirmation:'APPLY_CONFIRMED'})}).then(r=>r.json().then(x=>({ok:r.ok,x}))).then(({ok,x})=>{if(!ok)throw new Error(x.error||'APPLY_FAILED');status.textContent='Applied to Source';live.textContent='Applied successfully';const rollback=el('button','Rollback Change');rollback.onclick=()=>{if(!window.confirm('Confirm Rollback'))return;fetch(previewOrigin+'/review/rollback',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(x.receipt)}).then(r=>r.json().then(y=>({ok:r.ok,y}))).then(({ok,y})=>{if(!ok)throw new Error(y.error||'ROLLBACK_FAILED');status.textContent='Rolled Back';live.textContent='Rolled back successfully';rollback.disabled=true;audit()})};actions.append(rollback);audit()}).catch(error=>{status.textContent=error.message;live.textContent=error.message})};actions.append(apply)}).catch(()=>{status.textContent='Controlled Apply unavailable offline'});window.addEventListener('review-record-updated',refresh);refresh();audit();return box}`,
|
|
163
|
+
`const dashboardFetch=window.fetch.bind(window);window.fetch=(input,init)=>{const promise=dashboardFetch(input,init);if(String(input).includes('/review/records')&&init?.method==='POST'&&String(init.body||'').includes('"status":"Approved"'))promise.then(r=>{if(r.ok)window.dispatchEvent(new Event('review-approval-updated'))});return promise};window.addEventListener('review-approval-updated',()=>{if(s.finding)detail(s.finding)});`,
|
|
164
|
+
`const originalDetail=detail;detail=f=>{originalDetail(f);if(f){details.append(lifecyclePanel(f));if(f.eligibility!=='AUTOMATED_ELIGIBLE')details.append(manualPanel(f))}};if(s.finding){details.append(lifecyclePanel(s.finding));if(s.finding.eligibility!=='AUTOMATED_ELIGIBLE')details.append(manualPanel(s.finding))}`,
|
|
165
|
+
`const rollbackConflictFetch=window.fetch.bind(window);window.fetch=(input,init)=>{const promise=rollbackConflictFetch(input,init);if(String(input).includes('/review/rollback')&&init?.method==='POST')promise.then(async response=>{if(response.status!==409)return;const payload=await response.clone().json().catch(()=>null);if(payload?.error!=='ROLLBACK_CONFLICT')return;document.querySelectorAll('.controlled-apply').forEach(panel=>{const status=panel.querySelector('.apply-ready,.apply-blocked,.empty');const live=panel.querySelector('.apply-live');if(status)status.textContent='Recovery required';if(live)live.textContent='ROLLBACK_CONFLICT'})});return promise};`,
|
|
166
|
+
`})();`,
|
|
167
|
+
].join('');
|