forked from containers/podman-desktop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension-loader.ts
1350 lines (1208 loc) · 51.9 KB
/
extension-loader.ts
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
* Copyright (C) 2022-2023 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/
import type * as containerDesktopAPI from '@podman-desktop/api';
import * as path from 'path';
import * as fs from 'fs';
import type { CommandRegistry } from './command-registry.js';
import type { ExtensionError, ExtensionInfo, ExtensionUpdateInfo } from './api/extension-info.js';
import AdmZip from 'adm-zip';
import type { TrayMenuRegistry } from './tray-menu-registry.js';
import { Disposable } from './types/disposable.js';
import type { ProviderRegistry } from './provider-registry.js';
import type { ConfigurationRegistry, IConfigurationNode } from './configuration-registry.js';
import type { ImageRegistry } from './image-registry.js';
import type { MessageBox } from './message-box.js';
import type { ProgressImpl } from './progress-impl.js';
import { ProgressLocation } from './progress-impl.js';
import {
StatusBarItemImpl,
StatusBarAlignLeft,
StatusBarAlignRight,
StatusBarItemDefaultPriority,
} from './statusbar/statusbar-item.js';
import type { StatusBarRegistry } from './statusbar/statusbar-registry.js';
import type { FilesystemMonitoring } from './filesystem-monitoring.js';
import { Uri } from './types/uri.js';
import type { KubernetesClient } from './kubernetes-client.js';
import type { Proxy } from './proxy.js';
import type { ContainerProviderRegistry } from './container-registry.js';
import type { InputQuickPickRegistry } from './input-quickpick/input-quickpick-registry.js';
import { QuickPickItemKind, InputBoxValidationSeverity } from './input-quickpick/input-quickpick-registry.js';
import type { MenuRegistry } from '/@/plugin/menu-registry.js';
import { Emitter } from './events/emitter.js';
import { CancellationTokenSource } from './cancellation-token.js';
import type { ApiSenderType } from './api.js';
import type { AuthenticationImpl } from './authentication.js';
import type { Telemetry } from './telemetry/telemetry.js';
import { TelemetryTrustedValue } from './types/telemetry.js';
import { clipboard as electronClipboard } from 'electron';
import { securityRestrictionCurrentHandler } from '../security-restrictions-handler.js';
import type { IconRegistry } from './icon-registry.js';
import type { Directories } from './directories.js';
import { getBase64Image, isLinux, isMac, isWindows } from '../util.js';
import type { CustomPickRegistry } from './custompick/custompick-registry.js';
import type { Exec } from './util/exec.js';
import type { ProviderContainerConnectionInfo, ProviderKubernetesConnectionInfo } from './api/provider-info.js';
import type { ViewRegistry } from './view-registry.js';
import type { Context } from './context/context.js';
import type { OnboardingRegistry } from './onboarding-registry.js';
import { createHttpPatchedModules } from './proxy-resolver.js';
import { ModuleLoader } from './module-loader.js';
import { ExtensionLoaderSettings } from './extension-loader-settings.js';
import type { KubeGeneratorRegistry, KubernetesGeneratorProvider } from '/@/plugin/kube-generator-registry.js';
import type { CliToolRegistry } from './cli-tool-registry.js';
import type { NotificationRegistry } from './notification-registry.js';
import type { ImageCheckerImpl } from './image-checker.js';
/**
* Handle the loading of an extension
*/
export interface AnalyzedExtension {
id: string;
name: string;
// root folder (where is package.json)
path: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
manifest: any;
// main entry
mainPath?: string;
api: typeof containerDesktopAPI;
removable: boolean;
update?: {
version: string;
ociUri: string;
};
missingDependencies?: string[];
circularDependencies?: string[];
error?: string;
readonly subscriptions: { dispose(): unknown }[];
dispose(): void;
}
export interface ActivatedExtension {
id: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
deactivateFunction: any;
extensionContext: containerDesktopAPI.ExtensionContext;
}
const EXTENSION_OPTION = '--extension-folder';
export class ExtensionLoader {
private overrideRequireDone = false;
private moduleLoader: ModuleLoader;
protected activatedExtensions = new Map<string, ActivatedExtension>();
protected analyzedExtensions = new Map<string, AnalyzedExtension>();
private watcherExtensions = new Map<string, containerDesktopAPI.FileSystemWatcher>();
private reloadInProgressExtensions = new Map<string, boolean>();
protected extensionState = new Map<string, string>();
protected extensionStateErrors = new Map<string, unknown>();
protected watchTimeout = 1000;
// Plugins directory location
private pluginsDirectory;
protected pluginsScanDirectory;
// Extensions directory location
private extensionsStorageDirectory;
constructor(
private commandRegistry: CommandRegistry,
private menuRegistry: MenuRegistry,
private providerRegistry: ProviderRegistry,
private configurationRegistry: ConfigurationRegistry,
private imageRegistry: ImageRegistry,
private apiSender: ApiSenderType,
private trayMenuRegistry: TrayMenuRegistry,
private messageBox: MessageBox,
private progress: ProgressImpl,
private statusBarRegistry: StatusBarRegistry,
private kubernetesClient: KubernetesClient,
private fileSystemMonitoring: FilesystemMonitoring,
private proxy: Proxy,
private containerProviderRegistry: ContainerProviderRegistry,
private inputQuickPickRegistry: InputQuickPickRegistry,
private customPickRegistry: CustomPickRegistry,
private authenticationProviderRegistry: AuthenticationImpl,
private iconRegistry: IconRegistry,
private onboardingRegistry: OnboardingRegistry,
private telemetry: Telemetry,
private viewRegistry: ViewRegistry,
private context: Context,
directories: Directories,
private exec: Exec,
private kubeGeneratorRegistry: KubeGeneratorRegistry,
private cliToolRegistry: CliToolRegistry,
private notificationRegistry: NotificationRegistry,
private imageCheckerProvider: ImageCheckerImpl,
) {
this.pluginsDirectory = directories.getPluginsDirectory();
this.pluginsScanDirectory = directories.getPluginsScanDirectory();
this.extensionsStorageDirectory = directories.getExtensionsStorageDirectory();
this.moduleLoader = new ModuleLoader(require('module'), this.analyzedExtensions);
}
mapError(err: unknown): ExtensionError | undefined {
if (err) {
if (err instanceof Error) {
return { message: err.message, stack: err.stack };
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return { message: (err as any).toString() };
}
}
return undefined;
}
async listExtensions(): Promise<ExtensionInfo[]> {
return Array.from(this.analyzedExtensions.values()).map(extension => ({
name: extension.manifest.name,
displayName: extension.manifest.displayName,
description: extension.manifest.description,
version: extension.manifest.version,
publisher: extension.manifest.publisher,
state: this.extensionState.get(extension.id) || 'stopped',
error: this.mapError(this.extensionStateErrors.get(extension.id)),
id: extension.id,
path: extension.path,
removable: extension.removable,
update: extension.update,
icon: extension.manifest.icon ? this.updateImage(extension.manifest.icon, extension.path) : undefined,
}));
}
async loadPackagedFile(filePath: string): Promise<void> {
// need to unpack the file before load it
const filename = path.basename(filePath);
const dirname = path.dirname(filePath);
const unpackedDirectory = path.resolve(dirname, `../unpacked/${filename}`);
fs.mkdirSync(unpackedDirectory, { recursive: true });
// extract to an existing directory
const admZip = new AdmZip(filePath);
admZip.extractAllTo(unpackedDirectory, true);
const extension = await this.analyzeExtension(unpackedDirectory, true);
if (!extension.error) {
await this.loadExtension(extension);
this.apiSender.send('extension-started', {});
}
}
async init(): Promise<void> {
// create pluginsDirectory if it does not exist
if (!fs.existsSync(this.pluginsDirectory)) {
fs.mkdirSync(this.pluginsDirectory, { recursive: true });
}
if (!fs.existsSync(this.pluginsScanDirectory)) {
fs.mkdirSync(this.pluginsScanDirectory, { recursive: true });
}
this.moduleLoader.addOverride(createHttpPatchedModules(this.proxy)); // add patched http and https
this.moduleLoader.addOverride({ '@podman-desktop/api': ext => ext.api }); // add podman desktop API
this.moduleLoader.overrideRequire();
// register configuration for the max activation time
const maxActivationTimeConfiguration: IConfigurationNode = {
id: 'preferences.extension',
title: 'Extensions',
type: 'object',
properties: {
[ExtensionLoaderSettings.SectionName + '.' + ExtensionLoaderSettings.MaxActivationTime]: {
description: 'Maximum activation time for an extension, in seconds.',
type: 'number',
default: 10,
minimum: 1,
maximum: 100,
},
},
};
this.configurationRegistry.registerConfigurations([maxActivationTimeConfiguration]);
}
protected async setupScanningDirectory(): Promise<void> {
if (fs.existsSync(this.pluginsScanDirectory)) {
// add watcher
fs.watch(this.pluginsScanDirectory, (_, filename) => {
// need to load the file
if (filename) {
const packagedFile = path.resolve(this.pluginsScanDirectory, filename);
setTimeout(() => {
this.loadPackagedFile(packagedFile).catch((error: unknown) => {
console.error('Error while loadPackagedFile', error);
});
}, this.watchTimeout);
}
});
// scan all files in the directory
const entries = await fs.promises.readdir(this.pluginsScanDirectory, { withFileTypes: true });
// filter only files
const files = entries
.filter(entry => entry.isFile())
.filter(entry => entry.name.endsWith('.cdix'))
.map(file => path.join(this.pluginsScanDirectory, file.name));
// load all files
await Promise.all(files.map(file => this.loadPackagedFile(file)));
}
}
async start() {
// Scan the plugins-scanning directory
await this.setupScanningDirectory();
// Create the extensions storage directory if it does not exist
if (!fs.existsSync(this.extensionsStorageDirectory)) {
fs.mkdirSync(this.extensionsStorageDirectory);
}
let folders;
// scan all extensions that we can find from the extensions folder
if (import.meta.env.PROD) {
// in production mode, use the extensions locally
folders = await this.readProductionFolders(path.join(__dirname, '../../../extensions'));
} else {
// in development mode, use the extensions locally
folders = await this.readDevelopmentFolders(path.join(__dirname, '../../../extensions'));
}
const externalExtensions = await this.readExternalFolders();
// ok now load grab all extensions from these folders
const analyzedExtensions: AnalyzedExtension[] = [];
const analyzedFoldersExtension = (
await Promise.all(folders.map(folder => this.analyzeExtension(folder, false)))
).filter(extension => !extension.error);
analyzedExtensions.push(...analyzedFoldersExtension);
const analyzedExternalExtensions = (
await Promise.all(externalExtensions.map(folder => this.analyzeExtension(folder, false)))
).filter(extension => !extension.error);
analyzedExtensions.push(...analyzedExternalExtensions);
// also load extensions from the plugins directory
if (fs.existsSync(this.pluginsDirectory)) {
const pluginDirEntries = await fs.promises.readdir(this.pluginsDirectory, { withFileTypes: true });
// filter only directories ignoring node_modules directory
const pluginDirectories = pluginDirEntries
.filter(entry => entry.isDirectory())
.map(directory => this.pluginsDirectory + '/' + directory.name);
// collect all extensions from the pluginDirectory folders
const analyzedPluginsDirectoryExtensions: AnalyzedExtension[] = (
await Promise.all(pluginDirectories.map(folder => this.analyzeExtension(folder, true)))
).filter(extension => !extension.error);
analyzedExtensions.push(...analyzedPluginsDirectoryExtensions);
}
// now we have all extensions, we can load them
await this.loadExtensions(analyzedExtensions);
}
async analyzeExtension(extensionPath: string, removable: boolean): Promise<AnalyzedExtension> {
// do nothing if there is no package.json file
let error = undefined;
if (!fs.existsSync(path.resolve(extensionPath, 'package.json'))) {
error = `Ignoring extension ${extensionPath} without package.json file`;
console.warn(error);
const analyzedExtension: AnalyzedExtension = {
id: '<unknown>',
name: '<unknown>',
path: extensionPath,
manifest: undefined,
api: <typeof containerDesktopAPI>{},
removable,
subscriptions: [],
dispose(): void {},
error,
};
return analyzedExtension;
}
// log error if the manifest is missing required entries
const manifest = await this.loadManifest(extensionPath);
if (!manifest.name || !manifest.displayName || !manifest.version || !manifest.publisher || !manifest.description) {
error = `Extension ${extensionPath} missing required manifest entry in package.json (name, displayName, version, publisher, description)`;
console.warn(error);
}
// create api object
const api = this.createApi(extensionPath, manifest);
const disposables: Disposable[] = [];
const analyzedExtension: AnalyzedExtension = {
id: `${manifest.publisher}.${manifest.name}`,
name: manifest.name,
manifest,
path: extensionPath,
mainPath: manifest.main ? path.resolve(extensionPath, manifest.main) : undefined,
api,
removable,
subscriptions: disposables,
dispose(): void {
disposables.forEach(disposable => disposable.dispose());
},
error,
};
return analyzedExtension;
}
// check if all dependencies are available
// if not, set the missingDependencies property
searchForMissingDependencies(analyzedExtensions: AnalyzedExtension[]): void {
analyzedExtensions.forEach(extension => {
const missingDependencies: string[] = [];
extension.manifest?.extensionDependencies?.forEach((dependency: string) => {
if (!analyzedExtensions.find(analyzedExtension => analyzedExtension.id === dependency)) {
missingDependencies.push(dependency);
}
});
extension.missingDependencies = missingDependencies;
});
}
async loadExtensions(analyzedExtensions: AnalyzedExtension[]): Promise<void> {
// check if all dependencies are available
this.searchForMissingDependencies(analyzedExtensions);
// do we have circular dependencies?
this.searchForCircularDependencies(analyzedExtensions);
// now, need to sort them by extensionDependencies order
const sortedExtensions = this.sortExtensionsByDependencies(analyzedExtensions);
// now, load all extensions
await Promise.all(sortedExtensions.map(extension => this.loadExtension(extension)));
}
// do we have circular dependencies?
// set it in the circularDependencies property
// search if a dependency is in the extensionDependencies of the other extension
searchForCircularDependencies(analyzedExtension: AnalyzedExtension[]): void {
analyzedExtension.forEach(extension => {
const circularDependencies: string[] = [];
extension.manifest?.extensionDependencies?.forEach((dependency: string) => {
if (
analyzedExtension
.find(analyzedExtension => analyzedExtension.id === dependency)
?.manifest?.extensionDependencies?.includes(extension.id)
) {
circularDependencies.push(dependency);
}
});
extension.circularDependencies = circularDependencies;
});
}
topologicalSort(
analyzedExtension: AnalyzedExtension,
allExtensions: AnalyzedExtension[],
explored: Map<string, boolean>,
sorted: AnalyzedExtension[],
) {
// flasg the node as explored
explored.set(analyzedExtension.id, true);
// visit all the unvisited nodes
analyzedExtension.manifest?.extensionDependencies?.forEach((dependency: string) => {
// not visited yet, grab the AnalyzedExtension object and visit it
if (!explored.has(dependency)) {
const matchingDependency = allExtensions.find(extension => extension.id === dependency);
if (matchingDependency) {
this.topologicalSort(matchingDependency, allExtensions, explored, sorted);
}
}
});
// add at the end of the sorted array
sorted.push(analyzedExtension);
}
// use topological sort to sort extensions by dependencies
sortExtensionsByDependencies(analyzedExtensions: AnalyzedExtension[]): AnalyzedExtension[] {
const sorted: AnalyzedExtension[] = [];
const explored = new Map<string, boolean>();
// visit all unvisited nodes
analyzedExtensions.forEach(node => {
if (!explored.has(node.id)) {
this.topologicalSort(node, analyzedExtensions, explored, sorted);
}
});
return sorted;
}
async readDevelopmentFolders(folderPath: string): Promise<string[]> {
const entries = await fs.promises.readdir(folderPath, { withFileTypes: true });
// filter only directories ignoring node_modules directory
return entries
.filter(entry => entry.isDirectory())
.filter(directory => directory.name !== 'node_modules')
.map(directory => path.join(folderPath, directory.name));
}
async readExternalFolders(): Promise<string[]> {
const pathes = [];
for (let index = 0; index < process.argv.length; index++) {
if (process.argv[index] === EXTENSION_OPTION && index < process.argv.length - 1) {
pathes.push(process.argv[++index]);
}
}
return pathes;
}
async readProductionFolders(folderPath: string): Promise<string[]> {
const entries = await fs.promises.readdir(folderPath, { withFileTypes: true });
return entries
.filter(entry => entry.isDirectory())
.filter(directory => directory.name !== 'node_modules')
.map(directory => path.join(folderPath, directory.name, `/builtin/${directory.name}.cdix`));
}
/**
* Update the image to be a base64 content
*/
updateImage(
image: undefined | string | { light: string; dark: string },
rootPath: string,
): undefined | string | { light: string; dark: string } {
// do nothing if no image
if (!image) {
return undefined;
}
if (typeof image === 'string') {
return getBase64Image(path.resolve(rootPath, image));
} else {
if (image.light) {
const base64Image = getBase64Image(path.resolve(rootPath, image.light));
if (base64Image) {
image.light = base64Image;
}
}
if (image.dark) {
const base64Image = getBase64Image(path.resolve(rootPath, image.dark));
if (base64Image) {
image.dark = base64Image;
}
}
return image;
}
}
protected async reloadExtension(extension: AnalyzedExtension, removable: boolean): Promise<void> {
const inProgress = this.reloadInProgressExtensions.get(extension.id);
if (inProgress) {
return;
}
console.log(`Extension ${extension.path} has been updated, reloading it`);
this.reloadInProgressExtensions.set(extension.id, true);
// unload the extension
await this.deactivateExtension(extension.id);
// reload the extension
try {
const updatedExtension = await this.analyzeExtension(extension.path, removable);
if (!updatedExtension.error) {
await this.loadExtension(updatedExtension, true);
}
} catch (error) {
console.error('error while reloading extension', error);
} finally {
this.reloadInProgressExtensions.set(extension.id, false);
}
}
async loadExtension(extension: AnalyzedExtension, checkForMissingDependencies = false): Promise<void> {
// check if all dependencies are available
if (checkForMissingDependencies && extension?.manifest?.extensionDependencies) {
// search from existing .this.analyzedExtensions
const missing: string[] = extension.manifest.extensionDependencies.filter(
(dependency: string) => !this.analyzedExtensions.get(dependency),
);
if (missing.length > 0) {
extension.missingDependencies = missing;
}
}
const extensionConfiguration = extension.manifest?.contributes?.configuration;
if (extensionConfiguration) {
// add information about the current extension
extensionConfiguration.extension = extension;
extensionConfiguration.title = `Extension: ${extensionConfiguration.title}`;
extensionConfiguration.id = 'preferences.' + extension.id;
extension.subscriptions.push(this.configurationRegistry.registerConfigurations([extensionConfiguration]));
}
const menus = extension.manifest?.contributes?.menus;
if (menus) {
extension.subscriptions.push(this.menuRegistry.registerMenus(menus));
}
const extensionCommands = extension.manifest?.contributes?.commands;
if (extensionCommands) {
const disposable = this.commandRegistry.registerCommandsFromExtension(extension.id, extensionCommands);
extension.subscriptions.push(disposable);
}
const icons = extension.manifest?.contributes?.icons;
if (icons) {
this.iconRegistry.registerIconContribution(extension, icons);
}
const views = extension.manifest?.contributes?.views;
if (views) {
extension.subscriptions.push(this.viewRegistry.registerViews(extension.id, views));
}
const onboarding = extension.manifest?.contributes?.onboarding;
if (onboarding) {
extension.subscriptions.push(this.onboardingRegistry.registerOnboarding(extension, onboarding));
}
extension.subscriptions.push(this.notificationRegistry.registerExtension(extension.id));
this.analyzedExtensions.set(extension.id, extension);
this.extensionState.delete(extension.id);
this.extensionStateErrors.delete(extension.id);
const telemetryOptions = { extensionId: extension.id };
if (extension.missingDependencies && extension.missingDependencies.length > 0) {
this.extensionState.set(extension.id, 'failed');
this.extensionStateErrors.set(
extension.id,
`Missing dependencies for this extension: ${extension?.missingDependencies.join(', ')}`,
);
return;
}
try {
// in development mode, watch if the extension is updated and reload it
if (import.meta.env.DEV && !this.watcherExtensions.has(extension.id)) {
const extensionWatcher = this.fileSystemMonitoring.createFileSystemWatcher(extension.path);
extensionWatcher.onDidChange(async () => {
// wait 1 second before trying to reload the extension
// this is to avoid reloading the extension while it is still being updated
setTimeout(() => {
this.reloadExtension(extension, extension.removable).catch((error: unknown) =>
console.error('error while reloading extension', error),
);
}, 1000);
});
this.watcherExtensions.set(extension.id, extensionWatcher);
}
const runtime = this.loadRuntime(extension);
await this.activateExtension(extension, runtime);
} catch (err) {
this.extensionState.set(extension.id, 'failed');
this.extensionStateErrors.set(extension.id, err);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(telemetryOptions as any).error = err;
} finally {
this.telemetry.track('loadExtension', telemetryOptions);
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
createApi(extensionPath: string, extManifest: any): typeof containerDesktopAPI {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const instance = this;
const extensionInfo = {
id: `${extManifest.publisher}.${extManifest.name}`,
label: extManifest.displayName,
version: extManifest.version,
publisher: extManifest.publisher,
name: extManifest.name,
extensionPath,
icon: extManifest.icon ? instance.updateImage(extManifest.icon, extensionPath) : undefined,
};
const commandRegistry = this.commandRegistry;
const commands: typeof containerDesktopAPI.commands = {
registerCommand(
command: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
callback: (...args: any[]) => any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
thisArg?: any,
): containerDesktopAPI.Disposable {
return commandRegistry.registerCommand(command, callback, thisArg);
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
executeCommand<T = unknown>(commandId: string, ...args: any[]): PromiseLike<T> {
return commandRegistry.executeCommand(commandId, ...args);
},
};
//export function executeCommand<T = unknown>(command: string, ...rest: any[]): PromiseLike<T>;
const providerRegistry = this.providerRegistry;
const provider: typeof containerDesktopAPI.provider = {
createProvider(providerOptions: containerDesktopAPI.ProviderOptions): containerDesktopAPI.Provider {
// update path of images using the extension path
if (providerOptions.images) {
const images = providerOptions.images;
instance.updateImage.bind(instance);
images.icon = instance.updateImage(images.icon, extensionPath);
images.logo = instance.updateImage(images.logo, extensionPath);
}
return providerRegistry.createProvider(extensionInfo.id, extensionInfo.label, providerOptions);
},
onDidUpdateProvider: (listener, thisArg, disposables) => {
return providerRegistry.onDidUpdateProvider(listener, thisArg, disposables);
},
onDidUpdateContainerConnection: (listener, thisArg, disposables) => {
return providerRegistry.onDidUpdateContainerConnection(listener, thisArg, disposables);
},
onDidUpdateKubernetesConnection: (listener, thisArg, disposables) => {
return providerRegistry.onDidUpdateKubernetesConnection(listener, thisArg, disposables);
},
onDidUnregisterContainerConnection: (listener, thisArg, disposables) => {
return providerRegistry.onDidUnregisterContainerConnection(listener, thisArg, disposables);
},
onDidRegisterContainerConnection: (listener, thisArg, disposables) => {
return providerRegistry.onDidRegisterContainerConnection(listener, thisArg, disposables);
},
getContainerConnections: () => {
return providerRegistry.getContainerConnections();
},
getProviderLifecycleContext(
providerId: string,
providerConnectionInfo: ProviderContainerConnectionInfo | ProviderKubernetesConnectionInfo,
): containerDesktopAPI.LifecycleContext {
return providerRegistry.getMatchingProviderLifecycleContextByProviderId(providerId, providerConnectionInfo);
},
};
const proxyInstance = this.proxy;
const proxy: typeof containerDesktopAPI.proxy = {
getProxySettings(): containerDesktopAPI.ProxySettings | undefined {
return proxyInstance.proxy;
},
async setProxy(proxySettings: containerDesktopAPI.ProxySettings): Promise<void> {
return proxyInstance.setProxy(proxySettings);
},
onDidUpdateProxy: (listener, thisArg, disposables) => {
return proxyInstance.onDidUpdateProxy(listener, thisArg, disposables);
},
isEnabled(): boolean {
return proxyInstance.isEnabled();
},
onDidStateChange: (listener, thisArg, disposables) => {
return proxyInstance.onDidStateChange(listener, thisArg, disposables);
},
};
const trayMenuRegistry = this.trayMenuRegistry;
const tray: typeof containerDesktopAPI.tray = {
registerMenuItem(item: containerDesktopAPI.MenuItem): containerDesktopAPI.Disposable {
return trayMenuRegistry.registerMenuItem(item);
},
registerProviderMenuItem(providerId: string, item: containerDesktopAPI.MenuItem): containerDesktopAPI.Disposable {
return trayMenuRegistry.registerProviderMenuItem(providerId, item);
},
};
const configurationRegistry = this.configurationRegistry;
const configuration: typeof containerDesktopAPI.configuration = {
getConfiguration(
section?: string,
scope?: containerDesktopAPI.ConfigurationScope,
): containerDesktopAPI.Configuration {
return configurationRegistry.getConfiguration(section, scope);
},
onDidChangeConfiguration: (listener, thisArg, disposables) => {
return configurationRegistry.onDidChangeConfigurationAPI(listener, thisArg, disposables);
},
};
const imageRegistry = this.imageRegistry;
const registry: typeof containerDesktopAPI.registry = {
registerRegistry: (registry: containerDesktopAPI.Registry): Disposable => {
return imageRegistry.registerRegistry(registry);
},
suggestRegistry: (registry: containerDesktopAPI.RegistrySuggestedProvider): Disposable => {
return imageRegistry.suggestRegistry(registry);
},
unregisterRegistry: (registry: containerDesktopAPI.Registry): void => {
return imageRegistry.unregisterRegistry(registry);
},
onDidUpdateRegistry: (listener, thisArg, disposables) => {
return imageRegistry.onDidUpdateRegistry(listener, thisArg, disposables);
},
onDidRegisterRegistry: (listener, thisArg, disposables) => {
return imageRegistry.onDidRegisterRegistry(listener, thisArg, disposables);
},
onDidUnregisterRegistry: (listener, thisArg, disposables) => {
return imageRegistry.onDidUnregisterRegistry(listener, thisArg, disposables);
},
registerRegistryProvider: (registryProvider: containerDesktopAPI.RegistryProvider): Disposable => {
return imageRegistry.registerRegistryProvider(registryProvider);
},
};
const messageBox = this.messageBox;
const progress = this.progress;
const inputQuickPickRegistry = this.inputQuickPickRegistry;
const customPickRegistry = this.customPickRegistry;
const windowObj: typeof containerDesktopAPI.window = {
showInformationMessage: (message: string, ...items: string[]) => {
return messageBox.showDialog('info', extManifest.displayName, message, items);
},
showWarningMessage: (message: string, ...items: string[]) => {
return messageBox.showDialog('warning', extManifest.displayName, message, items);
},
showErrorMessage: (message: string, ...items: string[]) => {
return messageBox.showDialog('error', extManifest.displayName, message, items);
},
showInputBox: (options?: containerDesktopAPI.InputBoxOptions, token?: containerDesktopAPI.CancellationToken) => {
return inputQuickPickRegistry.showInputBox(options, token);
},
showQuickPick(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
items: readonly any[] | Promise<readonly any[]>,
options?: containerDesktopAPI.QuickPickOptions,
token?: containerDesktopAPI.CancellationToken,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> {
return inputQuickPickRegistry.showQuickPick(items, options, token);
},
withProgress: <R>(
options: containerDesktopAPI.ProgressOptions,
task: (
progress: containerDesktopAPI.Progress<{ message?: string; increment?: number }>,
token: containerDesktopAPI.CancellationToken,
) => Promise<R>,
): Promise<R> => {
return progress.withProgress(options, task);
},
showNotification: (notificationInfo: containerDesktopAPI.NotificationOptions): containerDesktopAPI.Disposable => {
return this.notificationRegistry.addNotification({
...notificationInfo,
extensionId: extensionInfo.id,
type: notificationInfo.type || 'info',
title: notificationInfo.title || extensionInfo.name,
});
},
createStatusBarItem: (
param1?: containerDesktopAPI.StatusBarAlignment | number,
param2?: number,
): containerDesktopAPI.StatusBarItem => {
let alignment: containerDesktopAPI.StatusBarAlignment = StatusBarAlignLeft;
let priority = StatusBarItemDefaultPriority;
if (typeof param2 !== 'undefined') {
alignment = param1 as containerDesktopAPI.StatusBarAlignment;
priority = param2;
} else if (typeof param1 !== 'undefined') {
if (typeof param1 === 'string') {
alignment = param1 as containerDesktopAPI.StatusBarAlignment;
} else {
priority = param1;
}
}
return new StatusBarItemImpl(this.statusBarRegistry, alignment, priority);
},
createCustomPick: <T extends containerDesktopAPI.CustomPickItem>(): containerDesktopAPI.CustomPick<T> => {
return customPickRegistry.createCustomPick();
},
};
const fileSystemMonitoring = this.fileSystemMonitoring;
const fs: typeof containerDesktopAPI.fs = {
createFileSystemWatcher(path: string): containerDesktopAPI.FileSystemWatcher {
return fileSystemMonitoring.createFileSystemWatcher(path);
},
};
const kubernetesClient = this.kubernetesClient;
const kubernetesGeneratorRegistry = this.kubeGeneratorRegistry;
const kubernetes: typeof containerDesktopAPI.kubernetes = {
getKubeconfig(): containerDesktopAPI.Uri {
return kubernetesClient.getKubeconfig();
},
async setKubeconfig(kubeconfig: containerDesktopAPI.Uri): Promise<void> {
return kubernetesClient.setKubeconfig(kubeconfig);
},
onDidUpdateKubeconfig: (listener, thisArg, disposables) => {
return kubernetesClient.onDidUpdateKubeconfig(listener, thisArg, disposables);
},
async createResources(context, manifests): Promise<void> {
return kubernetesClient.createResources(context, manifests);
},
registerKubernetesGenerator(provider: KubernetesGeneratorProvider): containerDesktopAPI.Disposable {
return kubernetesGeneratorRegistry.registerKubeGenerator(provider);
},
};
const containerProviderRegistry = this.containerProviderRegistry;
const containerEngine: typeof containerDesktopAPI.containerEngine = {
listContainers(): Promise<containerDesktopAPI.ContainerInfo[]> {
return containerProviderRegistry.listSimpleContainers();
},
createContainer(
engineId: string,
containerCreateOptions: containerDesktopAPI.ContainerCreateOptions,
): Promise<containerDesktopAPI.ContainerCreateResult> {
return containerProviderRegistry.createAndStartContainer(engineId, containerCreateOptions);
},
inspectContainer(engineId: string, id: string): Promise<containerDesktopAPI.ContainerInspectInfo> {
return containerProviderRegistry.getContainerInspect(engineId, id);
},
startContainer(engineId: string, id: string) {
return containerProviderRegistry.startContainer(engineId, id);
},
logsContainer(engineId: string, id: string, callback: (name: string, data: string) => void) {
return containerProviderRegistry.logsContainer(engineId, id, callback);
},
stopContainer(engineId: string, id: string) {
return containerProviderRegistry.stopContainer(engineId, id);
},
deleteContainer(engineId: string, id: string) {
return containerProviderRegistry.deleteContainer(engineId, id);
},
buildImage(
context: string,
eventCollect: (eventName: 'stream' | 'error' | 'finish', data: string) => void,
option?: containerDesktopAPI.BuildImageOptions,
) {
return containerProviderRegistry.buildImage(
context,
eventCollect,
option?.containerFile,
option?.target,
option?.platform,
option?.provider,
option?.abortController,
);
},
listImages(): Promise<containerDesktopAPI.ImageInfo[]> {
return containerProviderRegistry.listImages();
},
saveImage(engineId: string, id: string, filename: string) {
return containerProviderRegistry.saveImage(engineId, id, filename);
},
pushImage(
engineId: string,
imageId: string,
callback: (name: string, data: string) => void,
authInfo: containerDesktopAPI.ContainerAuthInfo | undefined,
): Promise<void> {
return containerProviderRegistry.pushImage(engineId, imageId, callback, authInfo);
},
pullImage(
providerContainerConnection: containerDesktopAPI.ContainerProviderConnection,
imageName: string,
callback: (event: containerDesktopAPI.PullEvent) => void,
): Promise<void> {
return containerProviderRegistry.pullImage(providerContainerConnection, imageName, callback);
},
tagImage(engineId: string, imageId: string, repo: string, tag: string | undefined): Promise<void> {
return containerProviderRegistry.tagImage(engineId, imageId, repo, tag);
},
deleteImage(engineId: string, id: string) {
return containerProviderRegistry.deleteImage(engineId, id);
},
info(engineId: string): Promise<containerDesktopAPI.ContainerEngineInfo> {
return containerProviderRegistry.info(engineId);
},
onEvent: (listener, thisArg, disposables) => {
return containerProviderRegistry.onEvent(listener, thisArg, disposables);
},
listNetworks(): Promise<containerDesktopAPI.NetworkInspectInfo[]> {
return containerProviderRegistry.listNetworks();
},
createNetwork(
providerContainerConnection: containerDesktopAPI.ContainerProviderConnection,
networkCreateOptions: containerDesktopAPI.NetworkCreateOptions,
): Promise<containerDesktopAPI.NetworkCreateResult> {
return containerProviderRegistry.createNetwork(providerContainerConnection, networkCreateOptions);
},
};
const authenticationProviderRegistry = this.authenticationProviderRegistry;
const authentication: typeof containerDesktopAPI.authentication = {
getSession: (providerId, scopes, options) => {
return authenticationProviderRegistry.getSession(extensionInfo, providerId, scopes, options);
},
registerAuthenticationProvider: (id, label, provider, options) => {
// update path of images using the extension path
if (options?.images) {
const images = options.images;
instance.updateImage.bind(instance);
images.icon = instance.updateImage(images.icon, extensionPath);
images.logo = instance.updateImage(images.logo, extensionPath);
}
return authenticationProviderRegistry.registerAuthenticationProvider(id, label, provider, options);
},
onDidChangeSessions: (listener, thisArg, disposables) => {
return authenticationProviderRegistry.onDidChangeSessions(listener, thisArg, disposables);
},
};
const telemetry = this.telemetry;
const env: typeof containerDesktopAPI.env = {
get isMac() {
return isMac();
},
get isWindows() {
return isWindows();
},
get isLinux() {
return isLinux();
},
openExternal: async (uri: containerDesktopAPI.Uri): Promise<boolean> => {