rtl-analyzer 0.2.0 → 0.4.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/README.md +90 -56
- package/dist/cli.js +18 -1
- package/dist/codemod.js +50 -12
- package/dist/companion-security.js +2 -0
- package/dist/contextual-preview-bridge.js +118 -0
- package/dist/contextual-preview.js +74 -0
- package/dist/controlled-apply.js +222 -0
- package/dist/css-configured-proposal.js +98 -0
- package/dist/css-directional.js +60 -0
- package/dist/css-icons.js +51 -0
- package/dist/css-spacing.js +65 -0
- package/dist/dashboard-batch-review.js +37 -0
- package/dist/dashboard-client.js +73 -50
- package/dist/dashboard-contextual-preview.js +127 -0
- package/dist/dashboard-data.js +4 -4
- package/dist/dashboard-embedded-preview.js +202 -0
- package/dist/dashboard-html.js +13 -10
- package/dist/dashboard-operation-flow.js +47 -0
- package/dist/dashboard-review-details.js +175 -0
- package/dist/dashboard-review-navigation.js +19 -0
- package/dist/dashboard-review-workflow.js +219 -0
- package/dist/dashboard-themes.js +34 -0
- package/dist/directional-properties.js +53 -0
- package/dist/discovery.js +1 -2
- package/dist/eligibility.js +8 -8
- package/dist/evidence-store.js +110 -0
- package/dist/example-preview-mappings.js +98 -0
- package/dist/manual-change-store.js +27 -0
- package/dist/migration-lifecycle.js +19 -0
- package/dist/original-preview-runtime.js +78 -0
- package/dist/output-path.js +65 -0
- package/dist/page-navigation.js +17 -0
- package/dist/policy-validation.js +7 -4
- package/dist/preview-cli.js +22 -0
- package/dist/preview-companion.js +649 -0
- package/dist/preview-configuration.js +171 -0
- package/dist/preview-runtime.js +102 -0
- package/dist/project-configuration.js +48 -0
- package/dist/project-root.js +12 -0
- package/dist/react-inline.js +65 -0
- package/dist/report-publisher.js +4 -7
- package/dist/review-approval.js +9 -0
- package/dist/review-session.js +211 -56
- package/dist/review-store.js +175 -0
- package/dist/review-workflow.js +820 -0
- package/dist/rules.js +27 -17
- package/dist/runtime-process.js +35 -0
- package/dist/scan-history.js +35 -0
- package/dist/scan-manifest-store.js +26 -0
- package/dist/scan.js +55 -4
- package/dist/scoped-direction-evidence.js +117 -0
- package/dist/serialization.js +1 -0
- package/dist/source-context.js +93 -0
- package/dist/source-snippets.js +3 -3
- package/dist/standalone-cli.js +14 -1
- package/dist/tailwind.js +3 -1
- package/dist/transformations.js +34 -0
- package/dist/validation.js +75 -0
- package/dist/workflow-validation.js +46 -0
- package/package.json +17 -8
package/README.md
CHANGED
|
@@ -1,83 +1,117 @@
|
|
|
1
|
-
# RTL Analyzer
|
|
1
|
+
# RTL Analyzer
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Find direction-dependent styles, inspect suggested fixes, and review changes for RTL and LTR interfaces.
|
|
4
|
+
|
|
5
|
+
[Quick start](#quick-start) · [Workflow](#how-a-review-works) · [Example projects](#example-projects) · [Limits](#what-is-and-is-not-covered) · [Advanced setup guide](https://github.com/FoushWare/rtl-analyzer/blob/v0.4.0/docs/guides/developer-testing.md)
|
|
4
6
|
|
|
5
7
|
## Quick start
|
|
6
8
|
|
|
7
|
-
|
|
9
|
+
Requires **Node.js 22.12 or later**. Run from your frontend project's root:
|
|
8
10
|
|
|
9
|
-
```
|
|
10
|
-
npx rtl-analyzer
|
|
11
|
+
```sh
|
|
12
|
+
npx rtl-analyzer@0.4.0
|
|
11
13
|
```
|
|
12
14
|
|
|
13
|
-
|
|
15
|
+
The command scans the current directory, writes reports to an external temporary directory and opens the report in your default browser. It does not start the live review services. For a scan of one directory, or command help:
|
|
14
16
|
|
|
15
|
-
|
|
17
|
+
```sh
|
|
18
|
+
npx rtl-analyzer@0.4.0 scan ./src --format json
|
|
19
|
+
npx rtl-analyzer@0.4.0 --help
|
|
20
|
+
```
|
|
16
21
|
|
|
17
|
-
|
|
22
|
+
A read-only scan needs no configuration. **Live Fix Studio review does need configuration**: explicit scan and copy scope, validation scripts, source-to-page bindings, your project's installed dependencies and Chromium. The [advanced setup guide](https://github.com/FoushWare/rtl-analyzer/blob/v0.4.0/docs/guides/developer-testing.md) covers it. To try the whole flow first, use one of the [example projects](#example-projects).
|
|
18
23
|
|
|
19
|
-
|
|
20
|
-
npx rtl-analyzer --help
|
|
21
|
-
npx rtl-analyzer --version
|
|
22
|
-
```
|
|
24
|
+
## How a review works
|
|
23
25
|
|
|
24
|
-
|
|
26
|
+
The screenshots below come from the released package running on the Workspace Integration example: a shared badge whose `margin-left: 8px` should follow the text direction.
|
|
25
27
|
|
|
26
|
-
|
|
27
|
-
npx rtl-analyzer scan . --format json
|
|
28
|
-
npx rtl-analyzer scan ./src --format markdown --output-dir ./rtl-report
|
|
29
|
-
npx rtl-analyzer scan . --format dashboard --output-dir ./rtl-report
|
|
30
|
-
```
|
|
28
|
+
### 1. Run the scan and open Fix Studio
|
|
31
29
|
|
|
32
|
-
|
|
30
|
+
Scan with a dashboard report and embedded source snippets, serve the report, and start the review companion. The dashboard reports the scan result and the number of findings.
|
|
33
31
|
|
|
34
|
-
|
|
32
|
+

|
|
35
33
|
|
|
36
|
-
|
|
34
|
+
### 2. Choose a review mode
|
|
37
35
|
|
|
38
|
-
|
|
39
|
-
npm ci
|
|
40
|
-
npm run build --prefix packages/rtl-analyzer
|
|
41
|
-
cd packages/rtl-analyzer
|
|
42
|
-
npm pack --dry-run
|
|
43
|
-
npm pack
|
|
44
|
-
```
|
|
36
|
+
**Prepare all, then review** prepares every eligible change in one isolated candidate so you can review them together. **Review one by one** prepares only the finding you are looking at. Both modes start with every decision **Pending**, and neither changes your source.
|
|
45
37
|
|
|
46
|
-
|
|
38
|
+

|
|
47
39
|
|
|
48
|
-
|
|
40
|
+
### 3. Find the finding in your code and on the page
|
|
49
41
|
|
|
50
|
-
|
|
42
|
+
Each finding shows its highlighted source line and why it was flagged. For findings with a configured page binding, **Highlight targets** outlines the affected element in the running page.
|
|
51
43
|
|
|
52
|
-
|
|
53
|
-
| --- | --- | --- |
|
|
54
|
-
| React inline JSX/TSX styles | Verified | Static object properties including physical margins, padding, and text alignment. |
|
|
55
|
-
| Emotion `styled` templates | Verified | Static tagged templates imported from `@emotion/styled`. |
|
|
56
|
-
| Emotion `css` prop | Verified | `@emotion/react` tagged templates and static object expressions. |
|
|
57
|
-
| MUI `sx` | Partial | Supported MUI imports and aliases such as `ml` and `pr`; wrapper semantics remain conservative. |
|
|
58
|
-
| MUI `styled` templates | Verified | Static tagged templates imported from `@mui/material/styles`. |
|
|
59
|
-
| Vanilla CSS/HTML | Verified | Tested physical declarations and HTML direction attributes. |
|
|
60
|
-
| CSS Modules | Verified | Physical declarations in discovered `.module.css` files. |
|
|
61
|
-
| 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. |
|
|
62
|
-
| 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. |
|
|
63
|
-
| SCSS/Sass | Unsupported with diagnostic | Files are skipped and reported through `SOURCE_COVERAGE`. |
|
|
44
|
+

|
|
64
45
|
|
|
65
|
-
|
|
46
|
+
### 4. Compare Before and After
|
|
66
47
|
|
|
67
|
-
|
|
48
|
+
The code card shows the original declaration next to the suggested one. The live panes render the original application (Before) and an isolated copy with the change (After). Switch between **LTR** and **RTL**, and between apps when a finding is bound to more than one. In one-by-one mode, After shows only the finding you selected.
|
|
68
49
|
|
|
69
|
-
|
|
50
|
+

|
|
70
51
|
|
|
71
|
-
|
|
72
|
-
npm run rtl:cli:package:smoke
|
|
73
|
-
```
|
|
52
|
+
### 5. Make a decision
|
|
74
53
|
|
|
75
|
-
|
|
54
|
+
Choose **Approve proposed change**, **Reject fix**, **Defer** or **Needs review**. Approving adds the change to your accepted set. Your project files still have not changed.
|
|
76
55
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
56
|
+

|
|
57
|
+
|
|
58
|
+
### 6. Validate the accepted changes
|
|
59
|
+
|
|
60
|
+
**Validate changes** runs your configured checks, and a scoped LTR/RTL runtime check, against a candidate that contains only the accepted changes.
|
|
61
|
+
|
|
62
|
+

|
|
63
|
+
|
|
64
|
+
### 7. Apply to source, explicitly
|
|
65
|
+
|
|
66
|
+
Applying is a separate step. The confirmation names the destination project and every file that will be written. Rejected, deferred and unaccepted findings are excluded, and Apply creates receipt-backed backups.
|
|
67
|
+
|
|
68
|
+

|
|
69
|
+
|
|
70
|
+
Afterwards, check your diff and the interface in both directions.
|
|
71
|
+
|
|
72
|
+

|
|
73
|
+
|
|
74
|
+
### 8. Roll back if needed
|
|
75
|
+
|
|
76
|
+
**Review actions → Rollback applied changes** restores the files from the receipt. Rollback is refused if you edited the files after Apply, so it never overwrites your later work.
|
|
77
|
+
|
|
78
|
+

|
|
79
|
+
|
|
80
|
+
### Batch mode: prepare eligible changes, then approve selected ones
|
|
81
|
+
|
|
82
|
+
In **Prepare all, then review**, the batch overview lists every change that could be prepared. Nothing is approved automatically. Select the rows you want, **Approve selected**, then **Validate** and apply as above. Preparing a batch never writes to your source; applying it requires the same explicit confirmation. Use **View diff** to inspect any row.
|
|
83
|
+
|
|
84
|
+

|
|
85
|
+
|
|
86
|
+
If your source or your decisions change during a review, freshness checks can invalidate a suggestion or a validation. Failed or unavailable required evidence blocks Apply.
|
|
87
|
+
|
|
88
|
+
## What is and is not covered
|
|
89
|
+
|
|
90
|
+
Verified in this release (macOS, Chromium, desktop width):
|
|
91
|
+
|
|
92
|
+
- **Suggested fixes and live Before/After** for literal physical `margin-*`, `padding-*` and `text-align` in simple class rules of stylesheets you declare as `custom-css`, and for other declarations (borders, offsets, transforms) you declare yourself in `cssProposals` ([CSS proposal setup](https://github.com/FoushWare/rtl-analyzer/blob/v0.4.0/docs/guides/css-proposal-setup.md)).
|
|
93
|
+
- **Findings without a safe automatic fix** (for example fixed-edge positioning, ordering, transforms) are reported with an explanation and marked for manual review; you still get the Before view.
|
|
94
|
+
- **Detection only:** recognized utility classes and bounded SCSS declarations.
|
|
95
|
+
- **Live preview** supports Vite-compatible development scripts, including an Nx workspace that runs Vite. Next.js apps can be scanned statically, but live preview is not supported.
|
|
96
|
+
- **Not detected:** JavaScript key handling, focus order and other behavior that is not expressed in styles.
|
|
97
|
+
|
|
98
|
+
A scan reports potential issues; it does not prove a page renders correctly. Report publication and protected source operations use a trusted POSIX filesystem profile (macOS and Linux); Windows protected operations are unsupported. Safari, package managers other than npm and general framework compatibility are not certified. Project scripts must be trusted.
|
|
99
|
+
|
|
100
|
+
## Example projects
|
|
101
|
+
|
|
102
|
+
Six runnable projects live in the repository under [`examples/`](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples). They are not part of the npm package. Copy one to a temporary folder before you apply anything.
|
|
103
|
+
|
|
104
|
+
| Project | What it shows |
|
|
105
|
+
| --- | --- |
|
|
106
|
+
| [Foundations Lab](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples/foundations-lab) | Direction, spacing, edges, transforms in a Vite app |
|
|
107
|
+
| [Account Checkout](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples/account-checkout) | Two supported fixes, one manual-review case, clean controls |
|
|
108
|
+
| [Admin Dashboard](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples/admin-dashboard) | Tables, dialog and tabs; several manual-review findings |
|
|
109
|
+
| [Bilingual Storefront](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples/bilingual-storefront) | Next.js and Tailwind; static scan only |
|
|
110
|
+
| [Interaction Playground](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples/interaction-playground) | Drawer, rating and slider; scanner finds CSS risks, not key handling |
|
|
111
|
+
| [Workspace Integration](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples/workspace-integration) | Nx workspace, two apps and a shared library |
|
|
112
|
+
|
|
113
|
+
Each project's README has its setup instructions and expected findings. The [hands-on testing guide](https://github.com/FoushWare/rtl-analyzer/blob/v0.4.0/docs/guides/example-testing-guide.md) walks through all six.
|
|
114
|
+
|
|
115
|
+
## Development
|
|
82
116
|
|
|
83
|
-
|
|
117
|
+
The public package bundles a pinned implementation at build time. Consumers install `rtl-analyzer`; the internal `@atlas/rtl-scanner` package is private. Clone with submodules and follow the [build, pack and verification commands](https://github.com/FoushWare/rtl-analyzer/blob/v0.4.0/docs/guides/developer-testing.md#build-pack-and-verify). Licensed under [MIT](https://github.com/FoushWare/rtl-analyzer/blob/v0.4.0/packages/rtl-analyzer/LICENSE).
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
1
2
|
import { exitCode } from './coverage.js';
|
|
2
3
|
import { scan } from './scan.js';
|
|
3
4
|
import { json, markdown } from './report.js';
|
|
@@ -8,13 +9,29 @@ import { structuredMarkdown } from './structured-markdown.js';
|
|
|
8
9
|
import { dashboardHtml } from './dashboard-html.js';
|
|
9
10
|
import { extractSourceSnippets } from './source-snippets.js';
|
|
10
11
|
import { pathToFileURL } from 'node:url';
|
|
12
|
+
import { realpathSync } from 'node:fs';
|
|
11
13
|
const defaultDependencies = { scan, json, markdown, publishReports, publishArtifacts, extractSourceSnippets };
|
|
14
|
+
export const CLI_HELP = `Usage: rtl-scanner [options]
|
|
15
|
+
|
|
16
|
+
Read-only static analysis. Review and source Apply require the local rtl-preview companion.
|
|
17
|
+
|
|
18
|
+
--root <directory> Project root (default: current directory)
|
|
19
|
+
--format <format> json | markdown | markdown-structured | dashboard
|
|
20
|
+
--output-dir <directory> Existing external directory; never overwrites reports
|
|
21
|
+
--embed-source-snippets Opt-in source embedding; requires dashboard and output-dir
|
|
22
|
+
--fail-on-findings Exit 1 for actionable findings (incomplete analysis exits 2)
|
|
23
|
+
-h, --help Show this help
|
|
24
|
+
`;
|
|
12
25
|
export async function runCli(argv, io, dependencies = defaultDependencies) {
|
|
13
26
|
let root = process.cwd();
|
|
14
27
|
let format = 'json';
|
|
15
28
|
let gate = false;
|
|
16
29
|
let outputDir;
|
|
17
30
|
let embedSource = false;
|
|
31
|
+
if (argv.length === 1 && ['--help', '-h'].includes(argv[0])) {
|
|
32
|
+
io.writeStdout(CLI_HELP);
|
|
33
|
+
return 0;
|
|
34
|
+
}
|
|
18
35
|
try {
|
|
19
36
|
const args = argv.filter(a => { if (a === '--fail-on-findings') {
|
|
20
37
|
gate = true;
|
|
@@ -70,7 +87,7 @@ export async function runCli(argv, io, dependencies = defaultDependencies) {
|
|
|
70
87
|
return 2;
|
|
71
88
|
}
|
|
72
89
|
}
|
|
73
|
-
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
90
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
|
|
74
91
|
const io = { writeStdout: (s) => process.stdout.write(s), writeStderr: (s) => console.error(s) };
|
|
75
92
|
process.exitCode = await runCli(process.argv.slice(2), io);
|
|
76
93
|
}
|
package/dist/codemod.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import ts from 'typescript';
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
|
-
import { REVIEW_SOURCE } from './review-session.js';
|
|
4
3
|
import { applyReviewPatch } from './review-session.js';
|
|
5
4
|
export const BIDI_TRANSFORMATION_ID = 'bidi-isolate-auto';
|
|
6
5
|
export class TransformationRejected extends Error {
|
|
@@ -11,37 +10,76 @@ export class TransformationRejected extends Error {
|
|
|
11
10
|
}
|
|
12
11
|
}
|
|
13
12
|
const sha = (value) => createHash('sha256').update(value).digest('hex');
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
13
|
+
/** Detection keeps uncertain direction ancestors visible; proposals never overwrite them. */
|
|
14
|
+
export function hasIsolation(node, detection = false) {
|
|
15
|
+
for (let parent = node; parent; parent = parent.parent) {
|
|
16
|
+
if (!(ts.isJsxElement(parent) || ts.isJsxSelfClosingElement(parent)))
|
|
17
|
+
continue;
|
|
18
|
+
const opening = ts.isJsxElement(parent) ? parent.openingElement : parent;
|
|
19
|
+
const tag = opening.tagName.getText();
|
|
20
|
+
if (tag === 'bdi' || tag === 'bdo')
|
|
21
|
+
return true;
|
|
22
|
+
for (const p of opening.attributes.properties) {
|
|
23
|
+
if (ts.isJsxSpreadAttribute(p)) {
|
|
24
|
+
if (!detection)
|
|
25
|
+
return true;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (p.name.getText() === 'dir' && (!detection || p.initializer && ts.isStringLiteral(p.initializer) && ['ltr', 'auto'].includes(p.initializer.text)))
|
|
20
29
|
return true;
|
|
30
|
+
if (p.name.getText() !== 'style')
|
|
31
|
+
continue;
|
|
32
|
+
const expression = p.initializer && ts.isJsxExpression(p.initializer) ? p.initializer.expression : undefined;
|
|
33
|
+
if (!expression || !ts.isObjectLiteralExpression(expression)) {
|
|
34
|
+
if (!detection)
|
|
35
|
+
return true;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
for (const prop of expression.properties) {
|
|
39
|
+
if (!ts.isPropertyAssignment(prop)) {
|
|
40
|
+
if (!detection)
|
|
41
|
+
return true;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
const key = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : prop.name.getText();
|
|
45
|
+
if (!detection && ['direction', 'unicodeBidi', 'writingMode'].includes(key))
|
|
46
|
+
return true;
|
|
47
|
+
if (detection && key === 'unicodeBidi' && ts.isStringLiteral(prop.initializer) && ['isolate', 'isolate-override', 'plaintext'].includes(prop.initializer.text))
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
21
50
|
}
|
|
22
51
|
}
|
|
23
52
|
return false;
|
|
24
53
|
}
|
|
25
54
|
export function proposeBidiIsolation(finding, source) {
|
|
26
|
-
if (finding.
|
|
55
|
+
if (finding.ruleId !== 'RTL.BIDI.ISOLATION' || !/^RTL\.BIDI\.ISOLATION:[a-f0-9]{24,64}$/.test(finding.id) || !/[.][jt]sx$/.test(finding.path) || /[\\\x00-\x1f]/.test(finding.path) || finding.path.startsWith('/') || finding.path.split('/').some(p => !p || p === '.' || p === '..'))
|
|
27
56
|
throw new TransformationRejected('UNSUPPORTED_FINDING_IDENTITY');
|
|
28
|
-
|
|
57
|
+
if (finding.exceptionReason || ['INTENTIONAL_LTR', 'INFORMATIONAL'].includes(finding.category))
|
|
58
|
+
throw new TransformationRejected('INTENTIONAL_CONTENT_REQUIRES_REVIEW');
|
|
59
|
+
const file = ts.createSourceFile(finding.path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
29
60
|
let target;
|
|
30
61
|
function visit(node) { if (ts.isJsxExpression(node) && node.getStart(file) === finding.range.start.offset && node.end === finding.range.end.offset)
|
|
31
62
|
target = node; ts.forEachChild(node, visit); }
|
|
32
63
|
visit(file);
|
|
33
64
|
if (!target)
|
|
34
65
|
throw new TransformationRejected('UNSUPPORTED_AST_RANGE');
|
|
35
|
-
if (!target.expression || !ts.isPropertyAccessExpression(target.expression) || target.expression.
|
|
66
|
+
if (!target.expression || !ts.isPropertyAccessExpression(target.expression) || !ts.isIdentifier(target.expression.expression) || !['id', 'name', 'email', 'address'].includes(target.expression.name.text))
|
|
36
67
|
throw new TransformationRejected('AMBIGUOUS_TOKEN_EXPRESSION');
|
|
37
68
|
if (hasIsolation(target))
|
|
38
69
|
throw new TransformationRejected('ALREADY_ISOLATED');
|
|
39
70
|
if (!target.parent || !(ts.isJsxElement(target.parent) || ts.isJsxFragment(target.parent)))
|
|
40
71
|
throw new TransformationRejected('UNSUPPORTED_WRAPPER');
|
|
72
|
+
const textContainers = new Set(['Link', 'a', 'span', 'div', 'p', 'strong', 'small', 'label', 'li', 'td', 'th', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
|
|
73
|
+
if (ts.isJsxElement(target.parent) && !textContainers.has(target.parent.openingElement.tagName.getText(file)))
|
|
74
|
+
throw new TransformationRejected('UNSUPPORTED_TEXT_CONTAINER');
|
|
75
|
+
for (let ancestor = target.parent; ancestor; ancestor = ancestor.parent) {
|
|
76
|
+
if (ts.isJsxElement(ancestor) && ['svg', 'math', 'script', 'style', 'textarea', 'title', 'option', 'select'].includes(ancestor.openingElement.tagName.getText(file)))
|
|
77
|
+
throw new TransformationRejected('UNSAFE_HTML_CONTEXT');
|
|
78
|
+
}
|
|
41
79
|
const original = source.slice(finding.range.start.offset, finding.range.end.offset);
|
|
42
|
-
if (original !==
|
|
80
|
+
if (original !== finding.original)
|
|
43
81
|
throw new TransformationRejected('SOURCE_RANGE_MISMATCH');
|
|
44
|
-
return { transformationId: BIDI_TRANSFORMATION_ID, reason: '
|
|
82
|
+
return { transformationId: BIDI_TRANSFORMATION_ID, reason: 'Requires semantic review: direct identifier.id/name/email/address text child in JSX; wrap only the verified expression in auto-direction bidi isolation. Preserve canonical text and copying; inspect punctuation in both directions.', patch: { findingId: finding.id, path: finding.path, startOffset: finding.range.start.offset, endOffset: finding.range.end.offset, expectedSha256: sha(original), replacement: '<bdi dir="auto">' + original + '</bdi>' } };
|
|
45
83
|
}
|
|
46
84
|
export async function dryRunBidiIsolation(session, finding, source) {
|
|
47
85
|
const proposal = proposeBidiIsolation(finding, source);
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/** Installed only by the generated local Vite preview config, before the real app entry. */
|
|
2
|
+
export const contextualBridgeSource = String.raw `
|
|
3
|
+
function installContextPreview(config){
|
|
4
|
+
if(!config.bindings.length)return;
|
|
5
|
+
const parent=window.parent,identity=config.identity,dashboardOrigin=config.dashboardOrigin;
|
|
6
|
+
const dataId=parent!==window&&/^rtl-preview:[a-f0-9-]{36}$/.test(window.name)?window.name.slice(12):null;
|
|
7
|
+
const storageKey=config.dataAdapter!=='none'&&dataId?'rtl-analyzer-preview:atlas-seed-v1:'+dataId:null;
|
|
8
|
+
window.__rtlPreviewStorageKey=storageKey;
|
|
9
|
+
let releaseData;window.__rtlPreviewDataReady=storageKey?new Promise(resolve=>releaseData=resolve):Promise.resolve();
|
|
10
|
+
let initialized=!storageKey,active=null,preparing=false,lastScroll='',layer=null,lastFingerprint='',lastBoxes='';
|
|
11
|
+
const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
|
|
12
|
+
const visible=node=>{const r=node.getBoundingClientRect(),s=getComputedStyle(node);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'};
|
|
13
|
+
const select=(selector)=>{try{return [...document.querySelectorAll(selector)].filter(n=>!n.closest('[data-rtl-context-overlay]')).slice(0,500)}catch{return []}};
|
|
14
|
+
function validSeed(text){try{const rows=JSON.parse(text);return text.length<100000&&Array.isArray(rows)&&rows.length<=200&&rows.every(row=>row&&typeof row.id==='string'&&row.id.length<100&&typeof row.customerId==='string'&&Array.isArray(row.items)&&row.items.length<100)}catch{return false}}
|
|
15
|
+
async function fingerprint(text){const bytes=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(text));return [...new Uint8Array(bytes)].map(n=>n.toString(16).padStart(2,'0')).join('')}
|
|
16
|
+
function resolveData(request){
|
|
17
|
+
if(initialized)return true;if(!Array.isArray(window.__rtlPreviewSeedInvoices))return false;
|
|
18
|
+
const existing=localStorage.getItem(storageKey),seed=request.seedData||JSON.stringify(window.__rtlPreviewSeedInvoices);
|
|
19
|
+
if(!validSeed(seed)||existing&&!validSeed(existing))return false;
|
|
20
|
+
if(identity.role==='candidate'&&!request.seedData)return false;
|
|
21
|
+
if(!existing)localStorage.setItem(storageKey,seed);
|
|
22
|
+
initialized=true;releaseData();return true;
|
|
23
|
+
}
|
|
24
|
+
function routeMatches(route,request){if(location.pathname!==route.path)return false;if(!route.urls)return true;if(!['ltr','rtl'].includes(request.mode))return false;const expected=new URL(route.urls[request.mode],location.origin),actual=new URL(location.href);return [...expected.searchParams].every(([key,value])=>actual.searchParams.get(key)===value);}
|
|
25
|
+
function inputValue(input,value){const setter=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set;setter.call(input,value);input.dispatchEvent(new Event('input',{bubbles:true}));input.dispatchEvent(new Event('change',{bubbles:true}))}
|
|
26
|
+
async function until(fn){for(let i=0;i<70;i++){const result=fn();if(result)return result;await wait(40)}return null}
|
|
27
|
+
async function openCustomerMenu(){const combo=document.querySelector('.form-grid [role="combobox"]');if(!combo)return;combo.dispatchEvent(new MouseEvent('mousedown',{bubbles:true,button:0}));await until(()=>document.querySelector('[role="listbox"]'))}
|
|
28
|
+
async function prepare(route,mapping){
|
|
29
|
+
if(['customer-menu','invoice-confirm'].includes(route.prepare))await until(()=>document.querySelector('.form-grid [role="combobox"]'));
|
|
30
|
+
if(route.prepare==='customer-dialog')await until(()=>document.querySelector('.customer-card button'));
|
|
31
|
+
if(route.prepare==='sidebar')await until(()=>document.querySelector('aside'));
|
|
32
|
+
if(route.prepare==='sidebar'){
|
|
33
|
+
const aside=document.querySelector('aside');if(aside&&aside.getBoundingClientRect().right<=1||aside&&aside.getBoundingClientRect().left>=innerWidth){document.querySelector('.mobile-menu')?.click();await wait(100)}
|
|
34
|
+
}
|
|
35
|
+
if(route.prepare==='customer-dialog'&&!document.querySelector('.MuiDialogContent-root')){document.querySelector('.customer-card button')?.click();await until(()=>document.querySelector('.MuiDialogContent-root'))}
|
|
36
|
+
if(route.prepare==='customer-menu'&&!document.querySelector('[role="listbox"]'))await openCustomerMenu();
|
|
37
|
+
if(route.prepare==='invoice-confirm'&&!document.querySelector('.MuiDialogContent-root')){
|
|
38
|
+
const combo=document.querySelector('.form-grid [role="combobox"]');
|
|
39
|
+
if(combo&&!combo.textContent.trim().replace(/\u200b/g,'')){await openCustomerMenu();document.querySelector('[role="option"]')?.click();await wait(60)}
|
|
40
|
+
const inputs=[...document.querySelectorAll('.line-item input')];if(inputs[0]&&!inputs[0].value){inputValue(inputs[0],'RTL preview scenario');await wait(80)}if(inputs[2]&&!(Number(inputs[2].value)>0))inputValue(inputs[2],'125');
|
|
41
|
+
await wait(60);document.querySelector('form button[type="submit"]')?.click();await until(()=>document.querySelector('.MuiDialogContent-root'));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
let cssEpoch=0,cssSignature='',cssCache=new WeakMap(),lastDirectionSignature='',directionRevision=0;
|
|
45
|
+
const invalidateCss=()=>cssEpoch++;
|
|
46
|
+
const directionSnapshot=()=>{if(!active)return '';const nodes=select(active.mapping.selector);return JSON.stringify({root:getComputedStyle(document.documentElement).direction,targets:nodes.map(node=>getComputedStyle(node).direction),href:location.href});};
|
|
47
|
+
const notifyDirectionChange=()=>{if(!active)return;const signature=directionSnapshot();if(!signature||signature===lastDirectionSignature)return;lastDirectionSignature=signature;directionRevision++;parent.postMessage({type:'rtl-context-direction-changed',version:2,nonce:active.request.nonce,role:identity.role,application:identity.application,projectRoot:identity.projectRoot,sessionId:active.request.sessionId,runtimeSessionId:identity.sessionId,findingId:active.request.findingId,sourcePath:active.request.sourcePath,sourceSha256:config.sourceHashes[active.request.sourcePath],routeId:active.request.routeId,directionRevision,href:location.href,directions:JSON.parse(signature)},dashboardOrigin)};
|
|
48
|
+
new MutationObserver(records=>{if(records.some(record=>{const node=record.target.nodeType===1?record.target:record.target.parentElement;return !node?.closest('[data-rtl-context-overlay]')})){invalidateCss();notifyDirectionChange()}}).observe(document.documentElement,{subtree:true,childList:true,attributes:true,characterData:true});
|
|
49
|
+
for(const type of ['pointerover','pointerout','focusin','focusout','input','change','click'])document.addEventListener(type,invalidateCss,true);
|
|
50
|
+
window.addEventListener('hashchange',()=>{invalidateCss();notifyDirectionChange()});window.addEventListener('resize',()=>{invalidateCss();notifyDirectionChange()});setInterval(notifyDirectionChange,250);
|
|
51
|
+
function specificity(selector){const clean=selector.replace(/:where\([^)]*\)/g,'').replace(/::[\w-]+/g,'').replace(/:(is|not|has)\(/g,'(');return [(clean.match(/#[\w-]+/g)||[]).length,(clean.match(/\.[\w-]+|\[[^\]]+\]|:[\w-]+/g)||[]).length,(clean.replace(/#[\w-]+|\.[\w-]+|\[[^\]]+\]|:[\w-]+/g,'').match(/(?:^|[\s>+~(])([a-z][\w-]*)/gi)||[]).length]}
|
|
52
|
+
function styleRules(){const out=[];let order=0;function walk(rules,owner,conditions,enabled){for(const rule of rules){if(rule.selectorText&&rule.style)out.push({rule,owner,conditions,enabled,order:order++});else if(rule.cssRules){let active=enabled;const condition=rule.conditionText||'';if(rule.constructor.name==='CSSMediaRule')active=active&&matchMedia(condition).matches;else if(rule.constructor.name==='CSSSupportsRule')active=active&&CSS.supports(condition);walk(rule.cssRules,owner,condition?[...conditions,condition]:conditions,active)}}}for(const sheet of document.styleSheets){try{walk(sheet.cssRules,sheet.ownerNode,[],!sheet.disabled&&(!sheet.media?.mediaText||matchMedia(sheet.media.mediaText).matches))}catch{}}return out}
|
|
53
|
+
function ownerMatches(owner,path){const vite=owner?.getAttribute('data-vite-dev-id')?.replaceAll('\\','/');if(vite?.endsWith('/'+path))return true;try{if(owner?.tagName!=='LINK')return false;const url=new URL(owner.href,location.href);return url.origin===location.origin&&decodeURIComponent(url.pathname)==='/'+path}catch{return false}}
|
|
54
|
+
function cssResult(node,css,finding,rules){
|
|
55
|
+
const key=[cssEpoch,finding.id,css.property,getComputedStyle(node).direction,innerWidth,innerHeight].join('|'),cached=cssCache.get(node);
|
|
56
|
+
if(cached?.key===key&&getComputedStyle(node).getPropertyValue(cached.result.resolvedProperty)===cached.result.computedValue)return cached.result;
|
|
57
|
+
let property=css.property;const opposite={'margin-left':'margin-right','margin-right':'margin-left','right':'left','left':'right'};
|
|
58
|
+
if(css.inline&&!node.style.getPropertyValue(property)&&getComputedStyle(node).direction==='rtl'&&opposite[property]&&rules.some(r=>r.enabled&&r.rule.style.getPropertyValue(opposite[property])===css.value&&safeMatches(node,r.rule.selectorText)))property=opposite[property];
|
|
59
|
+
const applicable=[],sources=[];
|
|
60
|
+
for(const entry of rules){const {rule}=entry;if(!safeMatches(node,rule.selectorText))continue;const value=rule.style.getPropertyValue(property);if(!value)continue;const spec=rule.selectorText.split(',').filter(s=>safeMatches(node,s)).map(specificity).sort(compare).at(-1)||[0,0,0];const source=css.selector?ownerMatches(entry.owner,finding.path)&&rule.selectorText.split(',').map(s=>s.trim()).includes(css.selector):value.replace(/\s/g,'')===css.value.replace(/\s/g,'');
|
|
61
|
+
const candidate={...entry,value,source,rank:[rule.style.getPropertyPriority(property)==='important'?1:0,0,...spec,entry.order]};if(source)sources.push(candidate);if(entry.enabled)applicable.push(candidate);
|
|
62
|
+
}
|
|
63
|
+
if(node.style.getPropertyValue(property)){const candidate={value:node.style.getPropertyValue(property),source:!!css.inline,conditions:[],enabled:true,rank:[node.style.getPropertyPriority(property)==='important'?1:0,1,0,0,0,1e9]};applicable.push(candidate);if(candidate.source)sources.push(candidate)}
|
|
64
|
+
const winner=applicable.sort((a,b)=>compare(a.rank,b.rank)).at(-1),conditionActive=(!css.media||matchMedia(css.media).matches)&&(!css.rtlOnly||getComputedStyle(node).direction==='rtl'&&!node.classList.contains('is-open'));
|
|
65
|
+
const result={sourceProperty:css.property,resolvedProperty:property,declaredValue:css.value,computedValue:getComputedStyle(node).getPropertyValue(property),selectorMatched:true,conditionActive,contribution:!conditionActive?'inactive':winner?.source?'contributing':sources.some(s=>s.enabled)?'overridden':'unresolved-cascade',winner:winner?{value:winner.value,selector:winner.rule?.selectorText||'style attribute',conditions:winner.conditions}:null,limitation:'CSSOM cascade attribution for these example rules (normal/important, specificity, order, media/supports, inline and generated sx); no universal layered/shadow stylesheet analysis. A contribution is not an RTL-defect verdict.'};cssCache.set(node,{key,result});return result;
|
|
66
|
+
}
|
|
67
|
+
function compare(a,b){for(let i=0;i<Math.max(a.length,b.length);i++){const delta=(a[i]||0)-(b[i]||0);if(delta)return delta}return 0}
|
|
68
|
+
function safeMatches(node,selector){try{return node.matches(selector)}catch{return false}}
|
|
69
|
+
function boxes(nodes,instance){const chosen=instance===-2?[]:instance<0?nodes:nodes.slice(instance,instance+1),signature=JSON.stringify([innerWidth,innerHeight,chosen.map(node=>{const r=node.getBoundingClientRect();return [nodes.indexOf(node),visible(node),r.x,r.y,r.width,r.height]})]);if(layer&&signature===lastBoxes)return;lastBoxes=signature;if(!layer){layer=document.createElement('div');layer.dataset.rtlContextOverlay='true';Object.assign(layer.style,{position:'fixed',inset:'0',pointerEvents:'none',zIndex:'2147483647',overflow:'hidden'});document.body.append(layer)}const selected=instance===-2?[]:instance<0?nodes:nodes.slice(instance,instance+1);layer.replaceChildren();for(const node of selected){if(!visible(node))continue;const r=node.getBoundingClientRect(),index=nodes.indexOf(node),box=document.createElement('div');box.className='rtl-context-highlight';box.dataset.targetIndex=String(index);const outside=r.right<=0||r.bottom<=0||r.left>=innerWidth||r.top>=innerHeight;Object.assign(box.style,{position:'absolute',left:Math.max(1,r.left)+'px',top:Math.max(1,r.top)+'px',width:Math.max(2,Math.min(r.width,innerWidth-Math.max(1,r.left)-2))+'px',height:Math.max(2,Math.min(r.height,innerHeight-Math.max(1,r.top)-2))+'px',outline:'3px solid #e26b00',outlineOffset:'-2px',background:'rgba(255,163,40,.07)',boxSizing:'border-box'});if(outside){box.style.left='4px';box.style.top='4px';box.style.width='230px';box.style.height='30px';box.textContent='Target '+(index+1)+' is outside the viewport';box.style.background='#fff4db';box.style.color='#6e3500'}layer.append(box)}}
|
|
70
|
+
document.addEventListener('click',event=>{const anchor=event.target.closest?.('a[href]');if(!anchor||!active)return;const url=new URL(anchor.href,location.href);if(['localhost','127.0.0.1'].includes(url.hostname)&&['4200','4201'].includes(url.port)&&url.origin!==location.origin){event.preventDefault();event.stopPropagation();parent.postMessage({type:'rtl-context-navigation',version:2,nonce:active.request.nonce,role:identity.role,application:identity.application,projectRoot:identity.projectRoot,sessionId:active.request.sessionId,runtimeSessionId:identity.sessionId,findingId:active.request.findingId,sourcePath:active.request.sourcePath,sourceSha256:config.sourceHashes[active.request.sourcePath],routeId:active.request.routeId,nextApplication:url.port==='4201'?'procurement':'invoicing'},dashboardOrigin)}},true);
|
|
71
|
+
let paintPending=false;const repaint=()=>{if(paintPending||!active)return;paintPending=true;requestAnimationFrame(()=>{paintPending=false;if(active)boxes(select(active.mapping.selector),active.instance)})};
|
|
72
|
+
window.addEventListener('scroll',repaint,true);window.addEventListener('resize',repaint);
|
|
73
|
+
window.addEventListener('message',async event=>{
|
|
74
|
+
const request=event.data;
|
|
75
|
+
if(event.origin!==dashboardOrigin||event.source!==parent||!request||request.type!=='rtl-context-probe'||request.version!==2||typeof request.nonce!=='string'||request.nonce.length>100||request.role!==identity.role||request.application!==identity.application||request.runtimeSessionId!==identity.sessionId||request.projectRoot!==identity.projectRoot||typeof request.sessionId!=='string'||request.sessionId.length>100||typeof request.sourceSha256!=='string'||request.sourceSha256!==config.sourceHashes[request.sourcePath]||!Number.isInteger(request.instance)||request.instance< -2||request.instance>500)return;
|
|
76
|
+
const binding=config.bindings.find(b=>b.finding.id===request.findingId&&b.finding.path===request.sourcePath);if(!binding)return;
|
|
77
|
+
const route=binding.mapping.routes.find(r=>r.id===request.routeId&&r.application===identity.application);if(!route)return;
|
|
78
|
+
if(!resolveData(request))return;
|
|
79
|
+
const key=[request.nonce,request.findingId,request.routeId].join('|');
|
|
80
|
+
if(!active||active.key!==key){active={key,mapping:binding.mapping,instance:request.instance,request};lastScroll='';preparing=true;try{await until(()=>document.querySelector(config.readySelector||'#root > *'));if(routeMatches(route,request))await prepare(route,binding.mapping)}finally{if(active?.key===key)preparing=false}}
|
|
81
|
+
else if(preparing)return;
|
|
82
|
+
if(active?.key!==key)return;active.instance=request.instance;active.request=request;
|
|
83
|
+
if(request.command==='reveal-navigation'){document.querySelector('.mobile-menu')?.click();await wait(80)}
|
|
84
|
+
if(request.command==='reset-data'&&storageKey&&validSeed(request.seedData)){localStorage.setItem(storageKey,request.seedData);const next=new URL(route.path,location.origin);for(const key of ['demo','lang']){const value=new URLSearchParams(location.search).get(key);if(value)next.searchParams.set(key,value)}location.replace(next.href);return}
|
|
85
|
+
const probeRevision=directionRevision;
|
|
86
|
+
const nodes=routeMatches(route,request)?select(binding.mapping.selector):[];
|
|
87
|
+
if(request.command==='highlight')lastScroll='';
|
|
88
|
+
const scrollKey=key+':'+request.instance+':'+nodes.length;if(request.instance!==-2&&nodes.length&&lastScroll!==scrollKey){const node=nodes[Math.max(0,request.instance)]||nodes[0];if(visible(node))node.scrollIntoView({block:'center',inline:'nearest',behavior:'instant'});lastScroll=scrollKey}
|
|
89
|
+
boxes(nodes,request.instance);
|
|
90
|
+
const rules=binding.mapping.css?styleRules():[];
|
|
91
|
+
if(binding.mapping.css){const signature=rules.map(entry=>[entry.enabled,entry.conditions.join(' '),entry.rule.cssText].join('|')).join('\n');if(signature!==cssSignature){cssSignature=signature;cssEpoch++;cssCache=new WeakMap()}}
|
|
92
|
+
const sourceRules=binding.mapping.configured&&binding.mapping.sourceSelector?styleRules().filter(entry=>ownerMatches(entry.owner,binding.finding.path)&&entry.rule.selectorText.split(',').map(s=>s.trim()).includes(binding.mapping.sourceSelector)):[];
|
|
93
|
+
const sourceStatus=!binding.mapping.configured||!binding.mapping.sourceSelector?'not-required':!sourceRules.length?'source-not-observed':!nodes.length?'target-not-found':nodes.some(node=>sourceRules.some(entry=>safeMatches(node,entry.rule.selectorText)))?'source-rule-matched':'target-source-mismatch';
|
|
94
|
+
const targets=nodes.map((node,index)=>{const r=node.getBoundingClientRect();const explicitKey=node.getAttribute('id')||node.getAttribute('data-id')||node.getAttribute('data-key')||node.getAttribute('data-testid')||node.getAttribute('data-target-id');const nameSelector='h1,h2,h3,h4,h5,h6,strong,[data-name],.name,.contact-name';const h=(node.matches?.(nameSelector)?node:null)||node.querySelector?.(nameSelector);const nameText=(h?.textContent||node.getAttribute('aria-label')||node.getAttribute('title')||'').trim().replace(/\s+/g,' ');const emailSelector='.email,.contact-email,a[href^="mailto:"]';const emailEl=(node.matches?.(emailSelector)?node:null)||node.querySelector?.(emailSelector);const emailText=(emailEl?.textContent||emailEl?.getAttribute('href')?.replace(/^mailto:/,'')||'').trim();const cleanLabel=(binding.mapping.kind==='document'?'Whole document · '+document.title:(nameText||(emailText?emailText.split('@')[0]:'Target '+(index+1)))).slice(0,100);const rawCandidateKey=explicitKey||(nameText&&emailText?nameText+' · '+emailText:nameText||emailText||null);return {index,effectiveDirection:getComputedStyle(node).direction,pageDirection:getComputedStyle(document.documentElement).direction,rawKey:rawCandidateKey,hasExplicitKey:!!explicitKey,label:cleanLabel,name:nameText||null,rendered:visible(node),inViewport:r.right>0&&r.bottom>0&&r.left<innerWidth&&r.top<innerHeight,rect:{x:r.x,y:r.y,width:r.width,height:r.height},...(binding.mapping.css?{css:cssResult(node,binding.mapping.css,binding.finding,rules)}:{})}});
|
|
95
|
+
const keyCounts={};targets.forEach(t=>{if(t.rawKey)keyCounts[t.rawKey]=(keyCounts[t.rawKey]||0)+1});
|
|
96
|
+
targets.forEach(t=>{
|
|
97
|
+
if(t.rawKey&&keyCounts[t.rawKey]===1){t.key=t.rawKey;t.keyGuaranteed=true;t.ambiguous=false}
|
|
98
|
+
else if(t.rawKey&&keyCounts[t.rawKey]>1){t.key=t.rawKey;t.keyGuaranteed=false;t.ambiguous=true}
|
|
99
|
+
else{t.key=null;t.keyGuaranteed=false;t.ambiguous=false}
|
|
100
|
+
});
|
|
101
|
+
const labelCounts={};targets.forEach(t=>{labelCounts[t.label]=(labelCounts[t.label]||0)+1});
|
|
102
|
+
targets.forEach(t=>{
|
|
103
|
+
if(labelCounts[t.label]>1){
|
|
104
|
+
if(t.key&&!t.ambiguous){
|
|
105
|
+
const disambig=t.key.includes(' · ')?t.key.split(' · ')[1]:t.key;
|
|
106
|
+
t.label+=' ('+disambig+')';
|
|
107
|
+
}else{
|
|
108
|
+
t.label+=' (#'+(t.index+1)+')';
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
const seedData=storageKey?localStorage.getItem(storageKey):null,defaultSeedData=JSON.stringify(window.__rtlPreviewSeedInvoices||[]);
|
|
113
|
+
const dataFingerprint=seedData?await fingerprint(seedData):null;if(active?.key!==key||probeRevision!==directionRevision)return;lastFingerprint=dataFingerprint;
|
|
114
|
+
const routeReady=!!document.querySelector(config.readySelector||'#root > *');
|
|
115
|
+
parent.postMessage({type:'rtl-context-status',version:2,nonce:request.nonce,role:identity.role,application:identity.application,projectRoot:identity.projectRoot,sessionId:request.sessionId,runtimeSessionId:identity.sessionId,findingId:request.findingId,sourcePath:request.sourcePath,sourceSha256:config.sourceHashes[request.sourcePath],routeId:request.routeId,directionRevision:probeRevision,route:location.pathname,dir:getComputedStyle(document.documentElement).direction,routeReady,sourceStatus,targetStatus:preparing?'preparing':!routeReady?'route-not-ready':!routeMatches(route,request)?'navigated':sourceStatus==='source-not-observed'?'source-not-loaded':sourceStatus==='target-source-mismatch'?'target-mismatch':targets.some(t=>t.rendered)?binding.mapping.kind==='document'?'document':'verified':targets.length?'hidden':binding.mapping.configured?'missing-target':'unresolved',targets,dataFingerprint,seedData,defaultSeedData,dataScope:storageKey,fixtureData:config.dataAdapter==='none'?'application-data':'atlas-seed-v1'},dashboardOrigin);
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
`;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { loadPreviewConfiguration, configuredMapping, routeUrl } from './preview-configuration.js';
|
|
4
|
+
import { scan } from './scan.js';
|
|
5
|
+
import { validateProjectSourcePath, candidateApplicationRuntime } from './review-session.js';
|
|
6
|
+
import { candidateEntries, composeWorkflowFile } from './review-workflow.js';
|
|
7
|
+
import { verifiedSourceTransition } from './source-context.js';
|
|
8
|
+
import { classifyEligibility } from './eligibility.js';
|
|
9
|
+
export const ORIGINAL_PREVIEW_ORIGINS = { invoicing: 'http://127.0.0.1:4200', procurement: 'http://127.0.0.1:4201' };
|
|
10
|
+
const sha = (value) => createHash('sha256').update(value).digest('hex');
|
|
11
|
+
export async function contextualPreview(root, query, workflow) {
|
|
12
|
+
const report = await scan(root);
|
|
13
|
+
if (report.inputDigest !== query.get('inputDigest') || report.policyDigest !== query.get('policyDigest'))
|
|
14
|
+
throw Error('DASHBOARD_SOURCE_IDENTITY_MISMATCH');
|
|
15
|
+
const finding = report.findings.find(f => f.id === query.get('findingId'));
|
|
16
|
+
if (!finding)
|
|
17
|
+
throw Error('FINDING_NOT_IN_CURRENT_REPORT');
|
|
18
|
+
const historical = !!workflow && workflow.state !== 'Reviewing';
|
|
19
|
+
if (historical)
|
|
20
|
+
await verifiedSourceTransition(root, workflow);
|
|
21
|
+
else if (workflow && (workflow.root !== root || workflow.inputDigest !== report.inputDigest || workflow.policyDigest !== report.policyDigest))
|
|
22
|
+
throw Error('PREVIEW_SESSION_IDENTITY_MISMATCH');
|
|
23
|
+
const configuration = await loadPreviewConfiguration(root);
|
|
24
|
+
if (workflow && configuration.digest !== (workflow.previewConfigDigest ?? sha('')))
|
|
25
|
+
throw Error('PREVIEW_CONFIGURATION_CHANGED');
|
|
26
|
+
const mapping = configuredMapping(finding, configuration), route = mapping.routes.find(r => r.id === query.get('routeId')) || (!query.get('routeId') ? mapping.routes[0] : undefined);
|
|
27
|
+
const mode = query.get('mode') || 'ltr';
|
|
28
|
+
if (!['ltr', 'rtl'].includes(mode))
|
|
29
|
+
throw Error('INVALID_PREVIEW_DIRECTION');
|
|
30
|
+
if (mapping.routes.length && !route)
|
|
31
|
+
throw Error('UNAPPROVED_CONTEXT_ROUTE');
|
|
32
|
+
const source = await readFile(await validateProjectSourcePath(root, finding.path), 'utf8'), sourceHash = sha(source);
|
|
33
|
+
const identity = { projectRoot: root, inputDigest: report.inputDigest, policyDigest: report.policyDigest, findingId: finding.id, path: finding.path, line: finding.range.start.line, column: finding.range.start.column, sourceHash };
|
|
34
|
+
const entry = historical ? undefined : workflow?.entries.find(e => e.finding.id === finding.id);
|
|
35
|
+
const sessionId = historical ? null : workflow?.session?.id || null;
|
|
36
|
+
const eligibility = historical ? classifyEligibility(finding, true, source) : null;
|
|
37
|
+
const review = { inScope: historical || !workflow || !!entry, decision: entry?.decision || 'Pending', applied: entry?.applied || false, hasAutomaticFix: historical ? !!eligibility?.transformationId && !eligibility.blockers.length : !!entry?.patch, validation: historical ? 'Not run' : workflow?.validation?.state || 'Not run', workflowState: workflow?.state || 'No workflow', historical, patchInventory: historical ? [] : workflow?.entries.filter(e => e.patch && e.applied).map(e => ({ findingId: e.finding.id, path: e.finding.path, decision: e.decision })) || [] };
|
|
38
|
+
const candidateState = { prepared: !!sessionId, runtime: workflow?.session?.runtime?.status ?? 'not-started' };
|
|
39
|
+
if (!route)
|
|
40
|
+
return { contextVersion: 2, ...identity, mapping, route: null, original: { available: false, state: 'mapping-missing', reason: mapping.limitation }, candidate: { available: false, state: 'mapping-missing', reason: 'Preview mapping unavailable; ' + (sessionId ? 'candidate is prepared, but no route/target is configured.' : 'candidate has not been prepared.') }, candidateState, reason: mapping.limitation, sessionId, review };
|
|
41
|
+
const urlFor = (origin) => routeUrl(route, mode, origin);
|
|
42
|
+
async function runtime(origin, role, expectedRoot, sessionId, hash) {
|
|
43
|
+
try {
|
|
44
|
+
const response = await fetch(origin + '/__rtl_preview_identity', { signal: AbortSignal.timeout(1500) });
|
|
45
|
+
const actual = await response.json();
|
|
46
|
+
if (!response.ok || actual.projectRoot !== expectedRoot || actual.role !== role || actual.sessionId !== sessionId || actual.application !== route.application || actual.previewConfigDigest !== configuration.digest || actual.inputDigest !== report.inputDigest || actual.policyDigest !== report.policyDigest || actual.sourceHashes?.[finding.path] !== hash)
|
|
47
|
+
return { available: false, origin, url: urlFor(origin), sourceHash: hash, projectRoot: expectedRoot, runtimeSessionId: sessionId, reason: 'Runtime identity/source is stale or belongs to another application. Restart the scoped preview runtime.' };
|
|
48
|
+
return { available: true, state: 'runtime-ready', urls: { ltr: routeUrl(route, 'ltr', origin), rtl: routeUrl(route, 'rtl', origin) }, origin, url: urlFor(origin), sourceHash: hash, projectRoot: expectedRoot, runtimeSessionId: sessionId, reason: null };
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return { available: false, origin, url: urlFor(origin), sourceHash: hash, projectRoot: expectedRoot, runtimeSessionId: sessionId, reason: 'Runtime unavailable. Start the ' + route.application + ' original/candidate preview runtime; no unrelated process will be stopped.' };
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const original = await runtime(configuration.applications[route.application]?.originalOrigin ?? ORIGINAL_PREVIEW_ORIGINS[route.application], 'original', root, 'original', sourceHash);
|
|
55
|
+
let candidate = null, candidateReason = historical ? 'No current candidate. Historical candidate, decisions and validation remain bound to the completed review; they do not validate this current analysis.' : 'No isolated candidate session. Original contextual review does not require a codemod or an apply action.';
|
|
56
|
+
if (workflow?.session && entry && workflow.state === 'Reviewing') {
|
|
57
|
+
// Verify the selected candidate file against its immutable baseline and actual patch membership.
|
|
58
|
+
for (const [path, baseline] of Object.entries(workflow.baseline)) {
|
|
59
|
+
const expected = composeWorkflowFile(baseline, candidateEntries(workflow).filter(e => e.patch?.path === path).map(e => e.patch));
|
|
60
|
+
if (await readFile(await validateProjectSourcePath(workflow.session.candidateRoot, path), 'utf8') !== expected)
|
|
61
|
+
throw Error('STALE_CANDIDATE_SOURCE');
|
|
62
|
+
}
|
|
63
|
+
const before = workflow.baseline[finding.path];
|
|
64
|
+
const expected = composeWorkflowFile(before, candidateEntries(workflow).filter(e => e.patch?.path === finding.path).map(e => e.patch));
|
|
65
|
+
const candidateSource = await readFile(await validateProjectSourcePath(workflow.session.candidateRoot, finding.path), 'utf8');
|
|
66
|
+
if (candidateSource !== expected)
|
|
67
|
+
throw Error('STALE_CANDIDATE_SOURCE');
|
|
68
|
+
const active = candidateApplicationRuntime(workflow.session, route.application);
|
|
69
|
+
if (active?.status === 'healthy')
|
|
70
|
+
candidate = await runtime(active.origin, 'candidate', workflow.session.candidateRoot, workflow.session.id, sha(candidateSource));
|
|
71
|
+
candidateReason = active?.status === 'healthy' ? '' : 'Candidate application runtime is stopped. Use the explicit Open candidate preview action; selecting/highlighting does not start runtimes.';
|
|
72
|
+
}
|
|
73
|
+
return { contextVersion: 2, ...identity, mapping, route, dataAdapter: configuration.applications[route.application]?.dataAdapter ?? 'atlas', original, candidate, candidateReason, candidateState, sessionId, review };
|
|
74
|
+
}
|