-
-
Notifications
You must be signed in to change notification settings - Fork 511
Expand file tree
/
Copy pathModuleResolverNode.ts
More file actions
600 lines (531 loc) · 17.9 KB
/
ModuleResolverNode.ts
File metadata and controls
600 lines (531 loc) · 17.9 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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import type * as PrettierTypes from "prettier";
import * as semver from "semver";
import { commands, TextDocument, Uri, window, workspace } from "vscode";
import {
resolveGlobalNodePath,
resolveGlobalYarnPath,
resolveGlobalPnpmPath,
} from "./utils/global-node-paths.js";
import { findUp, pathExists, FIND_UP_STOP } from "./utils/find-up.js";
import { LoggingService } from "./LoggingService.js";
import {
FAILED_TO_LOAD_MODULE_MESSAGE,
INVALID_PRETTIER_CONFIG,
INVALID_PRETTIER_PATH_MESSAGE,
OUTDATED_PRETTIER_VERSION_MESSAGE,
UNTRUSTED_WORKSPACE_SKIPPING_CONFIG,
UNTRUSTED_WORKSPACE_USING_BUNDLED_PRETTIER,
USING_BUNDLED_PRETTIER,
} from "./message.js";
import {
ModuleResolverInterface,
PackageManagers,
PrettierOptions,
PrettierResolveConfigOptions,
PrettierVSCodeConfig,
PrettierInstance,
} from "./types.js";
import {
getWorkspaceConfig,
getWorkspaceRelativePath,
} from "./utils/workspace.js";
import { PrettierDynamicInstance } from "./PrettierDynamicInstance.js";
const minPrettierVersion = "1.13.0";
let emptyConfigPath: string | undefined;
async function getEmptyConfigPath(): Promise<string> {
if (emptyConfigPath) {
return emptyConfigPath;
}
const tempDir = await fs.promises.mkdtemp(
path.join(os.tmpdir(), "prettier-vscode-"),
);
emptyConfigPath = path.join(tempDir, "empty.prettierrc.json");
await fs.promises.writeFile(emptyConfigPath, "{}", { encoding: "utf8" });
return emptyConfigPath;
}
export type PrettierNodeModule = typeof PrettierTypes;
// Lazy-load prettier to avoid blocking the extension host during module loading
let prettierModule: PrettierNodeModule | undefined;
async function getBundledPrettier(): Promise<PrettierNodeModule> {
if (!prettierModule) {
const imported = await import("prettier");
// Handle both ESM (Prettier v3+) and CJS (Prettier v2) modules
// CJS modules imported via ESM have their exports on the default property
prettierModule = (
imported.default?.version ? imported.default : imported
) as PrettierNodeModule;
}
return prettierModule;
}
// Cache for global package manager paths (async)
const globalPathCache = new Map<string, Promise<string | undefined>>();
async function globalPathGet(
packageManager: PackageManagers,
): Promise<string | undefined> {
// Check if we already have a cached promise
if (globalPathCache.has(packageManager)) {
return globalPathCache.get(packageManager);
}
// Create the promise and cache it
let resolvePromise: Promise<string | undefined>;
switch (packageManager) {
case "npm":
resolvePromise = resolveGlobalNodePath();
break;
case "yarn":
resolvePromise = resolveGlobalYarnPath();
break;
case "pnpm":
resolvePromise = resolveGlobalPnpmPath();
break;
default:
resolvePromise = Promise.resolve(undefined);
}
globalPathCache.set(packageManager, resolvePromise);
return resolvePromise;
}
export class ModuleResolver implements ModuleResolverInterface {
private path2Module = new Map<string, PrettierInstance>();
constructor(private loggingService: LoggingService) {}
public async getGlobalPrettierInstance(): Promise<PrettierNodeModule> {
return getBundledPrettier();
}
public async getPrettierInstance(
fileName: string,
): Promise<PrettierInstance | PrettierNodeModule | undefined> {
// For untrusted workspaces, always use bundled prettier for security
if (!workspace.isTrusted) {
this.loggingService.logDebug(UNTRUSTED_WORKSPACE_USING_BUNDLED_PRETTIER);
return getBundledPrettier();
}
const { prettierPath, resolveGlobalModules } = getWorkspaceConfig(
Uri.file(fileName),
);
// Look for local module
let modulePath: string | undefined;
try {
modulePath = prettierPath
? await this.getModuleFromPrettierPath(fileName, prettierPath)
: await this.findPrettierModule(fileName);
} catch (error) {
let msg = `Unable to find prettier module`;
if (error instanceof Error) {
msg += `: ${error.message}`;
}
this.loggingService.logError(msg);
}
// If global modules allowed, look there
if (!modulePath && resolveGlobalModules) {
modulePath = await this.findGlobalModule("prettier");
}
// Fall back to bundled prettier when no local is found
if (!modulePath) {
this.loggingService.logDebug(USING_BUNDLED_PRETTIER);
return getBundledPrettier();
}
const isValidVersion = await this.isValidVersion(modulePath);
if (!isValidVersion) {
return undefined;
}
// Check cache
let prettierInstance = this.path2Module.get(modulePath);
if (prettierInstance) {
return prettierInstance;
}
// Create new instance using PrettierDynamicInstance for ESM support
prettierInstance = new PrettierDynamicInstance(modulePath);
// Import the module to populate version and validate it loads correctly
try {
await prettierInstance.import();
} catch (error) {
this.loggingService.logError(
`${FAILED_TO_LOAD_MODULE_MESSAGE}: ${modulePath}`,
error,
);
return undefined;
}
this.path2Module.set(modulePath, prettierInstance);
return prettierInstance;
}
private async getModuleFromPrettierPath(
fileName: string,
prettierPath: string,
): Promise<string | undefined> {
const absolutePrettierPath = path.isAbsolute(prettierPath)
? prettierPath
: path.join(
workspace.getWorkspaceFolder(Uri.file(fileName))?.uri.fsPath ?? "",
prettierPath,
);
if (await pathExists(absolutePrettierPath)) {
return absolutePrettierPath;
}
this.loggingService.logError(INVALID_PRETTIER_PATH_MESSAGE);
return undefined;
}
public async getResolvedIgnorePath(
fileName: string,
ignorePath: string,
): Promise<string | undefined> {
// First try workspace-relative path
const resolvedPath = getWorkspaceRelativePath(fileName, ignorePath);
if (resolvedPath && (await pathExists(resolvedPath))) {
return resolvedPath;
}
// If not found in workspace, search upward from file directory
// This handles nested workspace folders where .prettierignore is in a parent directory
const foundPath = await findUp(
async (dir: string) => {
const ignoreFilePath = path.join(dir, ignorePath);
if (await pathExists(ignoreFilePath)) {
return ignoreFilePath;
}
// Stop at marker file
if (
await pathExists(path.join(dir, ".do-not-use-prettier-vscode-root"))
) {
return FIND_UP_STOP;
}
return undefined;
},
{ cwd: path.dirname(fileName) },
);
if (foundPath) {
return foundPath;
}
this.loggingService.logWarning(
`Unable to resolve ignore path: ${ignorePath} for ${fileName}`,
);
return;
}
public async getResolvedConfig(
doc: TextDocument,
vscodeConfig: PrettierVSCodeConfig,
): Promise<"error" | "disabled" | PrettierOptions | null> {
const fileName = doc.fileName;
const prettier =
(await this.getPrettierInstance(fileName)) ??
(await getBundledPrettier());
return this.resolveConfig(prettier, fileName, vscodeConfig);
}
public async clearModuleCache(filePath: string): Promise<void> {
const prettier =
(await this.getPrettierInstance(filePath)) ??
(await getBundledPrettier());
try {
await prettier.clearConfigCache();
} catch (error) {
this.loggingService.logError(
`Failed to clear config cache for ${filePath}`,
error,
);
}
}
private async findPrettierModule(
fileName: string,
): Promise<string | undefined> {
// fileName might be a file path or a directory path (e.g., workspace folder)
// If it's a directory, use it directly; otherwise get its parent directory
let dir: string;
try {
const stat = await fs.promises.stat(fileName);
dir = stat.isDirectory() ? fileName : path.dirname(fileName);
} catch {
// If stat fails, assume it's a file path and get its parent
dir = path.dirname(fileName);
}
const foundPath = await findUp(
async (d: string) => {
const nodeModulesDir = path.join(d, "node_modules");
const prettierPath = path.join(nodeModulesDir, "prettier");
if (await pathExists(prettierPath)) {
return prettierPath;
}
// Also check for prettier inside nested dependencies
// This handles cases where prettier is a dependency of a local module
if (await pathExists(nodeModulesDir)) {
try {
const entries = await fs.promises.readdir(nodeModulesDir);
for (const entry of entries) {
// Skip hidden files and @scoped packages for now
if (entry.startsWith(".") || entry.startsWith("@")) {
continue;
}
const nestedPrettierPath = path.join(
nodeModulesDir,
entry,
"node_modules",
"prettier",
);
if (await pathExists(nestedPrettierPath)) {
return nestedPrettierPath;
}
}
} catch {
// Ignore errors reading directory
}
}
// Stop searching at .do-not-use-prettier-vscode-root marker
if (
await pathExists(path.join(d, ".do-not-use-prettier-vscode-root"))
) {
return FIND_UP_STOP;
}
return undefined;
},
{ cwd: dir },
);
return foundPath;
}
private async findGlobalModule(
moduleName: string,
): Promise<string | undefined> {
const packageManagers: PackageManagers[] = ["npm", "yarn", "pnpm"];
for (const pm of packageManagers) {
const globalPath = await globalPathGet(pm);
if (globalPath) {
const modulePath = path.join(globalPath, moduleName);
if (await pathExists(modulePath)) {
return modulePath;
}
}
}
return undefined;
}
private async isValidVersion(modulePath: string): Promise<boolean> {
let modulePackageJsonPath = "";
try {
// Check if modulePath is a file or directory
// If it's a file (e.g., .yarn/sdks/prettier/index.cjs), look for package.json in parent directory
let packageDir = modulePath;
try {
const stat = await fs.promises.stat(modulePath);
if (stat.isFile()) {
packageDir = path.dirname(modulePath);
}
} catch {
// If stat fails, assume it's a directory path
}
modulePackageJsonPath = path.join(packageDir, "package.json");
const rawPkgJson = await fs.promises.readFile(modulePackageJsonPath, {
encoding: "utf8",
});
const pkgJson = JSON.parse(rawPkgJson) as { version: string };
const version = pkgJson.version;
if (!semver.gte(version, minPrettierVersion)) {
this.loggingService.logError(OUTDATED_PRETTIER_VERSION_MESSAGE);
this.loggingService.logInfo(
`Found version ${version}, requires ${minPrettierVersion}+`,
);
// Show a warning popup to the user
void window
.showWarningMessage(
`Prettier: Version ${version} is outdated. Please upgrade to Prettier ${minPrettierVersion} or newer.`,
"Learn More",
)
.then((selection) => {
if (selection === "Learn More") {
void commands.executeCommand(
"vscode.open",
Uri.parse("https://prettier.io/docs/en/install"),
);
}
});
await commands.executeCommand(
"setContext",
"prettier.outdatedError",
true,
);
return false;
}
await commands.executeCommand(
"setContext",
"prettier.outdatedError",
false,
);
return true;
} catch {
this.loggingService.logError(
`${FAILED_TO_LOAD_MODULE_MESSAGE} ${modulePackageJsonPath}`,
);
return false;
}
}
public async resolveConfig(
prettierInstance: {
resolveConfigFile(filePath?: string): Promise<string | null>;
resolveConfig(
fileName: string,
options?: PrettierResolveConfigOptions,
): Promise<PrettierOptions | null>;
},
fileName: string,
vscodeConfig: PrettierVSCodeConfig,
): Promise<"error" | "disabled" | PrettierOptions | null> {
// In untrusted workspaces, skip config resolution entirely.
// Prettier's resolveConfigFile/resolveConfig can execute JS config files
// (.prettierrc.js, prettier.config.js, etc.) which would allow arbitrary
// code execution.
if (!workspace.isTrusted) {
this.loggingService.logDebug(UNTRUSTED_WORKSPACE_SKIPPING_CONFIG);
if (vscodeConfig.requireConfig) {
return "disabled";
}
return null;
}
const configSearchRoot = await findUp(
async (dir: string) => {
if (
await pathExists(
path.join(dir, ".do-not-use-prettier-vscode-root"),
)
) {
return dir;
}
return undefined;
},
{ cwd: path.dirname(fileName), type: "directory" },
);
const isWithinSearchRoot = (candidatePath: string) => {
if (!configSearchRoot) {
return true;
}
const relative = path.relative(configSearchRoot, candidatePath);
return (
relative === "" ||
(!relative.startsWith("..") && !path.isAbsolute(relative))
);
};
let configPath: string | undefined;
try {
configPath =
(await prettierInstance.resolveConfigFile(fileName)) ?? undefined;
} catch (error) {
this.loggingService.logError(
`Failed to resolve config file for ${fileName}`,
error,
);
return "error";
}
// Log what config file was found (if any)
if (configPath) {
this.loggingService.logInfo(`Using config file at ${configPath}`);
}
// Log if editorconfig will be considered
if (vscodeConfig.useEditorConfig) {
this.loggingService.logInfo(
"EditorConfig support is enabled, checking for .editorconfig files",
);
}
let resolvedConfig: PrettierOptions | null;
try {
const customConfigPath = vscodeConfig.configPath
? getWorkspaceRelativePath(fileName, vscodeConfig.configPath)
: undefined;
let limitConfigSearch = false;
if (!customConfigPath && configSearchRoot) {
if (!configPath) {
limitConfigSearch = true;
} else if (!isWithinSearchRoot(configPath)) {
this.loggingService.logInfo(
`Ignoring config file outside search root: ${configPath}`,
);
configPath = undefined;
limitConfigSearch = true;
}
}
// Log if a custom config path is specified in VS Code settings
if (customConfigPath) {
this.loggingService.logInfo(
`Using custom config path from settings: ${customConfigPath}`,
);
}
if (customConfigPath || configPath) {
const resolveConfigOptions: PrettierResolveConfigOptions = {
config: customConfigPath ?? configPath,
editorconfig: vscodeConfig.useEditorConfig,
};
resolvedConfig = await prettierInstance.resolveConfig(
fileName,
resolveConfigOptions,
);
} else if (limitConfigSearch && vscodeConfig.useEditorConfig) {
const editorConfigPath = await findUp(
async (dir: string) => {
const editorConfigCandidate = path.join(dir, ".editorconfig");
if (await pathExists(editorConfigCandidate)) {
return editorConfigCandidate;
}
if (
await pathExists(
path.join(dir, ".do-not-use-prettier-vscode-root"),
)
) {
return FIND_UP_STOP;
}
return undefined;
},
{ cwd: path.dirname(fileName) },
);
if (editorConfigPath) {
const resolveConfigOptions: PrettierResolveConfigOptions = {
config: await getEmptyConfigPath(),
editorconfig: true,
};
resolvedConfig = await prettierInstance.resolveConfig(
fileName,
resolveConfigOptions,
);
} else {
resolvedConfig = null;
}
} else {
const resolveConfigOptions: PrettierResolveConfigOptions = {
editorconfig: vscodeConfig.useEditorConfig,
};
resolvedConfig = await prettierInstance.resolveConfig(
fileName,
resolveConfigOptions,
);
}
} catch (error) {
this.loggingService.logError(INVALID_PRETTIER_CONFIG, error);
return "error";
}
// Log what configuration was resolved
if (resolvedConfig) {
this.loggingService.logInfo("Resolved config:", resolvedConfig);
}
// Determine config source for better user feedback
if (!configPath && resolvedConfig && vscodeConfig.useEditorConfig) {
// Config was resolved but no Prettier config file was found
// This means settings came from .editorconfig
this.loggingService.logInfo(
"No Prettier config file found, but settings were loaded from .editorconfig",
);
} else if (!configPath && !resolvedConfig) {
this.loggingService.logInfo(
"No local configuration (i.e. .prettierrc or .editorconfig) detected, will fall back to VS Code configuration",
);
}
if (!vscodeConfig.requireConfig) {
return resolvedConfig;
}
if (resolvedConfig) {
return resolvedConfig;
}
if (!configPath) {
this.loggingService.logInfo(
"Require config set to true but no config file found, disabling formatting.",
);
return "disabled";
}
return resolvedConfig;
}
public dispose(): void {
this.path2Module.clear();
}
}