rtl-analyzer 0.2.0 → 0.3.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.
Files changed (53) hide show
  1. package/README.md +76 -52
  2. package/dist/cli.js +18 -1
  3. package/dist/codemod.js +50 -12
  4. package/dist/companion-security.js +2 -0
  5. package/dist/contextual-preview-bridge.js +113 -0
  6. package/dist/contextual-preview.js +74 -0
  7. package/dist/controlled-apply.js +222 -0
  8. package/dist/css-directional.js +60 -0
  9. package/dist/css-icons.js +51 -0
  10. package/dist/css-spacing.js +64 -0
  11. package/dist/dashboard-client.js +57 -40
  12. package/dist/dashboard-contextual-preview.js +119 -0
  13. package/dist/dashboard-data.js +1 -1
  14. package/dist/dashboard-embedded-preview.js +200 -0
  15. package/dist/dashboard-html.js +11 -10
  16. package/dist/dashboard-review-details.js +175 -0
  17. package/dist/dashboard-review-workflow.js +151 -0
  18. package/dist/directional-properties.js +53 -0
  19. package/dist/discovery.js +1 -2
  20. package/dist/eligibility.js +8 -8
  21. package/dist/evidence-store.js +110 -0
  22. package/dist/example-preview-mappings.js +98 -0
  23. package/dist/manual-change-store.js +27 -0
  24. package/dist/migration-lifecycle.js +19 -0
  25. package/dist/original-preview-runtime.js +68 -0
  26. package/dist/output-path.js +65 -0
  27. package/dist/policy-validation.js +1 -1
  28. package/dist/preview-cli.js +22 -0
  29. package/dist/preview-companion.js +621 -0
  30. package/dist/preview-configuration.js +144 -0
  31. package/dist/preview-runtime.js +98 -0
  32. package/dist/project-configuration.js +48 -0
  33. package/dist/project-root.js +12 -0
  34. package/dist/react-inline.js +65 -0
  35. package/dist/report-publisher.js +4 -7
  36. package/dist/review-approval.js +9 -0
  37. package/dist/review-session.js +199 -54
  38. package/dist/review-store.js +175 -0
  39. package/dist/review-workflow.js +554 -0
  40. package/dist/rules.js +14 -13
  41. package/dist/runtime-process.js +35 -0
  42. package/dist/scan-history.js +35 -0
  43. package/dist/scan-manifest-store.js +26 -0
  44. package/dist/scan.js +55 -4
  45. package/dist/serialization.js +1 -0
  46. package/dist/source-context.js +93 -0
  47. package/dist/source-snippets.js +3 -3
  48. package/dist/standalone-cli.js +14 -1
  49. package/dist/tailwind.js +3 -1
  50. package/dist/transformations.js +20 -0
  51. package/dist/validation.js +71 -0
  52. package/dist/workflow-validation.js +46 -0
  53. package/package.json +17 -8
