|
1 | 1 | import { promises as fs } from 'node:fs';
|
2 |
| -import { dirname, posix, relative, resolve, sep } from 'node:path'; |
| 2 | +import { dirname, isAbsolute, posix, relative, resolve, sep } from 'node:path'; |
3 | 3 |
|
4 | 4 | import type { DecodedSourceMap, RawSourceMap } from '@ampproject/remapping';
|
5 | 5 | import MagicString from 'magic-string';
|
@@ -102,7 +102,8 @@ export const jsMiddleware = async ({
|
102 | 102 | import.meta.pleasantestArgs = [...window._pleasantestArgs]
|
103 | 103 | }`;
|
104 | 104 | const fileSrc = await fs.readFile(file, 'utf8');
|
105 |
| - const inlineStartIdx = fileSrc.indexOf(code); |
| 105 | + const EOL = detectLineEndings(fileSrc); |
| 106 | + const inlineStartIdx = fileSrc.indexOf(code.replaceAll('\n', EOL)); |
106 | 107 | code = injectedArgsCode + code;
|
107 | 108 | if (inlineStartIdx !== -1) {
|
108 | 109 | const str = new MagicString(fileSrc);
|
@@ -180,16 +181,16 @@ export const jsMiddleware = async ({
|
180 | 181 | if (resolved) {
|
181 | 182 | spec = typeof resolved === 'object' ? resolved.id : resolved;
|
182 | 183 | if (spec.startsWith('@npm/')) return addBuildId(`/${spec}`);
|
183 |
| - if (/^(\/|\\|[a-z]:\\)/i.test(spec)) { |
| 184 | + if (isAbsolute(path)) { |
184 | 185 | // Change FS-absolute paths to relative
|
185 |
| - spec = relative(dirname(file), spec).split(sep).join(posix.sep); |
| 186 | + spec = relative(dirname(file), spec).split(sep).join('/'); |
186 | 187 | if (!/^\.?\.?\//.test(spec)) spec = `./${spec}`;
|
187 | 188 | }
|
188 | 189 |
|
189 | 190 | if (typeof resolved === 'object' && resolved.external) {
|
190 | 191 | if (/^(data|https?):/.test(spec)) return spec;
|
191 | 192 |
|
192 |
| - spec = relative(root, spec).split(sep).join(posix.sep); |
| 193 | + spec = relative(root, spec).split(sep).join('/'); |
193 | 194 | if (!/^(\/|[\w-]+:)/.test(spec)) spec = `/${spec}`;
|
194 | 195 | return addBuildId(spec);
|
195 | 196 | }
|
@@ -233,3 +234,13 @@ export const jsMiddleware = async ({
|
233 | 234 | }
|
234 | 235 | };
|
235 | 236 | };
|
| 237 | + |
| 238 | +const detectLineEndings = (fileSrc: string) => { |
| 239 | + // Find the first line end (\n) and check if the character before is \r |
| 240 | + // This tells us whether the file uses \r\n or just \n for line endings. |
| 241 | + // Using node:os.EOL is not sufficient because git on windows |
| 242 | + // Can be configured to check out files with either kind of line ending. |
| 243 | + const firstLineEndPos = fileSrc.indexOf('\n'); |
| 244 | + if (fileSrc[firstLineEndPos - 1] === '\r') return '\r\n'; |
| 245 | + return '\n'; |
| 246 | +}; |
0 commit comments