proto_pdk_api 0.31.11

Core APIs for creating proto WASM plugins.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
mod build;
mod checksum;
mod source;

use crate::shapes::*;
use derive_setters::Setters;
use rustc_hash::FxHashMap;
use schematic::Schema;
use std::path::PathBuf;
use version_spec::{CalVer, SemVer, SpecError, UnresolvedVersionSpec, VersionSpec};
use warpgate_api::*;

pub use build::*;
pub use checksum::*;
pub use semver::{Version, VersionReq};
pub use source::*;

/// Enumeration of all available plugin functions that can be implemented by plugins.
///
/// This enum provides type-safe access to plugin function names and eliminates
/// the risk of typos when calling plugin functions. Each variant corresponds to
/// a specific plugin function with its associated input/output types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PluginFunction {
    /// Register and configure a tool with proto.
    ///
    /// Called when proto first loads a plugin to get basic metadata about the tool
    /// including its name, type, and configuration schema.
    ///
    /// **Input:** [`RegisterToolInput`] | **Output:** [`RegisterToolOutput`]
    RegisterTool,

    /// Define the tool configuration schema.
    ///
    /// **Input:** [`DefineToolConfigInput`] | **Output:** [`DefineToolConfigOutput`]
    DefineToolConfig,

    /// Register a backend with proto.
    ///
    /// Allows plugins to define custom backends for sourcing tools from locations
    /// other than the default registry.
    ///
    /// **Input:** [`RegisterBackendInput`] | **Output:** [`RegisterBackendOutput`]
    RegisterBackend,

    /// Define the backend configuration schema.
    ///
    /// **Input:** [`DefineBackendConfigInput`] | **Output:** [`DefineBackendConfigOutput`]
    DefineBackendConfig,

    /// Detect version files in a project.
    ///
    /// Returns a list of file patterns that should be checked for version information
    /// when auto-detecting tool versions.
    ///
    /// **Input:** [`DetectVersionInput`] | **Output:** [`DetectVersionOutput`]
    DetectVersionFiles,

    /// Parse version information from files.
    ///
    /// Extracts version specifications from configuration files like `.nvmrc`,
    /// `package.json`, `pyproject.toml`, etc.
    ///
    /// **Input:** [`ParseVersionFileInput`] | **Output:** [`ParseVersionFileOutput`]
    ParseVersionFile,

    /// Pin a version to a file in the provided directory.
    ///
    /// **Input:** [`PinVersionInput`] | **Output:** [`PinVersionOutput`]
    PinVersion,

    /// Unpin a version from a file in the provided directory.
    ///
    /// **Input:** [`UnpinVersionInput`] | **Output:** [`UnpinVersionOutput`]
    UnpinVersion,

    /// Load available versions for a tool.
    ///
    /// Fetches the list of available versions that can be installed, including
    /// version aliases like "latest" or "lts".
    ///
    /// **Input:** [`LoadVersionsInput`] | **Output:** [`LoadVersionsOutput`]
    LoadVersions,

    /// Resolve version specifications to concrete versions.
    ///
    /// Takes version requirements or aliases and resolves them to specific
    /// installable versions.
    ///
    /// **Input:** [`ResolveVersionInput`] | **Output:** [`ResolveVersionOutput`]
    ResolveVersion,

    /// Download prebuilt tool archives.
    ///
    /// Provides URLs and metadata for downloading pre-compiled tool binaries
    /// instead of building from source.
    ///
    /// **Input:** [`DownloadPrebuiltInput`] | **Output:** [`DownloadPrebuiltOutput`]
    DownloadPrebuilt,

    /// Provide build instructions for tools.
    ///
    /// Returns the steps needed to build a tool from source, including dependencies,
    /// build commands, and environment requirements.
    ///
    /// **Input:** [`BuildInstructionsInput`] | **Output:** [`BuildInstructionsOutput`]
    BuildInstructions,

    /// Unpack downloaded archives.
    ///
    /// Handles custom unpacking logic for tool archives when the default extraction
    /// methods are insufficient.
    ///
    /// **Input:** [`UnpackArchiveInput`] | **Output:** None
    UnpackArchive,

    /// Verify download checksums.
    ///
    /// Provides custom checksum verification logic for downloaded tool archives
    /// to ensure integrity.
    ///
    /// **Input:** [`VerifyChecksumInput`] | **Output:** [`VerifyChecksumOutput`]
    VerifyChecksum,

    /// Native tool installation.
    ///
    /// Handles tool installation using the tool's own installation methods rather
    /// than proto's standard process.
    ///
    /// **Input:** [`NativeInstallInput`] | **Output:** [`NativeInstallOutput`]
    NativeInstall,

    /// Native tool uninstallation.
    ///
    /// Handles tool removal using the tool's own uninstallation methods rather
    /// than simple directory deletion.
    ///
    /// **Input:** [`NativeUninstallInput`] | **Output:** [`NativeUninstallOutput`]
    NativeUninstall,

    /// Locate tool executables.
    ///
    /// Identifies where executables are located within an installed tool and
    /// configures them for proto's shim system.
    ///
    /// **Input:** [`LocateExecutablesInput`] | **Output:** [`LocateExecutablesOutput`]
    LocateExecutables,

    /// Sync the tool manifest.
    ///
    /// Allows plugins to update proto's inventory of installed versions with
    /// external changes.
    ///
    /// **Input:** [`SyncManifestInput`] | **Output:** [`SyncManifestOutput`]
    SyncManifest,

    /// Sync shell profile configuration.
    ///
    /// Configures shell environment variables and PATH modifications needed for
    /// the tool to work properly.
    ///
    /// **Input:** [`SyncShellProfileInput`] | **Output:** [`SyncShellProfileOutput`]
    SyncShellProfile,

    /// Setup the environment during activation or execution.
    ///
    /// **Input:** [`ActivateEnvironmentInput`] | **Output:** [`ActivateEnvironmentOutput`]
    ActivateEnvironment,
}