@@ -0,0 +1,144 @@
1
+ import { readFile, lstat, realpath } from 'node:fs/promises';
2
+ import { resolve, relative, isAbsolute, join } from 'node:path';
3
+ import { hash } from './model.js';
4
+ import { exampleContextMapping } from './example-preview-mappings.js';
5
+ import postcss from 'postcss';
6
+ export const PREVIEW_CONFIGURATION = 'rtl-preview.config.json';
7
+ const fail = (message) => { throw Error('PREVIEW_CONFIGURATION_INVALID: ' + message); };
8
+ const object = (x) => !!x && typeof x === 'object' && !Array.isArray(x);
9
+ function shape(x, keys, label) { if (!object(x) || Object.keys(x).some(k => !keys.includes(k)))
10
+ fail(label + ' shape/unknown field'); }
11
+ const text = (x, max = 1000) => typeof x === 'string' && x.length > 0 && x.length <= max && !/[\x00-\x1f]/.test(x);
12
+ export function previewRelativePath(path) { if (!text(path) || isAbsolute(path) || path.includes('\\') || path.split('/').some(p => !p || p === '..' || p === '.' || ['node_modules', '.git'].includes(p)))
13
+ fail('project-relative path required'); }
14
+ export async function previewFile(root, path, directoryAllowed = false) {
15
+ const base = await realpath(root), target = resolve(base, path);
16
+ if (relative(base, target).startsWith('..') || isAbsolute(relative(base, target)))
17
+ fail('path escapes root');
18
+ let cursor = base;
19
+ for (const part of path.split('/')) {
20
+ cursor = join(cursor, part);
21
+ if ((await lstat(cursor)).isSymbolicLink())
22
+ fail('symlink not allowed');
23
+ }
24
+ const info = await lstat(target);
25
+ if (!info.isFile() && !(directoryAllowed && info.isDirectory()))
26
+ fail('regular file required');
27
+ return target;
28
+ }
29
+ async function configurationText(root) { try {
30
+ const path = join(root, PREVIEW_CONFIGURATION);
31
+ if ((await lstat(path)).isSymbolicLink())
32
+ fail('symlink configuration');
33
+ const value = await readFile(path, 'utf8');
34
+ if (value.length > 200000)
35
+ fail('size limit');
36
+ return value;
37
+ }
38
+ catch (e) {
39
+ if (e.code === 'ENOENT')
40
+ return undefined;
41
+ throw e;
42
+ } }
43
+ export async function previewConfigurationDigest(root) { const raw = await configurationText(root); return raw === undefined ? hash('') : hash('preview-config\0' + raw); }
44
+ export async function loadPreviewConfiguration(root) {
45
+ const raw = await configurationText(root);
46
+ if (raw === undefined)
47
+ return { schemaVersion: 1, applications: {}, mappings: [], digest: hash('') };
48
+ let x;
49
+ try {
50
+ x = JSON.parse(raw);
51
+ }
52
+ catch {
53
+ fail('JSON parse');
54
+ }
55
+ ;
56
+ shape(x, ['schemaVersion', 'applications', 'mappings'], 'root');
57
+ if (x.schemaVersion !== 1 || !object(x.applications) || !Array.isArray(x.mappings))
58
+ fail('schemaVersion/applications/mappings');
59
+ const applications = {};
60
+ for (const [id, a] of Object.entries(x.applications)) {
61
+ if (!/^[a-z][a-z0-9-]{0,50}$/.test(id) || ['__proto__', 'constructor', 'prototype'].includes(id))
62
+ fail('application id');
63
+ shape(a, ['viteConfig', 'entry', 'originalOrigin', 'readySelector', 'dataAdapter', 'routes', 'startupScript'], 'application');
64
+ previewRelativePath(a.viteConfig);
65
+ previewRelativePath(a.entry);
66
+ if (a.startupScript !== undefined && (!text(a.startupScript, 100) || !/^[-\w:]+$/.test(a.startupScript)))
67
+ fail('startup script');
68
+ if (!/[.][cm]?[jt]s$/.test(a.viteConfig) || !text(a.readySelector) || !['none', 'atlas'].includes(String(a.dataAdapter)) || !Array.isArray(a.routes) || !a.routes.length)
69
+ fail('runtime fields');
70
+ let u;
71
+ try {
72
+ u = new URL(String(a.originalOrigin));
73
+ }
74
+ catch {
75
+ fail('origin');
76
+ }
77
+ ;
78
+ if (u.protocol !== 'http:' || u.hostname !== '127.0.0.1' || !u.port || u.origin !== a.originalOrigin || ['4318', '4320'].includes(u.port) || Number(u.port) >= 4202 && Number(u.port) <= 4212)
79
+ fail('loopback original origin required; dashboard/companion/candidate ports reserved');
80
+ const routes = [], ids = new Set();
81
+ for (const r of a.routes) {
82
+ shape(r, ['id', 'path', 'ltr', 'rtl'], 'route');
83
+ if (!text(r.id, 80) || ids.has(String(r.id)) || !text(r.path) || !/^\/[a-zA-Z0-9/_-]*$/.test(r.path))
84
+ fail('route id/path');
85
+ ids.add(String(r.id));
86
+ for (const key of ['ltr', 'rtl']) {
87
+ if (!text(r[key]) || !String(r[key]).startsWith('/') || String(r[key]).startsWith('//') || String(r[key]).includes('\\'))
88
+ fail('relative route URL');
89
+ const url = new URL(String(r[key]), String(a.originalOrigin));
90
+ if (url.origin !== a.originalOrigin || url.pathname !== r.path || url.hash)
91
+ fail('route URL/path mismatch');
92
+ }
93
+ routes.push(r);
94
+ }
95
+ await previewFile(root, a.viteConfig);
96
+ await previewFile(root, a.entry);
97
+ applications[id] = { ...a, routes };
98
+ }
99
+ const mappings = [], seen = new Set();
100
+ for (const m of x.mappings) {
101
+ shape(m, ['source', 'sourceSelector', 'context', 'targetSelector', 'routes'], 'mapping');
102
+ previewRelativePath(m.source);
103
+ if (!text(m.targetSelector) || !Array.isArray(m.routes) || !m.routes.length || m.sourceSelector !== undefined && !text(m.sourceSelector) || m.context !== undefined && !text(m.context))
104
+ fail('mapping fields');
105
+ if (m.source.endsWith('.css') && !text(m.sourceSelector))
106
+ fail('CSS sourceSelector required');
107
+ const key = JSON.stringify([m.source, m.sourceSelector, m.context]);
108
+ if (seen.has(key))
109
+ fail('ambiguous duplicate mapping');
110
+ seen.add(key);
111
+ await previewFile(root, m.source);
112
+ const refs = new Set();
113
+ for (const ref of m.routes) {
114
+ shape(ref, ['application', 'route'], 'route reference');
115
+ if (!text(ref.application) || !text(ref.route) || !applications[ref.application]?.routes.some(r => r.id === ref.route) || refs.has(ref.application + ':' + ref.route))
116
+ fail('unknown/duplicate route reference');
117
+ refs.add(ref.application + ':' + ref.route);
118
+ }
119
+ mappings.push(m);
120
+ }
121
+ return { schemaVersion: 1, applications, mappings, digest: hash('preview-config\0' + raw) };
122
+ }
123
+ export function configuredMapping(f, config) {
124
+ const candidates = config.mappings.filter(m => m.source === f.path && (!m.context || m.context === f.context) && (!m.sourceSelector || f.sourceMechanism === 'css' && f.context === 'stylesheet/' + m.sourceSelector));
125
+ if (candidates.length > 1)
126
+ return { kind: 'unresolved', label: 'Ambiguous configured mapping', selector: '', routes: [], evidence: [], limitation: 'More than one configured locator matches this source context; choose one explicit source binding.' };
127
+ if (!candidates.length)
128
+ return exampleContextMapping(f);
129
+ const m = candidates[0], routes = m.routes.map(ref => { const app = config.applications[ref.application], r = app.routes.find(r => r.id === ref.route); return { id: ref.application + ':' + r.id, application: ref.application, path: r.path, label: ref.application + ' · ' + r.path, urls: { ltr: r.ltr, rtl: r.rtl } }; });
130
+ const mapping = { kind: 'targets', label: 'Configured source binding · runtime verification required', selector: m.targetSelector, routes, evidence: [PREVIEW_CONFIGURATION + ' · ' + m.source + ' · ' + (m.sourceSelector || m.context || 'file locator')], configured: true, sourceSelector: m.sourceSelector, limitation: 'Configuration declares this relationship; the real route, loaded source rule and rendered target must be checked before Verified.' };
131
+ if (m.sourceSelector) {
132
+ try {
133
+ const root = postcss.parse('.probe{' + f.original + '}');
134
+ const decl = root.first?.type === 'rule' ? root.first.nodes.find(n => n.type === 'decl') : undefined;
135
+ if (decl?.type === 'decl')
136
+ mapping.css = { property: decl.prop, value: decl.value, selector: m.sourceSelector };
137
+ }
138
+ catch { /* Whole-rule findings still receive source-rule/target verification. */ }
139
+ }
140
+ return mapping;
141
+ }
142
+ export const runtimeConfigName = (application) => application === 'invoicing' ? 'vite.config.mts' : 'vite.' + application + '.config.mts';
143
+ export function routeUrl(route, mode, origin) { if (route.urls)
144
+ return new URL(route.urls[mode], origin).href; const u = new URL(route.path, origin); u.searchParams.set('demo', 'unmigrated-rtl'); u.searchParams.set('lang', mode === 'rtl' ? 'ar' : 'en'); return u.href; }
@@ -0,0 +1,98 @@
1
+ import { mkdir, readFile, realpath, stat, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { scan } from './scan.js';
5
+ import { contextualBridgeSource } from './contextual-preview-bridge.js';
6
+ import { loadPreviewConfiguration, configuredMapping, runtimeConfigName, previewFile } from './preview-configuration.js';
7
+ import postcss from 'postcss';
8
+ import { DASHBOARD_ORIGIN } from './companion-security.js';
9
+ const scriptJson = (value) => JSON.stringify(value).replaceAll('<', '\\u003c').replaceAll('\u2028', '\\u2028').replaceAll('\u2029', '\\u2029');
10
+ /** Only generated local preview configs install this bridge; production app files stay untouched. */
11
+ export async function writePreviewRuntimeConfig(root, identity, options = {}) {
12
+ const directory = join(root, '.rtl-preview');
13
+ await mkdir(directory, { recursive: true });
14
+ const application = options.application ?? 'invoicing';
15
+ const configuration = await loadPreviewConfiguration(root), configured = configuration.applications[application];
16
+ const dataAdapter = configured?.dataAdapter ?? 'atlas';
17
+ const entry = configured?.entry ?? 'apps/' + application + '/src/main.tsx';
18
+ const viteConfig = configured?.viteConfig ?? 'apps/' + application + '/vite.config.ts';
19
+ if (configured)
20
+ await previewFile(root, viteConfig);
21
+ const runtimeIdentity = { ...identity, projectRoot: await realpath(root), application, previewConfigDigest: configuration.digest, inputDigest: '', policyDigest: '' };
22
+ const sourceHashes = {};
23
+ let bindings = [];
24
+ const hasApps = await stat(join(root, 'apps')).then(value => value.isDirectory()).catch(error => { if (error.code === 'ENOENT')
25
+ return false; throw error; });
26
+ if (hasApps || Object.keys(configuration.applications).length) {
27
+ const report = await scan(options.contextRoot ?? root);
28
+ if (!report.complete)
29
+ throw Error('CONTEXT_SCAN_INCOMPLETE');
30
+ runtimeIdentity.inputDigest = report.inputDigest;
31
+ runtimeIdentity.policyDigest = report.policyDigest;
32
+ for (const path of report.files)
33
+ sourceHashes[path] = createHash('sha256').update(await readFile(join(root, path))).digest('hex');
34
+ bindings = report.findings.map(f => ({ finding: { id: f.id, path: f.path }, mapping: configuredMapping(f, configuration) })).filter(b => b.mapping.routes.some(r => r.application === application));
35
+ // Candidate CSS inspection reuses the shared proposal; no second transformation inventory.
36
+ if (options.contextRoot && options.contextRoot !== root) {
37
+ const { proposeTransformation } = await import('./transformations.js');
38
+ for (const binding of bindings) {
39
+ const f = report.findings.find(f => f.id === binding.finding.id);
40
+ if (!binding.mapping.configured || !binding.mapping.css)
41
+ continue;
42
+ const actual = postcss.parse(await readFile(join(root, f.path), 'utf8'));
43
+ let present = false;
44
+ actual.walkRules(r => { if (r.selector === binding.mapping.sourceSelector && r.nodes.some(d => d.type === 'decl' && d.prop === binding.mapping.css.property))
45
+ present = true; });
46
+ if (present)
47
+ continue;
48
+ try {
49
+ const proposal = proposeTransformation(f, await readFile(join(options.contextRoot, f.path), 'utf8'));
50
+ const replacement = postcss.parse('.probe{' + proposal.patch.replacement + '}').first;
51
+ const declaration = replacement?.type === 'rule' ? replacement.nodes.find(d => d.type === 'decl') : undefined;
52
+ if (declaration?.type === 'decl')
53
+ binding.mapping.css = { ...binding.mapping.css, property: declaration.prop, value: declaration.value };
54
+ }
55
+ catch { /* Target binding remains independent of transformation eligibility. */ }
56
+ }
57
+ }
58
+ }
59
+ const bridge = `(()=>{
60
+ const identity=${scriptJson(runtimeIdentity)},dashboardOrigin=${scriptJson(DASHBOARD_ORIGIN)};
61
+ window.addEventListener('message',event=>{
62
+ const request=event.data;
63
+ if(event.origin!==dashboardOrigin||event.source!==window.parent||!request||request.type!=='rtl-preview-probe'||request.version!==1||typeof request.nonce!=='string'||request.nonce.length>100||request.role!==identity.role||typeof request.findingId!=='string'||!/^RTL\\.BIDI\\.ISOLATION:[a-f0-9]{24,64}$/.test(request.findingId)||request.sourcePath!=='apps/invoicing/src/components/InvoiceTable.tsx'||request.expectedSha256!==identity.sourceSha256||request.runtimeSessionId!==identity.sessionId||typeof request.sessionId!=='string')return;
64
+ if(request.projectRoot!==undefined&&request.projectRoot!==identity.projectRoot)return;
65
+ const links=[...document.querySelectorAll('.invoice-link')];
66
+ const invoiceIds=links.map(link=>link.textContent.trim());
67
+ const bdiCount=document.querySelectorAll('.invoice-link bdi[dir="auto"]').length;
68
+ const rendered=location.pathname==='/invoices'&&links.length>0&&links.every(link=>link.getBoundingClientRect().width>0)&&getComputedStyle(links[0]).color!=='rgb(0, 0, 0)';
69
+ window.parent.postMessage({type:'rtl-preview-status',version:1,nonce:request.nonce,role:identity.role,sessionId:request.sessionId,runtimeSessionId:identity.sessionId,projectRoot:identity.projectRoot,findingId:request.findingId,sourcePath:request.sourcePath,sourceSha256:identity.sourceSha256,rendered,dir:document.documentElement.dir,route:location.pathname,invoiceIds,bdiCount,fixtureData:'atlas-seed-v1'},dashboardOrigin);
70
+ });
71
+ })();` + contextualBridgeSource + '\ninstallContextPreview(' + scriptJson({ identity: runtimeIdentity, dashboardOrigin: DASHBOARD_ORIGIN, sourceHashes, bindings, dataAdapter, readySelector: configured?.readySelector ?? '#root > *' }) + ');';
72
+ const contents = `import { mergeConfig } from 'vite';
73
+ import base from ${JSON.stringify('../' + viteConfig)};
74
+ export default mergeConfig(base, {
75
+ cacheDir:${JSON.stringify(join(root, '.rtl-vite-cache', identity.role, application))},
76
+ esbuild:{target:'esnext'},
77
+ plugins: [{name:'rtl-local-preview',apply:'serve',enforce:'pre',
78
+ transform(source,id){
79
+ const path=id.split('?')[0].replaceAll('\\\\','/');
80
+ if(${JSON.stringify(dataAdapter === 'atlas')}&&path.endsWith('/libs/shared/src/index.ts')&&path.startsWith(${JSON.stringify(runtimeIdentity.projectRoot + '/')})){
81
+ if(!source.includes('const storageKey = \"atlas-invoices-v1\";'))throw Error('PREVIEW_STORAGE_BINDING_UNAVAILABLE');
82
+ return source.replace('const storageKey = \"atlas-invoices-v1\";', 'const storageKey = (window as any).__rtlPreviewStorageKey || \"atlas-invoices-v1\";') + '\\n;(window as any).__rtlPreviewSeedInvoices = seedInvoices;';
83
+ }
84
+ if(path===${JSON.stringify(join(runtimeIdentity.projectRoot, entry))})return 'await (window.__rtlPreviewDataReady || Promise.resolve());\\n'+source;
85
+ },
86
+ configureServer(server){server.middlewares.use('/__rtl_preview_identity',(_request,response)=>{response.setHeader('Content-Type','application/json');response.setHeader('Cache-Control','no-store');response.end(${JSON.stringify(JSON.stringify({ ...runtimeIdentity, contextVersion: 2, sourceHashes }))});});},
87
+ transformIndexHtml(){return [{tag:'script',children:${JSON.stringify(bridge)},injectTo:'head-prepend'}];}
88
+ }],
89
+ server:{headers:{'Content-Security-Policy':${JSON.stringify('frame-ancestors ' + DASHBOARD_ORIGIN)}}}
90
+ });
91
+ `;
92
+ const config = join(directory, runtimeConfigName(application));
93
+ // Identity reconciliation is idempotent; unchanged descriptors must not restart Vite.
94
+ if (await readFile(config, 'utf8').catch(error => { if (error.code === 'ENOENT')
95
+ return ''; throw error; }) !== contents)
96
+ await writeFile(config, contents, 'utf8');
97
+ return config;
98
+ }
@@ -0,0 +1,48 @@
1
+ import { readFile, lstat } from 'node:fs/promises';
2
+ import { join, isAbsolute } from 'node:path';
3
+ import { previewFile } from './preview-configuration.js';
4
+ export const PROJECT_CONFIGURATION = 'rtl-project.config.json';
5
+ export function projectRelativePath(value) {
6
+ if (typeof value !== 'string' || !value || value.length > 1000 || isAbsolute(value) || /[\\\x00-\x1f]/.test(value) || value.split('/').some(p => !p || p === '.' || p === '..' || ['node_modules', '.git', '.rtl-preview', '.rtl-vite-cache', 'dist'].includes(p)))
7
+ throw Error('PROJECT_CONFIGURATION_INVALID_PATH');
8
+ }
9
+ export async function loadProjectConfiguration(root) {
10
+ let raw;
11
+ try {
12
+ const path = join(root, PROJECT_CONFIGURATION);
13
+ if ((await lstat(path)).isSymbolicLink())
14
+ throw Error('PROJECT_CONFIGURATION_SYMLINK');
15
+ raw = await readFile(path, 'utf8');
16
+ }
17
+ catch (error) {
18
+ if (error.code === 'ENOENT')
19
+ return;
20
+ throw error;
21
+ }
22
+ if (raw.length > 100000)
23
+ throw Error('PROJECT_CONFIGURATION_SIZE');
24
+ const c = JSON.parse(raw);
25
+ if (!c || c.schemaVersion !== 1 || Object.keys(c).some(k => !['schemaVersion', 'scanRoots', 'copyPaths', 'packageManager', 'validation', 'validationExclusions'].includes(k)) || !['npm', 'pnpm', 'yarn'].includes(c.packageManager) || !c.validation || typeof c.validation !== 'object' || Array.isArray(c.validation))
26
+ throw Error('PROJECT_CONFIGURATION_INVALID');
27
+ for (const paths of [c.scanRoots, c.copyPaths]) {
28
+ if (!Array.isArray(paths) || !paths.length || paths.length > 100 || new Set(paths).size !== paths.length)
29
+ throw Error('PROJECT_CONFIGURATION_INVALID_SCOPE');
30
+ for (const path of paths) {
31
+ projectRelativePath(path); /* Check every ancestor, including directories. */
32
+ await previewFile(root, path, true);
33
+ }
34
+ }
35
+ if (c.scanRoots.some(path => !c.copyPaths.some(copy => path === copy || path.startsWith(copy + '/'))))
36
+ throw Error('PROJECT_CONFIGURATION_SCAN_NOT_COPIED');
37
+ for (const [name, args] of Object.entries(c.validation))
38
+ if (!['typecheck', 'build', 'test'].includes(name) || !Array.isArray(args) || !args.length || args.length > 30 || args.some(a => typeof a !== 'string' || !a || a.length > 1000 || /[\x00-\x1f]/.test(a)))
39
+ throw Error('PROJECT_CONFIGURATION_INVALID_CHECK');
40
+ if (c.validationExclusions) {
41
+ if (typeof c.validationExclusions !== 'object' || Array.isArray(c.validationExclusions))
42
+ throw Error('PROJECT_CONFIGURATION_INVALID_EXCLUSION');
43
+ for (const [name, reason] of Object.entries(c.validationExclusions))
44
+ if (!['typecheck', 'build', 'test'].includes(name) || c.validation[name] || typeof reason !== 'string' || !reason.trim() || reason.length > 1000)
45
+ throw Error('PROJECT_CONFIGURATION_INVALID_EXCLUSION');
46
+ }
47
+ return c;
48
+ }
@@ -0,0 +1,12 @@
1
+ import { lstat, realpath } from 'node:fs/promises';
2
+ import { isAbsolute, resolve } from 'node:path';
3
+ export async function resolveTrustedProjectRoot() {
4
+ const configured = process.env.RTL_PROJECT_ROOT;
5
+ if (!configured || !isAbsolute(configured))
6
+ throw new Error('TRUSTED_PROJECT_ROOT_REQUIRED');
7
+ const root = await realpath(resolve(configured));
8
+ const stat = await lstat(root);
9
+ if (!stat.isDirectory())
10
+ throw new Error('TRUSTED_PROJECT_ROOT_NOT_DIRECTORY');
11
+ return root;
12
+ }
@@ -0,0 +1,65 @@
1
+ import ts from 'typescript';
2
+ import { hash } from './model.js';
3
+ import { directionalProperty, propertyConflict, readingEdgeReason } from './directional-properties.js';
4
+ import { hasIsolation } from './codemod.js';
5
+ export const REACT_INLINE_TRANSFORMATION_ID = 'react-inline-logical';
6
+ const css = (s) => s.replace(/[A-Z]/g, c => '-' + c.toLowerCase());
7
+ const camel = (s) => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
8
+ export function proposeReactInline(finding, source) {
9
+ const reject = (s) => { throw Error('REACT_INLINE_' + s); };
10
+ if (!['RTL.CSS.PHYSICAL', 'RTL.GEOMETRY.EDGE'].includes(finding.ruleId) || finding.sourceMechanism !== 'react-inline' || !/^.+\.[jt]sx$/.test(finding.path))
11
+ reject('DIRECT_JSX_STYLE_ONLY');
12
+ if (finding.exceptionReason || ['INTENTIONAL_LTR', 'INFORMATIONAL'].includes(finding.category) || finding.ownership !== 'custom-inline')
13
+ reject('OWNER_OR_INTENT_REVIEW');
14
+ if (!new RegExp('^' + finding.ruleId.replaceAll('.', '\\.') + ':[a-f0-9]{24,64}$').test(finding.id))
15
+ reject('FINDING_IDENTITY');
16
+ const file = ts.createSourceFile(finding.path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
17
+ let target;
18
+ function walk(n) { if (ts.isPropertyAssignment(n) && n.getStart(file) === finding.range.start.offset && n.end === finding.range.end.offset)
19
+ target = n; ts.forEachChild(n, walk); }
20
+ walk(file);
21
+ if (!target || source.slice(finding.range.start.offset, finding.range.end.offset) !== finding.original)
22
+ reject('STALE_RANGE');
23
+ const p = target, object = p.parent;
24
+ if (!ts.isObjectLiteralExpression(object) || !ts.isJsxExpression(object.parent) || !ts.isJsxAttribute(object.parent.parent) || object.parent.parent.name.getText(file) !== 'style')
25
+ reject('DIRECT_OBJECT_REQUIRED');
26
+ const opening = object.parent.parent.parent.parent;
27
+ if (!(ts.isJsxOpeningElement(opening) || ts.isJsxSelfClosingElement(opening)) || !/^[a-z][a-z0-9]*$/.test(opening.tagName.getText(file)))
28
+ reject('NATIVE_ELEMENT_REQUIRED');
29
+ const element = opening;
30
+ if (hasIsolation(element) || element.attributes.properties.some(a => ts.isJsxSpreadAttribute(a)))
31
+ reject('DIRECTION_OR_SPREAD_REVIEW');
32
+ if (object.properties.some(n => !ts.isPropertyAssignment(n) || ts.isComputedPropertyName(n.name)))
33
+ reject('UNRESOLVED_OBJECT');
34
+ if (/rtl-physical\s*:/i.test(object.getFullText(file)))
35
+ reject('INTENTIONAL_PHYSICAL');
36
+ if (!(ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)))
37
+ reject('PROPERTY_SPELLING');
38
+ const key = p.name.text;
39
+ if (key.includes('-'))
40
+ reject('PROPERTY_SPELLING');
41
+ const value = p.initializer;
42
+ const literal = (n) => ts.isStringLiteral(n) ? n.text : ts.isNumericLiteral(n) ? n.text : ts.isPrefixUnaryExpression(n) && n.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(n.operand) ? '-' + n.operand.text : undefined;
43
+ const raw = literal(value);
44
+ if (raw === undefined)
45
+ reject('LITERAL_VALUE_REQUIRED');
46
+ const spec = directionalProperty(css(key), raw, !ts.isStringLiteral(value));
47
+ if (!spec)
48
+ reject('UNSUPPORTED_PROPERTY_OR_VALUE');
49
+ const peers = object.properties.filter((n) => ts.isPropertyAssignment(n) && n !== p);
50
+ if (peers.some(n => !(ts.isIdentifier(n.name) || ts.isStringLiteral(n.name)) || propertyConflict(css(key), css(n.name.text), spec.family)))
51
+ reject('CASCADE_DECLARATION_CONFLICT');
52
+ if (spec.family === 'positioning' && !peers.some(n => n.name.getText(file) === 'position' && ts.isStringLiteral(n.initializer) && /^(absolute|fixed)$/.test(n.initializer.text)))
53
+ reject('EXPLICIT_POSITION_REQUIRED');
54
+ // No dynamic peer can silently introduce unresolved direction/cascade semantics.
55
+ if (peers.some(n => literal(n.initializer) === undefined))
56
+ reject('DYNAMIC_PEER_REVIEW');
57
+ const name = camel(spec.logical), nameRaw = ts.isStringLiteral(p.name) ? source[p.name.getStart(file)] + name + source[p.name.end - 1] : name;
58
+ let replacement = nameRaw + source.slice(p.name.end, p.end);
59
+ if (spec.family === 'alignment') {
60
+ if (!ts.isStringLiteral(value) || /\\/.test(value.getText(file)))
61
+ reject('VALUE_SPELLING');
62
+ replacement = source.slice(p.getStart(file), value.getStart(file)) + source[value.getStart(file)] + spec.value + source[value.end - 1];
63
+ }
64
+ return { transformationId: REACT_INLINE_TRANSFORMATION_ID, reason: readingEdgeReason, patch: { findingId: finding.id, path: finding.path, startOffset: p.getStart(file), endOffset: p.end, expectedSha256: hash(finding.original), replacement } };
65
+ }
@@ -17,7 +17,7 @@ async function assertDirectory(path, root, fs) {
17
17
  // The trusted-owner POSIX profile cannot eliminate a malicious directory
18
18
  // replacement between validation and the hard-link call; the immediate
19
19
  // lstat and same-directory no-overwrite link minimize that residual TOCTOU.
20
- if (fs.platform !== 'darwin' && fs.platform !== 'linux' && fs.platform !== 'win32')
20
+ if (fs.platform !== 'darwin' && fs.platform !== 'linux')
21
21
  throw new PublicationError('unsupported platform/filesystem profile');
22
22
  const absolute = resolve(path);
23
23
  const rel = relative(root, absolute);
@@ -39,8 +39,9 @@ async function prepare(directory, name, contents, fs) {
39
39
  handle = await fs.open(temp, 'wx', 0o600);
40
40
  await handle.writeFile(contents, 'utf8');
41
41
  await handle.sync();
42
+ const stat = await handle.stat();
42
43
  await handle.close();
43
- return { temp };
44
+ return { temp, stat: { dev: stat.dev, ino: stat.ino } };
44
45
  }
45
46
  catch (error) {
46
47
  await handle?.close().catch(() => undefined);
@@ -58,11 +59,7 @@ async function publish(directory, name, contents, fs) {
58
59
  await assertDirectory(directory, directory + '/__external-root-that-cannot-match', fs);
59
60
  const destination = join(directory, name);
60
61
  await fs.link(prepared.temp, destination);
61
- const sourceStat = await fs.lstat(prepared.temp);
62
- const destinationStat = await fs.lstat(destination);
63
- if (sourceStat.dev !== destinationStat.dev || sourceStat.ino !== destinationStat.ino || destinationStat.isSymbolicLink())
64
- throw new PublicationError('published destination identity mismatch');
65
- created = { path: destination, dev: destinationStat.dev, ino: destinationStat.ino };
62
+ created = { path: destination, ...prepared.stat };
66
63
  await fs.unlink(prepared.temp);
67
64
  return created;
68
65
  }
@@ -0,0 +1,9 @@
1
+ export function recoverCandidateSessionId(input, current) {
2
+ if (input.candidateSessionId && current?.candidateSessionId && input.candidateSessionId !== current.candidateSessionId) {
3
+ throw new Error('CANDIDATE_SESSION_MISMATCH');
4
+ }
5
+ const candidateSessionId = input.candidateSessionId ?? current?.candidateSessionId;
6
+ if (!candidateSessionId)
7
+ throw new Error('HEALTHY_CANDIDATE_REQUIRED');
8
+ return candidateSessionId;
9
+ }