-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlugin.ts
More file actions
566 lines (399 loc) · 10.2 KB
/
Copy pathPlugin.ts
File metadata and controls
566 lines (399 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
/**
* RestPlugin.ts - esbuild plugin that invokes the Rest compiler
*
* This plugin integrates the Rest compiler (a Rust-based TypeScript compiler)
* into the esbuild build pipeline. When enabled, it intercepts TypeScript
* files and delegates compilation to the Rest CLI instead of esbuild's
* built-in TypeScript loader.
*
* Usage:
* import RestPlugin from './RestPlugin';
*
* import esbuildConfig from './Output';
*
*
* esbuildConfig.plugins?.push(RestPlugin());
*
*
* Environment Variables:
* Compiler - Set to "Rest" to enable the Rest compiler
* REST_BINARY_PATH - Override the path to the Rest binary
* REST_OPTIONS - Additional command-line options for Rest
*
* @module ESBuild/RestPlugin
*/
import { spawnSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, dirname, extname, join } from "node:path";
import { fileURLToPath } from "node:url";
import type { OnLoadResult, Plugin } from "esbuild";
const __dirname = dirname(fileURLToPath(import.meta.url));
// Enable verbose logging if REST_VERBOSE is set
const REST_VERBOSE = process.env["REST_VERBOSE"] === "true";
// Check if Rest compiler should be used
const USE_REST_COMPILER = process.env["Compiler"]?.toLowerCase() === "rest";
// Rest binary path resolution
const REST_BINARY_PATH =
process.env["REST_BINARY_PATH"] ||
(() => {
// Try to find the Rest binary in various locations
const possiblePaths = [
// From @codeeditorland/rest package
join(
__dirname,
"..",
"..",
"node_modules",
"@codeeditorland/rest",
"bin",
"rest",
),
join(
__dirname,
"..",
"..",
"node_modules",
"@codeeditorland/rest",
"bin",
"rest.exe",
),
// From Element/Rest directory (cargo install --bin=rest location)
join(__dirname, "..", "..", "..", "Rest", "bin", "rest"),
join(__dirname, "..", "..", "..", "Rest", "bin", "Rest"),
join(__dirname, "..", "..", "..", "Rest", "bin", "rest.exe"),
join(__dirname, "..", "..", "..", "Rest", "bin", "Rest.exe"),
// From Target/release (local cargo build)
join(
__dirname,
"..",
"..",
"..",
"Rest",
"Target",
"release",
"rest",
),
join(
__dirname,
"..",
"..",
"..",
"Rest",
"Target",
"release",
"Rest",
),
join(
__dirname,
"..",
"..",
"..",
"Rest",
"Target",
"release",
"rest.exe",
),
join(
__dirname,
"..",
"..",
"..",
"Rest",
"Target",
"release",
"Rest.exe",
),
// Also check debug build (debug directory)
join(
__dirname,
"..",
"..",
"..",
"Rest",
"Target",
"debug",
"rest",
),
join(
__dirname,
"..",
"..",
"..",
"Rest",
"Target",
"debug",
"Rest",
),
// Global installation
"rest",
];
// Debug: log all paths if REST_VERBOSE
if (REST_VERBOSE) {
console.log("[Rest] Checking binary paths:");
for (const p of possiblePaths) {
console.log(
` ${p} -> ${existsSync(p) ? "FOUND" : "not found"}`,
);
}
}
for (const path of possiblePaths) {
if (existsSync(path)) {
console.log(`[Rest] Found binary at: ${path}`);
return path;
}
}
// Default fallback
console.log("[Rest] Falling back to 'rest' from PATH");
return "rest";
})();
// Rest compiler options
const REST_OPTIONS =
process.env["REST_OPTIONS"]?.split(" ").filter(Boolean) || [];
// Enable source maps if NODE_ENV is development or Sourcemap env is set
const ENABLE_SOURCE_MAPS =
process.env["NODE_ENV"] === "development" ||
process.env["TAURI_ENV_DEBUG"] === "true" ||
process.env["RestSourcemap"] === "true";
/**
* Creates the Rest esbuild plugin
*
* @returns {Plugin} The esbuild plugin configuration
*/
export default function RestPlugin(): Plugin {
return {
name: "rest",
setup(build) {
// Only enable if Compiler=Rest is set
if (!USE_REST_COMPILER) {
return;
}
// Log plugin activation with full details
const log = (...args: unknown[]) => {
if (
build.initialOptions.logLevel !== "silent" ||
REST_VERBOSE
) {
console.log("[Rest]", ...args);
}
};
log("Plugin activated - Using Rest compiler");
log("Binary path:", REST_BINARY_PATH);
// Always log debug info when REST_VERBOSE is true
console.log("[Rest] REST_VERBOSE is:", REST_VERBOSE);
console.log("[Rest] __dirname:", __dirname);
console.log(
"[Rest] Checking for binary at resolved path:",
REST_BINARY_PATH,
);
const explicitlyCheck = [
join(
__dirname,
"..",
"..",
"..",
"Rest",
"Target",
"release",
"Rest",
),
join(
__dirname,
"..",
"..",
"..",
"Rest",
"Target",
"release",
"rest",
),
join(__dirname, "..", "..", "..", "Rest", "bin", "Rest"),
join(__dirname, "..", "..", "..", "Rest", "bin", "rest"),
];
for (const p of explicitlyCheck) {
console.log(` Candidate: ${p} exists: ${existsSync(p)}`);
}
if (ENABLE_SOURCE_MAPS) {
log("Source maps: enabled");
}
// Check if Rest binary is available
try {
if (
!existsSync(REST_BINARY_PATH) &&
REST_BINARY_PATH !== "rest"
) {
console.warn(
`[Rest] Binary not found at: ${REST_BINARY_PATH}`,
);
console.warn(
"[Rest] Falling back to global installation or esbuild default",
);
}
} catch (_error) {
// Ignore errors during binary check
}
// Helper function to compile a single file with Rest
const compileWithRest = async (
filePath: string,
ext: string,
): Promise<OnLoadResult | null> => {
const fs = await import("node:fs/promises");
// Rest CLI uses directory-based compilation, so we need to create temp dirs
const tempInputDir = mkdtempSync(join(tmpdir(), "rest-input-"));
const tempOutputDir = mkdtempSync(
join(tmpdir(), "rest-output-"),
);
try {
// Copy input file to temp input directory with same name
const inputFileName = basename(filePath);
const tempInputPath = join(tempInputDir, inputFileName);
await fs.copyFile(filePath, tempInputPath);
// Build Rest compiler command arguments
const args: string[] = [
"compile",
"--input",
tempInputDir,
"--output",
tempOutputDir,
];
// Add source map flag if enabled
if (ENABLE_SOURCE_MAPS) {
args.push("--sourcemap");
}
// Add custom REST_OPTIONS
args.push(...REST_OPTIONS);
if (REST_VERBOSE) {
console.log(
"[Rest] Executing:",
REST_BINARY_PATH,
args.join(" "),
);
}
// Execute Rest compiler using spawnSync for better error capture
const result = spawnSync(REST_BINARY_PATH, args, {
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
env: { ...process.env },
});
if (result.status !== 0) {
const stderr = result.stderr || "";
const stdout = result.stdout || "";
throw new Error(
`Rest compilation failed (exit code ${result.status}):\n${stdout}\n${stderr}`,
);
}
// Read the compiled output file
const outputExt =
ext === ".ts" || ext === ".tsx" ? ".js" : ext;
const tempOutputPath = join(
tempOutputDir,
inputFileName.replace(
extname(inputFileName),
outputExt,
),
);
if (!existsSync(tempOutputPath)) {
throw new Error(
`Rest compiler did not produce output file: ${tempOutputPath}`,
);
}
const contents = readFileSync(tempOutputPath, "utf8");
// Handle source maps if generated
let mapContents: string | undefined;
const mapPath = tempOutputPath + ".map";
if (ENABLE_SOURCE_MAPS && existsSync(mapPath)) {
mapContents = readFileSync(mapPath, "utf8");
}
return {
contents,
loader: "js",
watchFiles: [filePath],
...(mapContents && {
pluginData: { map: mapContents },
}),
};
} finally {
// Clean up temp directories (best effort)
try {
const { rmSync } = await import("node:fs");
rmSync(tempInputDir, { recursive: true, force: true });
rmSync(tempOutputDir, { recursive: true, force: true });
} catch (_error) {
// Ignore cleanup errors
}
}
};
// Intercept TypeScript files
build.onLoad(
{ filter: /\.tsx?$/, namespace: "file" },
async ({ path: filePath }) => {
try {
const ext = extname(filePath);
const result = await compileWithRest(filePath, ext);
if (result) {
return result;
}
} catch (error) {
// On error, fall back to esbuild's default TypeScript handling
const errorMsg = (error as Error).message;
console.warn(
`[Rest] Failed to compile ${filePath} with Rest:`,
errorMsg,
);
console.warn(
`[Rest] Falling back to esbuild TypeScript loader`,
);
}
// Return null to let esbuild handle it
return null;
},
);
// Handle JavaScript files (pass through or compile if needed)
build.onLoad(
{ filter: /\.jsx?$/, namespace: "file" },
async ({ path: filePath }) => {
if (!USE_REST_COMPILER) {
return null;
}
try {
const ext = extname(filePath);
const result = await compileWithRest(filePath, ext);
if (result) {
return result;
}
} catch (error) {
console.warn(
`[Rest] Failed to compile ${filePath} with Rest:`,
(error as Error).message,
);
}
return null;
},
);
},
};
}
/**
* Check if Rest compiler is available and configured
*
* @returns {boolean} True if Rest compiler is enabled
*/
export function isRestEnabled(): boolean {
return USE_REST_COMPILER;
}
/**
* Get the Rest binary path
*
* @returns {string} The resolved binary path
*/
export function getRestBinaryPath(): string {
return REST_BINARY_PATH;
}
/**
* Create Rest plugin conditionally based on COMPILER environment variable
*
* @returns {Plugin | null} Rest plugin if enabled, null otherwise
*/
export function createRestPluginIfEnabled(): Plugin | null {
return USE_REST_COMPILER ? RestPlugin() : null;
}