impl PluginFunction {
    /// Get the string representation of the plugin function name.
    ///
    /// This returns the actual function name that should be used when calling
    /// the plugin function via WASM.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::RegisterTool => "register_tool",
            Self::DefineToolConfig => "define_tool_config",
            Self::RegisterBackend => "register_backend",
            Self::DefineBackendConfig => "define_backend_config",
            Self::DetectVersionFiles => "detect_version_files",
            Self::ParseVersionFile => "parse_version_file",
            Self::PinVersion => "pin_version",
            Self::UnpinVersion => "unpin_version",
            Self::LoadVersions => "load_versions",
            Self::ResolveVersion => "resolve_version",
            Self::DownloadPrebuilt => "download_prebuilt",
            Self::BuildInstructions => "build_instructions",
            Self::UnpackArchive => "unpack_archive",
            Self::VerifyChecksum => "verify_checksum",
            Self::NativeInstall => "native_install",
            Self::NativeUninstall => "native_uninstall",
            Self::LocateExecutables => "locate_executables",
            Self::SyncManifest => "sync_manifest",
            Self::SyncShellProfile => "sync_shell_profile",
            Self::ActivateEnvironment => "activate_environment",
        }
    }
}

impl AsRef<str> for PluginFunction {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

pub(crate) fn is_false(value: &bool) -> bool {
    !(*value)
}

pub(crate) fn is_default<T: Default + PartialEq>(value: &T) -> bool {
    value == &T::default()
}

api_struct!(
    /// Information about the current state of the plugin,
    /// after a version has been resolved.
    pub struct PluginContext {
        /// The version of proto (the core crate) calling plugin functions.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub proto_version: Option<Version>,

        /// Virtual path to the tool's temporary directory.
        pub temp_dir: VirtualPath,

        /// Virtual path to the tool's installation directory.
        pub tool_dir: VirtualPath,

        /// Current version. Will be a "latest" alias if not resolved.
        pub version: VersionSpec,

        /// Virtual path to the current working directory.
        pub working_dir: VirtualPath,
    }
);

api_struct!(
    /// Information about the current state of the plugin,
    /// before a version has been resolved.
    pub struct PluginUnresolvedContext {
        /// The version of proto (the core crate) calling plugin functions.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub proto_version: Option<Version>,

        /// Virtual path to the tool's temporary directory.
        pub temp_dir: VirtualPath,

        // TODO: Temporary compat with `PluginContext`
        #[doc(hidden)]
        #[deprecated]
        pub tool_dir: VirtualPath,

        // TODO: Temporary compat with `PluginContext`
        #[doc(hidden)]
        #[deprecated]
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub version: Option<VersionSpec>,

        /// Virtual path to the current working directory.
        pub working_dir: VirtualPath,
    }
);

api_unit_enum!(
    /// Supported types of plugins.
    pub enum PluginType {
        #[serde(alias = "CLI", alias = "CommandLine")] // TEMP
        CommandLine,
        #[default]
        #[serde(alias = "Language")]
        Language,
        #[serde(alias = "PM", alias = "DependencyManager")] // TEMP
        DependencyManager,
        #[serde(alias = "VM", alias = "VersionManager")] // TEMP
        VersionManager,
    }
);

api_struct!(
    /// Input passed to the `register_tool` function.
    pub struct RegisterToolInput {
        /// ID of the tool, as it was configured.
        pub id: Id,
    }
);

#[deprecated(note = "Use `RegisterToolInput` instead.")]
pub type ToolMetadataInput = RegisterToolInput;

api_struct!(
    /// Controls aspects of the tool inventory.
    #[serde(default)]
    pub struct ToolInventoryOptions {
        /// Override the tool inventory directory (where all versions are installed).
        /// This is an advanced feature and should only be used when absolutely necessary.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub override_dir: Option<VirtualPath>,

        /// When the inventory is backend managed, scope the inventory directory name
        /// with the backend as a prefix.
        #[serde(skip_serializing_if = "is_false")]
        pub scoped_backend_dir: bool,

        /// Suffix to append to all versions when labeling directories.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub version_suffix: Option<String>,
    }
);

api_unit_enum!(
    /// Supported strategies for installing a tool.
    pub enum InstallStrategy {
        #[serde(alias = "BuildFromSource")]
        BuildFromSource,
        #[default]
        #[serde(alias = "DownloadPrebuilt")]
        DownloadPrebuilt,
    }
);

api_struct!(
    /// Options related to lockfile integration.
    #[serde(default)]
    pub struct ToolLockOptions {
        /// Ignore operating system and architecture values
        /// when matching against records in the lockfile.
        #[serde(skip_serializing_if = "is_false")]
        pub ignore_os_arch: bool,

        /// Do not record the install in the lockfile.
        #[serde(skip_serializing_if = "is_false")]
        pub no_record: bool,
    }
);

api_struct!(
    /// Output returned by the `register_tool` function.
    pub struct RegisterToolOutput {
        /// Default strategy to use when installing a tool.
        #[serde(default)]
        pub default_install_strategy: InstallStrategy,

        /// Default alias or version to use as a fallback.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub default_version: Option<UnresolvedVersionSpec>,

        /// List of deprecation messages that will be displayed to users
        /// of this plugin.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        pub deprecations: Vec<String>,

        /// Controls aspects of the tool inventory.
        #[serde(default, skip_serializing_if = "is_default", alias = "inventory")]
        pub inventory_options: ToolInventoryOptions,

        /// Options for integrating with a lockfile.
        #[serde(default, skip_serializing_if = "is_default")]
        pub lock_options: ToolLockOptions,

        /// Minimum version of proto required to execute this plugin.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub minimum_proto_version: Option<Version>,

        /// Human readable name of the tool.
        pub name: String,

        /// Version of the plugin.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub plugin_version: Option<Version>,

        /// Other plugins that this plugin requires.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        pub requires: Vec<String>,

        /// Names of commands that will self-upgrade the tool,
        /// and should be blocked from happening.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        pub self_upgrade_commands: Vec<String>,

        /// Type of the tool.
        #[serde(rename = "type")]
        pub type_of: PluginType,

        /// Whether this plugin is unstable or not.
        #[serde(default)]
        pub unstable: Switch,
    }
);

#[deprecated(note = "Use `RegisterToolOutput` instead.")]
pub type ToolMetadataOutput = RegisterToolOutput;

pub type ConfigSchema = Schema;

api_struct!(
    /// Output returned from the `define_tool_config` function.
    pub struct DefineToolConfigOutput {
        /// Schema shape of the tool's configuration.
        pub schema: ConfigSchema,
    }
);

// BACKEND

api_struct!(
    /// Input passed to the `register_backend` function.
    pub struct RegisterBackendInput {
        /// Current tool context.
        pub context: PluginUnresolvedContext,

        /// ID of the tool, as it was configured.
        pub id: Id,
    }
);

api_struct!(
    /// Output returned by the `register_backend` function.
    pub struct RegisterBackendOutput {
        /// Unique identifier for this backend. Will be used as the folder name.
        pub backend_id: Id,

        /// List of executables, relative from the backend directory,
        /// that will be executed in the context of proto.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        pub exes: Vec<PathBuf>,

        /// Location in which to acquire source files for the backend.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub source: Option<SourceLocation>,
    }
);

api_struct!(
    /// Output returned from the `define_backend_config` function.
    pub struct DefineBackendConfigOutput {
        /// Schema shape of the backend's configuration.
        pub schema: ConfigSchema,
    }
);

// VERSION DETECTION/PINNING

api_struct!(
    /// Input passed to the `detect_version_files` function.
    pub struct DetectVersionInput {
        /// Current tool context.
        pub context: PluginUnresolvedContext,
    }
);

api_struct!(
    /// Output returned by the `detect_version_files` function.
    #[serde(default)]
    pub struct DetectVersionOutput {
        /// List of files that should be checked for version information.
        #[serde(skip_serializing_if = "Vec::is_empty")]
        pub files: Vec<String>,

        /// List of path patterns to ignore when traversing directories.
        #[serde(skip_serializing_if = "Vec::is_empty")]
        pub ignore: Vec<String>,
    }
);

api_struct!(
    /// Input passed to the `parse_version_file` function.
    pub struct ParseVersionFileInput {
        /// File contents to parse/extract a version from.
        pub content: String,

        /// Current tool context.
        pub context: PluginUnresolvedContext,

        /// Name of file that's being parsed.
        pub file: String,

        /// Virtual path to the file being parsed.
        pub path: VirtualPath,
    }
);

api_struct!(
    /// Output returned by the `parse_version_file` function.
    #[serde(default)]
    pub struct ParseVersionFileOutput {
        /// The version that was extracted from the file.
        /// Can be a semantic version or a version requirement/range.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub version: Option<UnresolvedVersionSpec>,
    }
);

api_struct!(
    /// Input passed to the `pin_version` function.
    pub struct PinVersionInput {
        /// Current tool context.
        pub context: PluginUnresolvedContext,

        /// Virtual directory in which the pin should occur.
        pub dir: VirtualPath,

        /// The version to pin.
        pub version: UnresolvedVersionSpec,
    }
);

api_struct!(
    /// Output returned by the `pin_version` function.
    #[serde(default)]
    pub struct PinVersionOutput {
        /// Virtual path of the file the version was pinned to.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub file: Option<VirtualPath>,

        /// Error message if the pin failed.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub error: Option<String>,

        /// Whether the pin was successful.
        pub pinned: bool,
    }
);

api_struct!(
    /// Input passed to the `unpin_version` function.
    pub struct UnpinVersionInput {
        /// Current tool context.
        pub context: PluginUnresolvedContext,

        /// Virtual directory in which the unpin should occur.
        pub dir: VirtualPath,
    }
);

api_struct!(
    /// Output returned by the `unpin_version` function.
    #[serde(default)]
    pub struct UnpinVersionOutput {
        /// Virtual path of the file the version was unpinned from.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub file: Option<VirtualPath>,

        /// Error message if the unpin failed.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub error: Option<String>,

        /// Whether the unpin was successful.
        pub unpinned: bool,

        /// The version that was unpinned.
        pub version: Option<UnresolvedVersionSpec>,
    }
);

// DOWNLOAD, BUILD, INSTALL, VERIFY

api_struct!(
    /// Input passed to the `native_install` function.
    pub struct NativeInstallInput {
        /// Current tool context.
        pub context: PluginContext,

        /// Whether to force install or not.
        pub force: bool,

        /// Virtual directory to install to.
        pub install_dir: VirtualPath,
    }
);

api_struct!(
    /// Output returned by the `native_install` function.
    pub struct NativeInstallOutput {
        /// A checksum/hash that was generated.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub checksum: Option<Checksum>,

        /// Error message if the install failed.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub error: Option<String>,

        /// Whether the install was successful.
        pub installed: bool,

        /// Whether to skip the install process or not.
        #[serde(default)]
        pub skip_install: bool,
    }
);

api_struct!(
    /// Input passed to the `native_uninstall` function.
    pub struct NativeUninstallInput {
        /// Current tool context.
        pub context: PluginContext,

        /// Virtual directory to uninstall from.
        pub uninstall_dir: VirtualPath,
    }
);

api_struct!(
    /// Output returned by the `native_uninstall` function.
    pub struct NativeUninstallOutput {
        /// Error message if the uninstall failed.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub error: Option<String>,

        /// Whether the install was successful.
        pub uninstalled: bool,

        /// Whether to skip the uninstall process or not.
        #[serde(default)]
        pub skip_uninstall: bool,
    }
);

api_struct!(
    /// Input passed to the `download_prebuilt` function.
    pub struct DownloadPrebuiltInput {
        /// Current tool context.
        pub context: PluginContext,

        /// Virtual directory to install to.
        pub install_dir: VirtualPath,
    }
);

api_struct!(
    /// Output returned by the `download_prebuilt` function.
    pub struct DownloadPrebuiltOutput {
        /// Name of the direct folder within the archive that contains the tool,
        /// and will be removed when unpacking the archive.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub archive_prefix: Option<String>,

        /// The checksum hash itself.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub checksum: Option<Checksum>,

        /// File name of the checksum to download. If not provided,
        /// will attempt to extract it from the URL.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub checksum_name: Option<String>,

        /// Public key to use for checksum verification.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub checksum_public_key: Option<String>,

        /// A secure URL to download the checksum file for verification.
        /// If the tool does not support checksum verification, this setting can be omitted.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub checksum_url: Option<String>,

        /// File name of the archive to download. If not provided,
        /// will attempt to extract it from the URL.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub download_name: Option<String>,

        /// A secure URL to download the tool/archive.
        pub download_url: String,

        /// A map of HTTP headers to include in all requests
        /// during the download phase.
        #[serde(default, skip_serializing_if = "FxHashMap::is_empty")]
        pub http_headers: FxHashMap<String, String>,

        /// A script, relative from the install directory, to execute after
        /// the prebuilt has been installed.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub post_script: Option<PathBuf>,
    }
);

api_struct!(
    /// Input passed to the `unpack_archive` function.
    pub struct UnpackArchiveInput {
        /// Current tool context.
        pub context: PluginContext,

        /// Virtual path to the downloaded file.
        pub input_file: VirtualPath,

        /// Virtual directory to unpack the archive into, or copy the executable to.
        pub output_dir: VirtualPath,
    }
);

api_struct!(
    /// Output returned by the `verify_checksum` function.
    pub struct VerifyChecksumInput {
        /// Current tool context.
        pub context: PluginContext,

        /// Virtual path to the checksum file.
        pub checksum_file: VirtualPath,

        /// A checksum of the downloaded file. The type of hash
        /// is derived from the checksum file's extension, otherwise
        /// it defaults to SHA256.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub download_checksum: Option<Checksum>,

        /// Virtual path to the downloaded file.
        pub download_file: VirtualPath,
    }
);

api_struct!(
    /// Output returned by the `verify_checksum` function.
    pub struct VerifyChecksumOutput {
        /// Was the checksum correct?
        pub verified: bool,
    }
);

// EXECUTABLES, BINARYS, GLOBALS

api_struct!(
    /// Input passed to the `locate_executables` function.
    pub struct LocateExecutablesInput {
        /// Current tool context.
        pub context: PluginContext,

        /// Virtual directory the tool was installed to.
        pub install_dir: VirtualPath,
    }
);

api_struct!(
    /// Configuration for generated shim and symlinked executable files.
    #[derive(Setters)]
    #[serde(default)]
    pub struct ExecutableConfig {
        /// The file to execute, relative from the tool directory.
        /// Does *not* support virtual paths.
        #[setters(strip_option)]
        #[serde(skip_serializing_if = "Option::is_none")]
        pub exe_path: Option<PathBuf>,

        /// The executable path to use for symlinking instead of `exe_path`.
        /// This should only be used when `exe_path` is a non-standard executable.
        #[setters(strip_option)]
        #[serde(skip_serializing_if = "Option::is_none")]
        pub exe_link_path: Option<PathBuf>,

        /// Do not symlink a binary in `~/.proto/bin`.
        #[serde(skip_serializing_if = "is_false")]
        pub no_bin: bool,

        /// Do not generate a shim in `~/.proto/shims`.
        #[serde(skip_serializing_if = "is_false")]
        pub no_shim: bool,

        /// List of arguments to append to the parent executable, but prepend before
        /// all other arguments.
        #[serde(skip_serializing_if = "Vec::is_empty")]
        pub parent_exe_args: Vec<String>,

        /// The parent executable name required to execute the local executable path.
        #[setters(into, strip_option)]
        #[serde(skip_serializing_if = "Option::is_none")]
        pub parent_exe_name: Option<String>,

        /// Whether this is the primary executable or not.
        #[serde(skip_serializing_if = "is_false")]
        pub primary: bool,

        /// Custom args to prepend to user-provided args within the generated shim.
        #[setters(strip_option)]
        #[serde(skip_serializing_if = "Option::is_none")]
        pub shim_before_args: Option<StringOrVec>,

        /// Custom args to append to user-provided args within the generated shim.
        #[setters(strip_option)]
        #[serde(skip_serializing_if = "Option::is_none")]
        pub shim_after_args: Option<StringOrVec>,

        /// Custom environment variables to set when executing the shim.
        #[setters(strip_option)]
        #[serde(skip_serializing_if = "Option::is_none")]
        pub shim_env_vars: Option<FxHashMap<String, String>>,

        /// Update the file permissions to executable. This only exists as these
        /// values cannot be changed from within WASM.
        #[serde(skip_serializing_if = "is_false")]
        pub update_perms: bool,
    }
);

impl ExecutableConfig {
    pub fn new<T: AsRef<str>>(exe_path: T) -> Self {
        Self {
            exe_path: Some(PathBuf::from(exe_path.as_ref())),
            ..ExecutableConfig::default()
        }
    }

