-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathstartServer.ts
More file actions
761 lines (673 loc) · 24.9 KB
/
startServer.ts
File metadata and controls
761 lines (673 loc) · 24.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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
import {
AugmentedThemeDocset,
DocDefinition,
FileTuple,
findRoot as findConfigFileRoot,
isError,
makeFileExists,
makeGetDefaultLocaleFileUri,
makeGetDefaultSchemaLocaleFileUri,
makeGetDefaultSchemaTranslations,
makeGetDefaultTranslations,
makeGetMetafieldDefinitions,
memoize,
MetafieldDefinitionMap,
parseJSON,
path,
recursiveReadDirectory,
SourceCodeType,
UriString,
} from '@shopify/theme-check-common';
import {
Connection,
FileChangeType,
FileOperationRegistrationOptions,
InitializeResult,
ShowDocumentRequest,
TextDocumentSyncKind,
WorkspaceFolder,
} from 'vscode-languageserver';
import { ClientCapabilities } from '../ClientCapabilities';
import { CodeActionKinds, CodeActionsProvider } from '../codeActions';
import { Commands, ExecuteCommandProvider } from '../commands';
import { CompletionsProvider } from '../completions';
import { GetSnippetNamesForURI } from '../completions/providers/RenderSnippetCompletionProvider';
import { CSSLanguageService } from '../css/CSSLanguageService';
import { DefinitionProvider } from '../definitions/DefinitionProvider';
import { DiagnosticsManager, makeRunChecks } from '../diagnostics';
import { DocumentHighlightsProvider } from '../documentHighlights/DocumentHighlightsProvider';
import { DocumentLinksProvider } from '../documentLinks';
import { AugmentedJsonSourceCode, DocumentManager } from '../documents';
import { OnTypeFormattingProvider } from '../formatting';
import { HoverProvider } from '../hover';
import { JSONLanguageService } from '../json/JSONLanguageService';
import { LinkedEditingRangesProvider } from '../linkedEditingRanges/LinkedEditingRangesProvider';
import { RenameProvider } from '../rename/RenameProvider';
import { RenameHandler } from '../renamed/RenameHandler';
import { GetTranslationsForURI } from '../translations';
import {
Dependencies,
ThemeGraphDeadCodeRequest,
ThemeGraphDependenciesRequest,
ThemeGraphReferenceRequest,
ThemeGraphRootRequest,
} from '../types';
import { debounce } from '../utils';
import { snippetName } from '../utils/uri';
import { VERSION } from '../version';
import { CachedFileSystem } from './CachedFileSystem';
import { Configuration } from './Configuration';
import { safe } from './safe';
import { ThemeGraphManager } from './ThemeGraphManager';
const defaultLogger = () => {};
/**
* The `git:` VFS does not support the `fs.readDirectory` call and makes most things break.
* `git` URIs are the ones you'd encounter when doing a git diff in VS Code. They're not
* real files, they're just a way to represent changes in a git repository. As such, I don't
* think we want to sync those in our document manager or try to offer document links, etc.
*
* A middleware would be nice but it'd be a bit of a pain to implement.
*/
const hasUnsupportedDocument = (params: any) => {
return (
'textDocument' in params &&
'uri' in params.textDocument &&
typeof params.textDocument.uri === 'string' &&
(params.textDocument.uri.startsWith('git:') || params.textDocument.uri.startsWith('output:'))
);
};
/**
* This code runs in node and the browser, it can't talk to the file system
* or make requests. Stuff like that should be injected.
*
* In browser, theme-check-js wants these things:
* - fileExists(path)
* - defaultTranslations
*
* Which means we gotta provide 'em from here too!
*/
export function startServer(
connection: Connection,
{
fs: injectedFs,
loadConfig: injectedLoadConfig,
log = defaultLogger,
jsonValidationSet,
themeDocset: remoteThemeDocset,
fetchMetafieldDefinitionsForURI,
augmentDocset = true,
}: Dependencies,
) {
const fs = new CachedFileSystem(injectedFs);
const fileExists = makeFileExists(fs);
const loadConfig = memoize(injectedLoadConfig, (uri: string) => uri);
const clientCapabilities = new ClientCapabilities();
const configuration = new Configuration(connection, clientCapabilities);
const documentManager: DocumentManager = new DocumentManager(
fs,
connection,
clientCapabilities,
getModeForURI,
isValidSchema,
);
const themeGraphManager = new ThemeGraphManager(
connection,
documentManager,
fs,
findThemeRootURI,
);
const diagnosticsManager = new DiagnosticsManager(connection);
const documentLinksProvider = new DocumentLinksProvider(documentManager, findThemeRootURI);
const codeActionsProvider = new CodeActionsProvider(documentManager, diagnosticsManager);
const onTypeFormattingProvider = new OnTypeFormattingProvider(
documentManager,
async function setCursorPosition(textDocument, position) {
if (!clientCapabilities.hasShowDocumentSupport) return;
connection.sendRequest(ShowDocumentRequest.type, {
uri: textDocument.uri,
takeFocus: true,
selection: {
start: position,
end: position,
},
});
},
);
const linkedEditingRangesProvider = new LinkedEditingRangesProvider(documentManager);
const documentHighlightProvider = new DocumentHighlightsProvider(documentManager);
const renameProvider = new RenameProvider(
connection,
clientCapabilities,
documentManager,
findThemeRootURI,
);
const renameHandler = new RenameHandler(
connection,
clientCapabilities,
documentManager,
findThemeRootURI,
);
async function findThemeRootURI(uri: string): Promise<string | null> {
const rootUri = await findConfigFileRoot(uri, fileExists);
if (!rootUri) return null;
const config = await loadConfig(rootUri, fs);
return config.rootUri;
}
const getMetafieldDefinitionsForRootUri = memoize(
makeGetMetafieldDefinitions(fs),
(rootUri) => rootUri,
);
const getMetafieldDefinitions: NonNullable<Dependencies['getMetafieldDefinitions']> = async (
uri: string,
) => {
const rootUri = await findThemeRootURI(uri);
if (!rootUri) {
return {} as MetafieldDefinitionMap;
}
return getMetafieldDefinitionsForRootUri(rootUri);
};
// These are augmented here so that the caching is maintained over different runs.
// Allow consumers to disable augmentation for vanilla liquid LSP
const themeDocset =
augmentDocset ? new AugmentedThemeDocset(remoteThemeDocset) : remoteThemeDocset;
const cssLanguageService = new CSSLanguageService(documentManager);
const runChecks = debounce(
makeRunChecks(documentManager, diagnosticsManager, {
fs,
loadConfig,
themeDocset,
jsonValidationSet,
getMetafieldDefinitions,
cssLanguageService,
themeGraphManager,
}),
100,
);
const getTranslationsForURI: GetTranslationsForURI = async (uri) => {
const rootURI = await findThemeRootURI(uri);
if (!rootURI) return {};
const theme = documentManager.theme(rootURI);
const getDefaultTranslations = makeGetDefaultTranslations(fs, theme, rootURI);
const [defaultTranslations, shopifyTranslations] = await Promise.all([
getDefaultTranslations(),
themeDocset.systemTranslations(),
]);
return { ...shopifyTranslations, ...defaultTranslations };
};
const getSchemaTranslationsForURI: GetTranslationsForURI = async (uri) => {
const rootURI = await findThemeRootURI(uri);
if (!rootURI) return {};
const theme = documentManager.theme(rootURI);
const getDefaultSchemaTranslations = makeGetDefaultSchemaTranslations(fs, theme, rootURI);
return getDefaultSchemaTranslations();
};
const getDocDefinitionForURI = async (
uri: UriString,
category: 'snippets' | 'blocks',
name: string,
): Promise<DocDefinition | undefined> => {
const rootUri = await findThemeRootURI(uri);
if (!rootUri) return undefined;
const fileUri = path.join(rootUri, category, `${name}.liquid`);
const file = documentManager.get(fileUri);
if (!file || file.type !== SourceCodeType.LiquidHtml || isError(file.ast)) {
return undefined;
}
return file.getLiquidDoc();
};
const snippetFilter = ([uri]: FileTuple) => /\.liquid$/.test(uri) && /snippets/.test(uri);
const getSnippetNamesForURI: GetSnippetNamesForURI = safe(async (uri: string) => {
const rootUri = await findThemeRootURI(uri);
if (!rootUri) return [];
const snippetUris = await recursiveReadDirectory(fs, rootUri, snippetFilter);
return snippetUris.map(snippetName);
}, []);
const getThemeSettingsSchemaForURI = safe(async (uri: string) => {
const rootUri = await findThemeRootURI(uri);
if (!rootUri) return [];
const settingsSchemaUri = path.join(rootUri, 'config', 'settings_schema.json');
const contents = await fs.readFile(settingsSchemaUri);
const json = parseJSON(contents);
if (isError(json) || !Array.isArray(json)) {
throw new Error('Settings JSON file not in correct format');
}
return json;
}, []);
async function getModeForURI(uri: string) {
const rootUri = await findConfigFileRoot(uri, fileExists);
if (!rootUri) return 'theme';
const config = await loadConfig(rootUri, fs);
return config.context;
}
const getThemeBlockNames = safe(async (uri: string, includePrivate: boolean) => {
const rootUri = await findThemeRootURI(uri);
if (!rootUri) return [];
const blocks = await fs.readDirectory(path.join(rootUri, 'blocks'));
const blockNames = blocks.map(([uri]) => path.basename(uri, '.liquid'));
if (includePrivate) {
return blockNames;
}
return blockNames.filter((blockName) => !blockName.startsWith('_'));
}, []);
async function getThemeBlockSchema(uri: string, name: string) {
const rootUri = await findThemeRootURI(uri);
if (!rootUri) return;
const blockUri = path.join(rootUri, 'blocks', `${name}.liquid`);
const doc = documentManager.get(blockUri);
if (!doc || doc.type !== SourceCodeType.LiquidHtml) {
return;
}
return doc.getSchema();
}
// Defined as a function to solve a circular dependency (doc manager & json
// lang service both need each other)
async function isValidSchema(uri: string, jsonString: string) {
return jsonLanguageService.isValidSchema(uri, jsonString);
}
const getDefaultLocaleFileUri = makeGetDefaultLocaleFileUri(fs);
async function getDefaultLocaleSourceCode(uri: string) {
const rootUri = await findThemeRootURI(uri);
if (!rootUri) return null;
const defaultLocaleFileUri = await getDefaultLocaleFileUri(rootUri);
if (!defaultLocaleFileUri) return null;
return (documentManager.get(defaultLocaleFileUri) as AugmentedJsonSourceCode) ?? null;
}
const getDefaultSchemaLocaleFileUri = makeGetDefaultSchemaLocaleFileUri(fs);
async function getDefaultSchemaLocaleSourceCode(uri: string) {
const rootUri = await findThemeRootURI(uri);
if (!rootUri) return null;
const defaultLocaleFileUri = await getDefaultSchemaLocaleFileUri(rootUri);
if (!defaultLocaleFileUri) return null;
return (documentManager.get(defaultLocaleFileUri) as AugmentedJsonSourceCode) ?? null;
}
const definitionsProvider = new DefinitionProvider(
documentManager,
getDefaultLocaleSourceCode,
getDefaultSchemaLocaleSourceCode,
);
const jsonLanguageService = new JSONLanguageService(
documentManager,
jsonValidationSet,
getSchemaTranslationsForURI,
getModeForURI,
getThemeBlockNames,
getThemeBlockSchema,
findThemeRootURI,
);
const completionsProvider = new CompletionsProvider({
documentManager,
themeDocset,
getTranslationsForURI,
getSnippetNamesForURI,
getThemeSettingsSchemaForURI,
log,
getThemeBlockNames,
getMetafieldDefinitions,
getDocDefinitionForURI,
});
const hoverProvider = new HoverProvider(
documentManager,
themeDocset,
getMetafieldDefinitions,
getTranslationsForURI,
getThemeSettingsSchemaForURI,
getDocDefinitionForURI,
);
const executeCommandProvider = new ExecuteCommandProvider(
documentManager,
diagnosticsManager,
clientCapabilities,
runChecks,
connection,
);
const fetchMetafieldDefinitionsForWorkspaceFolders = async (folders: WorkspaceFolder[]) => {
if (!fetchMetafieldDefinitionsForURI) return;
for (let folder of folders) {
const mode = await getModeForURI(folder.uri);
if (mode === 'theme') {
fetchMetafieldDefinitionsForURI(folder.uri);
}
}
};
connection.onInitialize((params) => {
clientCapabilities.setup(params.capabilities, params.initializationOptions);
cssLanguageService.setup(params.capabilities);
jsonLanguageService.setup(params.capabilities);
configuration.setup();
const fileOperationRegistrationOptions: FileOperationRegistrationOptions = {
filters: [
{
pattern: {
glob: '**/*.{liquid,json}',
},
},
{
pattern: {
glob: '**/assets/*',
},
},
],
};
const result: InitializeResult = {
capabilities: {
textDocumentSync: {
change: TextDocumentSyncKind.Full,
save: true,
openClose: true,
},
codeActionProvider: {
codeActionKinds: [...CodeActionKinds],
},
completionProvider: {
triggerCharacters: ['.', '{{ ', '{% ', '<', '/', '[', '"', "'", ':', '@'],
},
definitionProvider: true,
documentOnTypeFormattingProvider: {
firstTriggerCharacter: ' ',
moreTriggerCharacter: ['{', '%', '-', '>'],
},
documentLinkProvider: {
resolveProvider: false,
workDoneProgress: false,
},
documentHighlightProvider: true,
linkedEditingRangeProvider: true,
renameProvider: {
prepareProvider: true,
},
executeCommandProvider: {
commands: [...Commands],
},
hoverProvider: {
workDoneProgress: false,
},
workspace: {
workspaceFolders: {
supported: true,
changeNotifications: true,
},
fileOperations: {
didRename: fileOperationRegistrationOptions,
},
},
},
serverInfo: {
name: 'theme-language-server',
version: VERSION,
},
};
return result;
});
connection.onInitialized(() => {
log(`[SERVER] Let's roll!`);
configuration.fetchConfiguration();
configuration.registerDidChangeCapability();
configuration.registerDidChangeWatchedFilesNotification({
watchers: [
{
globPattern: '**/.theme-check.yml',
},
{
globPattern: '**/.shopify/*',
},
{
globPattern: '**/*.liquid',
},
{
globPattern: '**/{locales,sections,templates,customers}/*.json',
},
{
globPattern: '**/config/settings_{data,schema}.json',
},
],
});
if (clientCapabilities.hasWorkspaceFoldersSupport) {
connection.workspace.getWorkspaceFolders().then(async (folders) => {
if (!folders) return;
fetchMetafieldDefinitionsForWorkspaceFolders(folders);
});
connection.workspace.onDidChangeWorkspaceFolders(async (params) => {
fetchMetafieldDefinitionsForWorkspaceFolders(params.added);
});
}
});
connection.onDidChangeConfiguration((_params) => {
configuration.clearCache();
});
connection.onDidOpenTextDocument(async (params) => {
if (hasUnsupportedDocument(params)) return;
const { uri, text, version } = params.textDocument;
documentManager.open(uri, text, version);
if (await configuration.shouldCheckOnOpen()) {
runChecks([uri]);
}
// The objective at the time of writing this is to make {Asset,Snippet}Rename
// fast when you eventually need it.
//
// I'm choosing the textDocument/didOpen notification as a hook because
// I'm not sure we have a better solution than this. Yes we have the
// initialize request with the workspace folders, but you might have opened
// an app folder. The root of a theme app extension would probably be
// at ${workspaceRoot}/extensions/${appExtensionName}. It'd be hard to
// figure out from the initialize request params.
//
// If we open a file that we know is liquid, then we can kind of guarantee
// we'll find a theme root and we'll preload that.
if (await configuration.shouldPreloadOnBoot()) {
const rootUri = await findThemeRootURI(uri);
if (rootUri) {
documentManager.preload(rootUri);
}
}
});
connection.onDidChangeTextDocument(async (params) => {
if (hasUnsupportedDocument(params)) return;
const { uri, version } = params.textDocument;
documentManager.change(uri, params.contentChanges[0].text, version);
if (await configuration.shouldCheckOnChange()) {
runChecks([uri]);
} else {
// The diagnostics may be stale! Clear em!
diagnosticsManager.clear(params.textDocument.uri);
}
});
connection.onDidSaveTextDocument(async (params) => {
if (hasUnsupportedDocument(params)) return;
const { uri } = params.textDocument;
if (await configuration.shouldCheckOnSave()) {
runChecks([uri]);
}
});
connection.onDidCloseTextDocument((params) => {
if (hasUnsupportedDocument(params)) return;
const { uri } = params.textDocument;
documentManager.close(uri);
diagnosticsManager.clear(uri);
});
connection.onDocumentLinks(async (params) => {
if (hasUnsupportedDocument(params)) return [];
const [liquidLinks, jsonLinks] = await Promise.all([
documentLinksProvider.documentLinks(params.textDocument.uri),
jsonLanguageService.documentLinks(params),
]);
return [...liquidLinks, ...jsonLinks];
});
connection.onDefinition(async (params) => {
if (hasUnsupportedDocument(params)) return [];
return definitionsProvider.definitions(params);
});
connection.onCodeAction(async (params) => {
return codeActionsProvider.codeActions(params);
});
connection.onExecuteCommand(async (params) => {
await executeCommandProvider.execute(params);
});
connection.onCompletion(async (params) => {
if (hasUnsupportedDocument(params)) return [];
return (
(await cssLanguageService.completions(params)) ??
(await jsonLanguageService.completions(params)) ??
(await completionsProvider.completions(params))
);
});
connection.onHover(async (params) => {
if (hasUnsupportedDocument(params)) return null;
return (
(await cssLanguageService.hover(params)) ??
(await jsonLanguageService.hover(params)) ??
(await hoverProvider.hover(params))
);
});
connection.onDocumentOnTypeFormatting(async (params) => {
if (hasUnsupportedDocument(params)) return null;
return onTypeFormattingProvider.onTypeFormatting(params);
});
connection.onDocumentHighlight(async (params) => {
if (hasUnsupportedDocument(params)) return [];
return documentHighlightProvider.documentHighlights(params);
});
connection.onPrepareRename(async (params) => {
if (hasUnsupportedDocument(params)) return null;
return renameProvider.prepare(params);
});
connection.onRenameRequest(async (params) => {
if (hasUnsupportedDocument(params)) return null;
return renameProvider.rename(params);
});
connection.languages.onLinkedEditingRange(async (params) => {
if (hasUnsupportedDocument(params)) return null;
return linkedEditingRangesProvider.linkedEditingRanges(params);
});
connection.workspace.onDidRenameFiles(async (params) => {
const triggerUris = params.files.map((fileRename) => fileRename.newUri);
// Behold the cache invalidation monster
for (const { oldUri, newUri } of params.files) {
// When a file is renamed, we paste the content of the old file into the
// new file in the document manager. We don't need to invalidate preload
// because that's the only thing that changed.
documentManager.rename(oldUri, newUri);
// When a file is renamed, readDirectory to the parent folder is invalidated.
fs.readDirectory.invalidate(path.dirname(oldUri));
fs.readDirectory.invalidate(path.dirname(newUri));
// When a file is renamed, readFile and stat for both the old and new URIs are invalidated.
fs.readFile.invalidate(oldUri);
fs.readFile.invalidate(newUri);
fs.stat.invalidate(oldUri);
fs.stat.invalidate(newUri);
themeGraphManager.rename(oldUri, newUri);
}
// We should complete refactors before running theme check
await renameHandler.onDidRenameFiles(params);
// MissingAssets/MissingSnippet should be rerun when a file is deleted
// since the file rename might cause an error.
runChecks.force(triggerUris);
});
/**
* onDidChangeWatchedFiles is triggered by file operations (in or out of the editor).
*
* For in-editor changes, happens redundantly with
* - onDidCreateFiles
* - onDidRenameFiles
* - onDidDeleteFiles
* - onDidSaveTextDocument
*
* Not redundant for operations that happen outside of the editor
* - git pull, checkout, reset, stash pop, etc.
* - shopify theme metafields pull
* - etc.
*
* It always runs and onDid* will never fire without a corresponding onDidChangeWatchedFiles.
*
* This is why the bulk of the cache invalidation logic is in this handler.
*/
connection.onDidChangeWatchedFiles(async (params) => {
if (params.changes.length === 0) return;
const triggerUris = params.changes.map((change) => change.uri);
const updates: Promise<any>[] = [];
for (const change of params.changes) {
// Theme Check config changes should clear the config cache
if (change.uri.endsWith('.theme-check.yml')) {
loadConfig.clearCache();
continue;
}
// Rename cache invalidation is handled by onDidRenameFiles
if (documentManager.hasRecentRename(change.uri)) {
documentManager.clearRecentRename(change.uri);
continue;
}
switch (change.type) {
case FileChangeType.Created:
// A created file invalidates readDirectory, readFile and stat
fs.readDirectory.invalidate(path.dirname(change.uri));
fs.readFile.invalidate(change.uri);
fs.stat.invalidate(change.uri);
themeGraphManager.create(change.uri);
// If a file is created under out feet, we update its contents.
updates.push(documentManager.changeFromDisk(change.uri));
break;
case FileChangeType.Changed:
// A changed file invalidates readFile and stat (but not readDirectory)
fs.readFile.invalidate(change.uri);
fs.stat.invalidate(change.uri);
themeGraphManager.change(change.uri);
// If the file is not open, we update its contents in the doc manager
// If it is open, then we don't need to update it because the document manager
// will have the version from the editor.
if (documentManager.get(change.uri)?.version === undefined) {
updates.push(documentManager.changeFromDisk(change.uri));
}
break;
case FileChangeType.Deleted:
// A deleted file invalides readDirectory, readFile, and stat
fs.readDirectory.invalidate(path.dirname(change.uri));
fs.readFile.invalidate(change.uri);
fs.stat.invalidate(change.uri);
themeGraphManager.delete(change.uri);
// If a file is deleted, it's removed from the document manager
documentManager.delete(change.uri);
break;
}
if (change.uri.endsWith('metafields.json')) {
updates.push(
findThemeRootURI(change.uri).then((rootUri) => {
if (rootUri) {
getMetafieldDefinitionsForRootUri.invalidate(rootUri);
}
}),
);
}
}
await Promise.all(updates);
// MissingAssets/MissingSnippet should be rerun when a file is deleted
// since an error might be introduced (and vice versa).
runChecks.force(triggerUris);
});
connection.onRequest(ThemeGraphReferenceRequest.type, async (params) => {
if (hasUnsupportedDocument(params)) return [];
const { uri, offset, includeIndirect } = params;
return themeGraphManager.getReferences(uri, offset, { includeIndirect }).catch((_) => []);
});
connection.onRequest(ThemeGraphDependenciesRequest.type, async (params) => {
if (hasUnsupportedDocument(params)) return [];
const { uri, offset, includeIndirect } = params;
return themeGraphManager.getDependencies(uri, offset, { includeIndirect }).catch((_) => []);
});
connection.onRequest(ThemeGraphRootRequest.type, async (params) => {
if (hasUnsupportedDocument(params)) return '';
const { uri } = params;
const rootUri = await findThemeRootURI(uri).catch((_) => undefined);
if (!rootUri || path.dirname(rootUri) === rootUri) {
console.error(uri);
}
return rootUri;
});
connection.onRequest(ThemeGraphDeadCodeRequest.type, async (params) => {
if (hasUnsupportedDocument(params)) return [];
const { uri } = params;
const rootUri = await findThemeRootURI(uri);
if (!rootUri) return [];
const deadFiles = await themeGraphManager.deadCode(rootUri);
return deadFiles;
});
connection.listen();
}