forked from voidzero-dev/vite-plus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor.ts
More file actions
418 lines (386 loc) · 10.9 KB
/
editor.ts
File metadata and controls
418 lines (386 loc) · 10.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
import fs from 'node:fs';
import fsPromises from 'node:fs/promises';
import path from 'node:path';
import { styleText } from 'node:util';
import * as prompts from '@voidzero-dev/vite-plus-prompts';
import { readJsonFile, writeJsonFile } from './json.ts';
const VSCODE_SETTINGS = {
// Set as default over per-lang to avoid conflicts with other formatters
'editor.defaultFormatter': 'oxc.oxc-vscode',
'oxc.fmt.configPath': './vite.config.ts',
'editor.formatOnSave': true,
// Oxfmt does not support partial formatting
'editor.formatOnSaveMode': 'file',
'editor.codeActionsOnSave': {
'source.fixAll.oxc': 'explicit',
},
} as const;
const VSCODE_EXTENSIONS = {
recommendations: ['VoidZero.vite-plus-extension-pack'],
} as const;
const ZED_SETTINGS = {
lsp: {
oxlint: {
initialization_options: {
settings: {
run: 'onType',
fixKind: 'safe_fix',
typeAware: true,
unusedDisableDirectives: 'deny',
},
},
},
oxfmt: {
initialization_options: {
settings: {
configPath: './vite.config.ts',
run: 'onSave',
},
},
},
},
languages: {
CSS: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
GraphQL: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
Handlebars: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
HTML: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
JavaScript: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
code_action: 'source.fixAll.oxc',
},
JSX: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
JSON: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
JSON5: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
JSONC: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
Less: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
Markdown: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
MDX: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
SCSS: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
TypeScript: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
TSX: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
'Vue.js': {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
YAML: {
format_on_save: 'on',
prettier: { allowed: false },
formatter: [{ language_server: { name: 'oxfmt' } }],
},
},
} as const;
export const EDITORS = [
{
id: 'vscode',
label: 'VSCode',
targetDir: '.vscode',
files: {
'settings.json': VSCODE_SETTINGS as Record<string, unknown>,
'extensions.json': VSCODE_EXTENSIONS as Record<string, unknown>,
},
},
{
id: 'zed',
label: 'Zed',
targetDir: '.zed',
files: {
'settings.json': ZED_SETTINGS as Record<string, unknown>,
},
},
] as const;
export type EditorId = (typeof EDITORS)[number]['id'];
export async function selectEditor({
interactive,
editor,
onCancel,
}: {
interactive: boolean;
editor?: string | false;
onCancel: () => void;
}): Promise<EditorId | undefined> {
// Skip entirely if --no-editor is passed
if (editor === false) {
return undefined;
}
if (interactive && !editor) {
const editorOptions = EDITORS.map((option) => ({
label: option.label,
value: option.id,
hint: option.targetDir,
}));
const otherOption = {
label: 'Other',
value: null,
hint: 'Skip writing editor configs',
};
const selectedEditor = await prompts.select({
message:
'Which editor are you using?\n ' +
styleText(
'gray',
'Writes editor config files to enable recommended extensions and Oxlint/Oxfmt integrations.',
),
options: [...editorOptions, otherOption],
initialValue: 'vscode',
});
if (prompts.isCancel(selectedEditor)) {
onCancel();
return undefined;
}
if (selectedEditor === null) {
return undefined;
}
return resolveEditorId(selectedEditor);
}
if (editor) {
return resolveEditorId(editor);
}
return undefined;
}
export function detectExistingEditor(projectRoot: string): EditorId | undefined {
for (const option of EDITORS) {
for (const fileName of Object.keys(option.files)) {
const filePath = path.join(projectRoot, option.targetDir, fileName);
if (fs.existsSync(filePath)) {
return option.id;
}
}
}
return undefined;
}
export interface EditorConflictInfo {
fileName: string;
displayPath: string;
}
/**
* Detect editor config files that would conflict (already exist).
* Read-only — does not write or modify any files.
*/
export function detectEditorConflicts({
projectRoot,
editorId,
}: {
projectRoot: string;
editorId: EditorId | undefined;
}): EditorConflictInfo[] {
if (!editorId) {
return [];
}
const editorConfig = EDITORS.find((e) => e.id === editorId);
if (!editorConfig) {
return [];
}
const conflicts: EditorConflictInfo[] = [];
for (const fileName of Object.keys(editorConfig.files)) {
const filePath = path.join(projectRoot, editorConfig.targetDir, fileName);
if (fs.existsSync(filePath)) {
conflicts.push({
fileName,
displayPath: `${editorConfig.targetDir}/${fileName}`,
});
}
}
return conflicts;
}
export async function writeEditorConfigs({
projectRoot,
editorId,
interactive,
conflictDecisions,
silent = false,
additionalSettings,
}: {
projectRoot: string;
editorId: EditorId | undefined;
interactive: boolean;
conflictDecisions?: Map<string, 'merge' | 'skip'>;
silent?: boolean;
additionalSettings?: Record<string, unknown>;
}) {
if (!editorId) {
return;
}
const editorConfig = EDITORS.find((e) => e.id === editorId);
if (!editorConfig) {
return;
}
const targetDir = path.join(projectRoot, editorConfig.targetDir);
await fsPromises.mkdir(targetDir, { recursive: true });
for (const [fileName, baseIncoming] of Object.entries(editorConfig.files)) {
const incoming =
fileName === 'settings.json' && additionalSettings
? { ...baseIncoming, ...additionalSettings }
: baseIncoming;
const filePath = path.join(targetDir, fileName);
if (fs.existsSync(filePath)) {
const displayPath = `${editorConfig.targetDir}/${fileName}`;
// Determine conflict action from pre-resolved decisions, interactive prompt, or default
let conflictAction: 'merge' | 'skip';
const preResolved = conflictDecisions?.get(fileName);
if (preResolved) {
conflictAction = preResolved;
} else if (interactive) {
const action = await prompts.select({
message:
`${displayPath} already exists.\n ` +
styleText(
'gray',
`Vite+ adds ${editorConfig.label} settings for the built-in linter and formatter. Merge adds new keys without overwriting existing ones.`,
),
options: [
{
label: 'Merge',
value: 'merge',
hint: 'Merge new settings into existing file',
},
{
label: 'Skip',
value: 'skip',
hint: 'Leave existing file unchanged',
},
],
initialValue: 'skip',
});
conflictAction = prompts.isCancel(action) || action === 'skip' ? 'skip' : 'merge';
} else {
// Non-interactive: always merge (safe because existing keys are never overwritten)
conflictAction = 'merge';
}
if (conflictAction === 'merge') {
mergeAndWriteEditorConfig(filePath, incoming, fileName, displayPath, silent);
} else {
if (!silent) {
prompts.log.info(`Skipped writing ${displayPath}`);
}
}
continue;
}
writeJsonFile(filePath, incoming);
if (!silent) {
prompts.log.success(`Wrote editor config to ${editorConfig.targetDir}/${fileName}`);
}
}
}
function mergeAndWriteEditorConfig(
filePath: string,
incoming: Record<string, unknown>,
fileName: string,
displayPath: string,
silent = false,
) {
const existing = readJsonFile(filePath, true);
const merged = mergeEditorConfigs(existing, incoming, fileName);
writeJsonFile(filePath, merged);
if (!silent) {
prompts.log.success(`Merged editor config into ${displayPath}`);
}
}
function mergeEditorConfigs(
existing: Record<string, unknown>,
incoming: Record<string, unknown>,
fileName: string,
): Record<string, unknown> {
if (fileName === 'extensions.json') {
const existingRecs = Array.isArray(existing['recommendations'])
? (existing['recommendations'] as string[])
: [];
const incomingRecs = Array.isArray(incoming['recommendations'])
? (incoming['recommendations'] as string[])
: [];
return {
...existing,
recommendations: [...new Set([...existingRecs, ...incomingRecs])],
};
}
return deepMerge(existing, incoming);
}
function deepMerge(
target: Record<string, unknown>,
source: Record<string, unknown>,
): Record<string, unknown> {
const result = { ...target };
for (const [key, value] of Object.entries(source)) {
if (!(key in result)) {
result[key] = value;
} else if (
typeof result[key] === 'object' &&
result[key] !== null &&
!Array.isArray(result[key]) &&
typeof value === 'object' &&
value !== null &&
!Array.isArray(value)
) {
result[key] = deepMerge(
result[key] as Record<string, unknown>,
value as Record<string, unknown>,
);
}
}
return result;
}
function resolveEditorId(editor: string): EditorId | undefined {
const normalized = editor.trim().toLowerCase();
const match = EDITORS.find(
(option) => option.id === normalized || option.label.toLowerCase() === normalized,
);
return match?.id;
}