    pub fn new_primary<T: AsRef<str>>(exe_path: T) -> Self {
        Self {
            exe_path: Some(PathBuf::from(exe_path.as_ref())),
            primary: true,
            ..ExecutableConfig::default()
        }
    }

    pub fn with_parent<T: AsRef<str>, P: AsRef<str>>(exe_path: T, parent_exe: P) -> Self {
        Self {
            exe_path: Some(PathBuf::from(exe_path.as_ref())),
            parent_exe_name: Some(parent_exe.as_ref().to_owned()),
            ..ExecutableConfig::default()
        }
    }
}

api_struct!(
    /// Output returned by the `locate_executables` function.
    #[serde(default)]
    pub struct LocateExecutablesOutput {
        /// Configures executable information to be used as proto bins/shims.
        /// The map key will be the name of the executable file.
        #[serde(skip_serializing_if = "FxHashMap::is_empty")]
        pub exes: FxHashMap<String, ExecutableConfig>,

        #[deprecated(note = "Use `exes_dirs` instead.")]
        #[serde(skip_serializing_if = "Option::is_none")]
        pub exes_dir: Option<PathBuf>,

        /// Relative directory path from the tool install directory in which
        /// pre-installed executables can be located. This directory path
        /// will be used during `proto activate`, but not for bins/shims.
        #[serde(skip_serializing_if = "Vec::is_empty")]
        pub exes_dirs: Vec<PathBuf>,

        /// List of directory paths to find the globals installation directory.
        /// Each path supports environment variable expansion.
        #[serde(skip_serializing_if = "Vec::is_empty")]
        pub globals_lookup_dirs: Vec<String>,

        /// A string that all global executables are prefixed with, and will be removed
        /// when listing and filtering available globals.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub globals_prefix: Option<String>,
    }
);

api_struct!(
    /// Input passed to the `activate_environment` function.
    pub struct ActivateEnvironmentInput {
        /// Current tool context.
        pub context: PluginContext,

        /// Path to the global packages directory for the tool, if found.
        pub globals_dir: Option<VirtualPath>,
    }
);

api_struct!(
    /// Output returned by the `activate_environment` function.
    #[serde(default)]
    pub struct ActivateEnvironmentOutput {
        /// Additional environment variables to set. Will overwrite any existing variables.
        pub env: FxHashMap<String, String>,

        /// Additional paths to prepend to `PATH`. Tool specific executables
        /// and globals directories do NOT need to be included here, as they
        /// are automatically included.
        pub paths: Vec<PathBuf>,
    }
);

// VERSION RESOLVING

api_struct!(
    /// Input passed to the `load_versions` function.
    pub struct LoadVersionsInput {
        /// Current tool context.
        pub context: PluginUnresolvedContext,

        /// The alias or version currently being resolved.
        pub initial: UnresolvedVersionSpec,
    }
);

api_struct!(
    /// Output returned by the `load_versions` function.
    #[serde(default)]
    pub struct LoadVersionsOutput {
        /// Latest canary version.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub canary: Option<UnresolvedVersionSpec>,

        /// Latest stable version.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub latest: Option<UnresolvedVersionSpec>,

        /// Mapping of aliases (channels, etc) to a version.
        #[serde(skip_serializing_if = "FxHashMap::is_empty")]
        pub aliases: FxHashMap<String, UnresolvedVersionSpec>,

        /// List of available production versions to install.
        #[serde(skip_serializing_if = "Vec::is_empty")]
        pub versions: Vec<VersionSpec>,
    }
);

impl LoadVersionsOutput {
    /// Create the output from a list of strings that'll be parsed as versions.
    /// The latest version will be the highest version number.
    pub fn from(values: Vec<String>) -> Result<Self, SpecError> {
        let mut versions = vec![];

        for value in values {
            versions.push(VersionSpec::parse(&value)?);
        }

        Ok(Self::from_versions(versions))
    }

