|
1 | 1 | import { spawn } from 'node:child_process' |
| 2 | +import { existsSync } from 'node:fs' |
2 | 3 | import path from 'node:path' |
3 | 4 | import { parse } from 'oxc-parser' |
4 | 5 | import type { Plugin, ViteDevServer } from 'vite' |
@@ -91,14 +92,41 @@ async function findJsxElements(code: string, filename: string): Promise<JsxLocat |
91 | 92 |
|
92 | 93 | type TransformOut = { code: string; map?: null } | undefined |
93 | 94 |
|
| 95 | +export function getSourceInspectorPath(filePath: string, cwd = process.cwd()): string { |
| 96 | + const normalizedFilePath = normalizePath(filePath) |
| 97 | + const normalizedCwd = normalizePath(cwd) |
| 98 | + |
| 99 | + if (normalizedFilePath === normalizedCwd) { |
| 100 | + return '/' |
| 101 | + } |
| 102 | + |
| 103 | + if (normalizedFilePath.startsWith(`${normalizedCwd}/`)) { |
| 104 | + return normalizedFilePath.slice(normalizedCwd.length) |
| 105 | + } |
| 106 | + |
| 107 | + return normalizedFilePath |
| 108 | +} |
| 109 | + |
| 110 | +export function resolveEditorFilePath( |
| 111 | + filePath: string, |
| 112 | + cwd = process.cwd(), |
| 113 | + fileExists: (path: string) => boolean = existsSync |
| 114 | +): string { |
| 115 | + const projectPath = path.join(cwd, filePath) |
| 116 | + |
| 117 | + // data-one-source uses "/foo.tsx" for project-relative paths, but files outside |
| 118 | + // cwd are stored as absolute paths and must not be re-joined onto cwd. |
| 119 | + return fileExists(projectPath) ? projectPath : filePath |
| 120 | +} |
| 121 | + |
94 | 122 | /** |
95 | 123 | * Transforms JSX to inject data-one-source attributes using oxc-parser. |
96 | 124 | */ |
97 | 125 | async function injectSourceToJsx(code: string, id: string): Promise<TransformOut> { |
98 | 126 | const [filePath] = id.split('?') |
99 | 127 | if (!filePath) return |
100 | 128 |
|
101 | | - const location = filePath.replace(normalizePath(process.cwd()), '') |
| 129 | + const location = getSourceInspectorPath(filePath) |
102 | 130 |
|
103 | 131 | // Quick check - skip if no JSX-like content |
104 | 132 | if (!code.includes('<') || !code.includes('>')) { |
@@ -159,7 +187,7 @@ function openInEditor( |
159 | 187 | return |
160 | 188 | } |
161 | 189 |
|
162 | | - const fullPath = path.join(process.cwd(), filePath) |
| 190 | + const fullPath = resolveEditorFilePath(filePath) |
163 | 191 | const l = line || '1' |
164 | 192 | const c = column || '1' |
165 | 193 | const buildArgs = editorArgs[resolved] |
|
0 commit comments