    /// Create the output from a list of version specifications.
    /// The latest version will be the highest version number.
    pub fn from_versions(versions: Vec<VersionSpec>) -> Self {
        let mut output = LoadVersionsOutput::default();
        let mut latest = Version::new(0, 0, 0);
        let mut calver = false;

        for version in versions {
            if let Some(inner) = version.as_version() {
                if inner.pre.is_empty() && inner.build.is_empty() && inner > &latest {
                    inner.clone_into(&mut latest);
                    calver = matches!(version, VersionSpec::Calendar(_));
                }
            }

            output.versions.push(version);
        }

        output.latest = Some(if calver {
            UnresolvedVersionSpec::Calendar(CalVer(latest))
        } else {
            UnresolvedVersionSpec::Semantic(SemVer(latest))
        });

        output
            .aliases
            .insert("latest".into(), output.latest.clone().unwrap());

        output
    }
}

api_struct!(
    /// Input passed to the `resolve_version` function.
    pub struct ResolveVersionInput {
        /// Current tool context.
        pub context: PluginUnresolvedContext,

        /// The alias or version currently being resolved.
        pub initial: UnresolvedVersionSpec,
    }
);

api_struct!(
    /// Output returned by the `resolve_version` function.
    #[serde(default)]
    pub struct ResolveVersionOutput {
        /// New alias or version candidate to resolve.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub candidate: Option<UnresolvedVersionSpec>,

        /// An explicitly resolved version to be used as-is.
        /// Note: Only use this field if you know what you're doing!
        #[serde(skip_serializing_if = "Option::is_none")]
        pub version: Option<VersionSpec>,
    }
);

// MISCELLANEOUS

api_struct!(
    /// Input passed to the `sync_manifest` function.
    pub struct SyncManifestInput {
        /// Current tool context.
        pub context: PluginUnresolvedContext,
    }
);

api_struct!(
    /// Output returned by the `sync_manifest` function.
    #[serde(default)]
    pub struct SyncManifestOutput {
        /// List of versions that are currently installed. Will replace
        /// what is currently in the manifest.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub versions: Option<Vec<VersionSpec>>,

        /// Whether to skip the syncing process or not.
        pub skip_sync: bool,
    }
);

api_struct!(
    /// Input passed to the `sync_shell_profile` function.
    pub struct SyncShellProfileInput {
        /// Current tool context.
        pub context: PluginContext,

        /// Arguments passed after `--` that was directly passed to the tool's executable.
        pub passthrough_args: Vec<String>,
    }
);

api_struct!(
    /// Output returned by the `sync_shell_profile` function.
    pub struct SyncShellProfileOutput {
        /// An environment variable to check for in the shell profile.
        /// If the variable exists, injecting path and exports will be avoided.
        pub check_var: String,

        /// A mapping of environment variables that will be injected as exports.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub export_vars: Option<FxHashMap<String, String>>,

        /// A list of paths to prepend to the `PATH` environment variable.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub extend_path: Option<Vec<String>>,

        /// Whether to skip the syncing process or not.
        #[serde(default)]
        pub skip_sync: bool,
    }
);