basalt-api 0.2.1

Public plugin API for the Basalt Minecraft server: traits, components, events, and the plugin registration system
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
//! Command argument types, parsing, and validation.
//!
//! Plugins declare command arguments with types, and the framework
//! handles parsing, validation, error messages, DeclareCommands
//! generation, and TabComplete responses.

use std::collections::HashMap;

/// Argument type for a command parameter.
///
/// Determines how the argument is parsed, validated, and presented
/// in client-side tab-completion (Brigadier tree).
#[derive(Debug, Clone)]
pub enum Arg {
    // --- Brigadier built-in parsers ---
    /// Boolean (true/false). Parser ID 0.
    Boolean,
    /// 64-bit floating point number. Parser ID 2.
    Double,
    /// 64-bit integer. Parser ID 3.
    Integer,
    /// Free-form single-word string. Parser ID 5, mode SINGLE_WORD.
    String,

    // --- Minecraft-specific parsers ---
    /// Entity selector (@a, @p, @r, @e, @s) or player name. Parser ID 6.
    Entity,
    /// Game profile (player name with tab-completion). Parser ID 7.
    GameProfile,
    /// Block position (integer coordinates, supports ~). Parser ID 42.
    BlockPos,
    /// Column position (x z integers). Parser ID 43.
    ColumnPos,
    /// 3D coordinates (supports ~ and ^). Parser ID 40.
    Vec3,
    /// 2D coordinates (x z, supports ~ and ^). Parser ID 41.
    Vec2,
    /// Block state (e.g., `stone`, `oak_planks[axis=x]`). Parser ID 44.
    BlockState,
    /// Item stack (e.g., `diamond_sword{Damage:10}`). Parser ID 46.
    ItemStack,
    /// Chat message (like GreedyString but with @mention support). Parser ID 48.
    Message,
    /// JSON text component. Parser ID 10.
    Component,
    /// Resource location (namespace:path). Parser ID 35.
    ResourceLocation,
    /// UUID. Parser ID 11.
    Uuid,
    /// Yaw and pitch rotation. Parser ID 39.
    Rotation,

    // --- Basalt extensions ---
    /// Fixed set of choices with tab-completion. Uses string parser
    /// with `minecraft:ask_server` suggestions.
    Options(Vec<std::string::String>),
    /// Player name — tab-completes with connected player names.
    /// Uses `minecraft:game_profile` parser (ID 7).
    Player,
}

/// Validation behavior for an argument.
///
/// Controls whether the framework validates the argument before
/// calling the handler, and what error message is shown on failure.
#[derive(Debug, Clone)]
pub enum Validation {
    /// Framework validates and sends a default error message.
    Auto,
    /// Framework validates and sends the custom error message.
    Custom(std::string::String),
    /// No validation — tab-completion still works, but the handler
    /// receives the raw value and manages errors itself.
    Disabled,
}

/// A declared command argument.
#[derive(Debug, Clone)]
pub struct CommandArg {
    /// Argument name shown in the client UI and used as a key.
    pub name: std::string::String,
    /// The argument type (determines parsing and Brigadier node).
    pub arg_type: Arg,
    /// Validation behavior.
    pub validation: Validation,
    /// Whether this argument is required.
    pub required: bool,
}

/// A parsed argument value.
#[derive(Debug, Clone, PartialEq)]
pub enum ArgValue {
    /// A string value.
    String(std::string::String),
    /// A parsed integer.
    Integer(i64),
    /// A parsed double.
    Double(f64),
    /// A parsed boolean.
    Boolean(bool),
    /// Three f64 coordinates (x, y, z).
    Vec3(f64, f64, f64),
    /// Three i32 coordinates (x, y, z).
    BlockPos(i32, i32, i32),
}

/// Parsed command arguments accessible by name.
///
/// Built by the framework after validating the raw argument string
/// against the command's declared arguments.
#[derive(Debug)]
pub struct CommandArgs {
    values: HashMap<std::string::String, ArgValue>,
    raw: std::string::String,
}

impl CommandArgs {
    /// Creates a new empty argument map.
    pub fn new(raw: std::string::String) -> Self {
        Self {
            values: HashMap::new(),
            raw,
        }
    }

    /// Inserts a parsed value.
    pub fn insert(&mut self, name: std::string::String, value: ArgValue) {
        self.values.insert(name, value);
    }

    /// Gets a string argument by name.
    pub fn get_string(&self, name: &str) -> Option<&str> {
        match self.values.get(name) {
            Some(ArgValue::String(s)) => Some(s),
            _ => None,
        }
    }

    /// Gets an integer argument by name.
    pub fn get_integer(&self, name: &str) -> Option<i64> {
        match self.values.get(name) {
            Some(ArgValue::Integer(v)) => Some(*v),
            _ => None,
        }
    }

    /// Gets a double argument by name.
    pub fn get_double(&self, name: &str) -> Option<f64> {
        match self.values.get(name) {
            Some(ArgValue::Double(v)) => Some(*v),
            _ => None,
        }
    }

    /// Gets a boolean argument by name.
    pub fn get_bool(&self, name: &str) -> Option<bool> {
        match self.values.get(name) {
            Some(ArgValue::Boolean(v)) => Some(*v),
            _ => None,
        }
    }

    /// Gets a Vec3 argument by name (x, y, z as f64).
    pub fn get_vec3(&self, name: &str) -> Option<(f64, f64, f64)> {
        match self.values.get(name) {
            Some(ArgValue::Vec3(x, y, z)) => Some((*x, *y, *z)),
            _ => None,
        }
    }

    /// Gets a BlockPos argument by name (x, y, z as i32).
    pub fn get_block_pos(&self, name: &str) -> Option<(i32, i32, i32)> {
        match self.values.get(name) {
            Some(ArgValue::BlockPos(x, y, z)) => Some((*x, *y, *z)),
            _ => None,
        }
    }

    /// Returns the raw argument string before parsing.
    pub fn raw(&self) -> &str {
        &self.raw
    }
}

impl Arg {
    /// Returns how many tokens this argument type consumes.
    ///
    /// Vec3 and BlockPos consume 3 tokens, Vec2/ColumnPos/Rotation consume 2,
    /// Message is greedy (0 means "consume all remaining"), everything else is 1.
    pub fn token_count(&self) -> usize {
        match self {
            Arg::Vec3 | Arg::BlockPos => 3,
            Arg::Vec2 | Arg::ColumnPos | Arg::Rotation => 2,
            Arg::Message => 0, // greedy — consumes the rest
            _ => 1,
        }
    }
}

/// Parses a raw argument string, trying variants if defined.
///
/// If `variants` is non-empty, tries each variant in order and
/// returns the first successful parse. If all fail, returns the
/// error from the last variant.
pub fn parse_command_args(
    raw: &str,
    schema: &[CommandArg],
    variants: &[Vec<CommandArg>],
) -> Result<CommandArgs, std::string::String> {
    if variants.is_empty() {
        return parse_args(raw, schema);
    }

    // Sort variants by total token count descending — most specific
    // (most tokens consumed) first. This ensures "10 64 -5" matches
    // Vec3 before matching as a Player name.
    let mut sorted: Vec<&Vec<CommandArg>> = variants.iter().collect();
    sorted.sort_by(|a, b| {
        let count_a: usize = a.iter().map(|arg| arg.arg_type.token_count()).sum();
        let count_b: usize = b.iter().map(|arg| arg.arg_type.token_count()).sum();
        count_b.cmp(&count_a)
    });

    let mut last_err = String::new();
    for variant in sorted {
        match parse_args(raw, variant) {
            Ok(args) => return Ok(args),
            Err(e) => last_err = e,
        }
    }
    Err(last_err)
}

/// Parses a raw argument string against declared arguments.
pub fn parse_args(raw: &str, schema: &[CommandArg]) -> Result<CommandArgs, std::string::String> {
    let tokens: Vec<&str> = raw.split_whitespace().collect();
    let mut args = CommandArgs::new(raw.to_string());

    let required_count = schema.iter().filter(|a| a.required).count();
    if tokens.len() < required_count {
        let names: Vec<&str> = schema.iter().map(|a| a.name.as_str()).collect();
        let usage = names
            .iter()
            .map(|n| format!("<{n}>"))
            .collect::<Vec<_>>()
            .join(" ");
        return Err(format!("Usage: {usage}"));
    }

    let mut tok = 0; // current token position

    for arg_def in schema {
        // Message consumes everything from this position onward
        if matches!(arg_def.arg_type, Arg::Message) {
            let remainder: String = tokens[tok..].join(" ");
            if remainder.is_empty() && arg_def.required {
                return Err(format!("Missing required argument: {}", arg_def.name));
            }
            if !remainder.is_empty() {
                args.insert(arg_def.name.clone(), ArgValue::String(remainder));
            }
            break;
        }

        let count = arg_def.arg_type.token_count();

        if tok >= tokens.len() {
            if arg_def.required {
                return Err(format!("Missing required argument: {}", arg_def.name));
            }
            continue;
        }

        // Multi-token types: parse into typed values
        if count > 1 {
            if tok + count > tokens.len() {
                if arg_def.required {
                    return Err(format!(
                        "Not enough values for '{}' (expected {count})",
                        arg_def.name
                    ));
                }
                continue;
            }
            let value = match &arg_def.arg_type {
                Arg::Vec3 => {
                    let x = tokens[tok]
                        .parse::<f64>()
                        .map_err(|_| format!("Invalid coordinate for '{}'", arg_def.name))?;
                    let y = tokens[tok + 1]
                        .parse::<f64>()
                        .map_err(|_| format!("Invalid coordinate for '{}'", arg_def.name))?;
                    let z = tokens[tok + 2]
                        .parse::<f64>()
                        .map_err(|_| format!("Invalid coordinate for '{}'", arg_def.name))?;
                    ArgValue::Vec3(x, y, z)
                }
                Arg::BlockPos => {
                    let x = tokens[tok]
                        .parse::<i32>()
                        .map_err(|_| format!("Invalid block coordinate for '{}'", arg_def.name))?;
                    let y = tokens[tok + 1]
                        .parse::<i32>()
                        .map_err(|_| format!("Invalid block coordinate for '{}'", arg_def.name))?;
                    let z = tokens[tok + 2]
                        .parse::<i32>()
                        .map_err(|_| format!("Invalid block coordinate for '{}'", arg_def.name))?;
                    ArgValue::BlockPos(x, y, z)
                }
                _ => {
                    // Vec2, ColumnPos, Rotation: store as joined string for now
                    ArgValue::String(tokens[tok..tok + count].join(" "))
                }
            };
            args.insert(arg_def.name.clone(), value);
            tok += count;
            continue;
        }

        let token = tokens[tok];
        tok += 1;

        if matches!(arg_def.validation, Validation::Disabled) {
            args.insert(arg_def.name.clone(), ArgValue::String(token.to_string()));
            continue;
        }

        match &arg_def.arg_type {
            Arg::String
            | Arg::Player
            | Arg::Entity
            | Arg::GameProfile
            | Arg::BlockState
            | Arg::ItemStack
            | Arg::Component
            | Arg::ResourceLocation
            | Arg::Uuid => {
                args.insert(arg_def.name.clone(), ArgValue::String(token.to_string()));
            }
            Arg::Integer => match token.parse::<i64>() {
                Ok(v) => {
                    args.insert(arg_def.name.clone(), ArgValue::Integer(v));
                }
                Err(_) => {
                    return Err(match &arg_def.validation {
                        Validation::Custom(msg) => msg.clone(),
                        _ => format!("Expected an integer for '{}'", arg_def.name),
                    });
                }
            },
            Arg::Double => match token.parse::<f64>() {
                Ok(v) => {
                    args.insert(arg_def.name.clone(), ArgValue::Double(v));
                }
                Err(_) => {
                    return Err(match &arg_def.validation {
                        Validation::Custom(msg) => msg.clone(),
                        _ => format!("Expected a number for '{}'", arg_def.name),
                    });
                }
            },
            Arg::Options(choices) => {
                if choices.iter().any(|c| c == token) {
                    args.insert(arg_def.name.clone(), ArgValue::String(token.to_string()));
                } else {
                    return Err(match &arg_def.validation {
                        Validation::Custom(msg) => msg.clone(),
                        _ => {
                            let opts = choices.join(", ");
                            format!("Invalid '{}'. Options: {opts}", arg_def.name)
                        }
                    });
                }
            }
            Arg::Boolean => match token {
                "true" => {
                    args.insert(arg_def.name.clone(), ArgValue::Boolean(true));
                }
                "false" => {
                    args.insert(arg_def.name.clone(), ArgValue::Boolean(false));
                }
                _ => {
                    return Err(match &arg_def.validation {
                        Validation::Custom(msg) => msg.clone(),
                        _ => format!("Expected true/false for '{}'", arg_def.name),
                    });
                }
            },
            // Multi-token and greedy types handled above
            Arg::Vec3
            | Arg::Vec2
            | Arg::BlockPos
            | Arg::ColumnPos
            | Arg::Rotation
            | Arg::Message => {
                unreachable!()
            }
        }
    }

    Ok(args)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn arg(name: &str, arg_type: Arg) -> CommandArg {
        CommandArg {
            name: name.to_string(),
            arg_type,
            validation: Validation::Auto,
            required: true,
        }
    }

    #[test]
    fn parse_double_args() {
        let schema = vec![
            arg("x", Arg::Double),
            arg("y", Arg::Double),
            arg("z", Arg::Double),
        ];
        let result = parse_args("10.5 64.0 -5.0", &schema).unwrap();
        assert_eq!(result.get_double("x"), Some(10.5));
        assert_eq!(result.get_double("y"), Some(64.0));
        assert_eq!(result.get_double("z"), Some(-5.0));
    }

    #[test]
    fn parse_integer_args() {
        let schema = vec![arg("count", Arg::Integer)];
        let result = parse_args("42", &schema).unwrap();
        assert_eq!(result.get_integer("count"), Some(42));
    }

    #[test]
    fn parse_string_arg() {
        let schema = vec![arg("name", Arg::String)];
        let result = parse_args("Steve", &schema).unwrap();
        assert_eq!(result.get_string("name"), Some("Steve"));
    }

    #[test]
    fn parse_options_valid() {
        let schema = vec![arg(
            "mode",
            Arg::Options(vec!["survival".into(), "creative".into()]),
        )];
        let result = parse_args("creative", &schema).unwrap();
        assert_eq!(result.get_string("mode"), Some("creative"));
    }

    #[test]
    fn parse_options_invalid() {
        let schema = vec![arg(
            "mode",
            Arg::Options(vec!["survival".into(), "creative".into()]),
        )];
        let err = parse_args("hardcore", &schema).unwrap_err();
        assert!(err.contains("Invalid 'mode'"));
    }

    #[test]
    fn parse_options_custom_error() {
        let schema = vec![CommandArg {
            name: "mode".into(),
            arg_type: Arg::Options(vec!["survival".into(), "creative".into()]),
            validation: Validation::Custom("Nope, bad mode".into()),
            required: true,
        }];
        let err = parse_args("hardcore", &schema).unwrap_err();
        assert_eq!(err, "Nope, bad mode");
    }

    #[test]
    fn parse_double_invalid() {
        let schema = vec![arg("x", Arg::Double)];
        let err = parse_args("abc", &schema).unwrap_err();
        assert!(err.contains("Expected a number"));
    }

    #[test]
    fn parse_too_few_args() {
        let schema = vec![
            arg("x", Arg::Double),
            arg("y", Arg::Double),
            arg("z", Arg::Double),
        ];
        let err = parse_args("10.5", &schema).unwrap_err();
        assert!(err.contains("Usage:"));
    }

    #[test]
    fn parse_validation_disabled() {
        let schema = vec![CommandArg {
            name: "value".into(),
            arg_type: Arg::Double,
            validation: Validation::Disabled,
            required: true,
        }];
        let result = parse_args("abc", &schema).unwrap();
        assert_eq!(result.get_string("value"), Some("abc"));
    }

    #[test]
    fn parse_optional_arg_missing() {
        let schema = vec![CommandArg {
            name: "target".into(),
            arg_type: Arg::String,
            validation: Validation::Auto,
            required: false,
        }];
        let result = parse_args("", &schema).unwrap();
        assert_eq!(result.get_string("target"), None);
    }

    #[test]
    fn parse_greedy_string() {
        let schema = vec![arg("msg", Arg::Message)];
        let result = parse_args("hello world foo", &schema).unwrap();
        assert_eq!(result.get_string("msg"), Some("hello world foo"));
    }

    #[test]
    fn parse_boolean_valid() {
        let schema = vec![arg("flag", Arg::Boolean)];
        let result = parse_args("true", &schema).unwrap();
        assert_eq!(result.get_bool("flag"), Some(true));

        let result = parse_args("false", &schema).unwrap();
        assert_eq!(result.get_bool("flag"), Some(false));
    }

    #[test]
    fn parse_boolean_invalid() {
        let schema = vec![arg("flag", Arg::Boolean)];
        let err = parse_args("maybe", &schema).unwrap_err();
        assert!(err.contains("Expected true/false"));
    }

    #[test]
    fn parse_player_arg() {
        let schema = vec![arg("target", Arg::Player)];
        let result = parse_args("Steve", &schema).unwrap();
        assert_eq!(result.get_string("target"), Some("Steve"));
    }

    #[test]
    fn parse_variants_first_match() {
        let v1 = vec![arg("x", Arg::Double), arg("y", Arg::Double)];
        let v2 = vec![arg("name", Arg::String)];
        let result = parse_command_args("10.5 20.0", &[], &[v1, v2]).unwrap();
        assert_eq!(result.get_double("x"), Some(10.5));
    }

    #[test]
    fn parse_variants_second_match() {
        let v1 = vec![arg("x", Arg::Double), arg("y", Arg::Double)];
        let v2 = vec![arg("name", Arg::Player)];
        let result = parse_command_args("Steve", &[], &[v1, v2]).unwrap();
        assert_eq!(result.get_string("name"), Some("Steve"));
    }

    #[test]
    fn raw_preserved() {
        let schema = vec![arg("msg", Arg::String)];
        let result = parse_args("hello world", &schema).unwrap();
        assert_eq!(result.raw(), "hello world");
    }

    #[test]
    fn parse_vec3_typed() {
        let schema = vec![arg("pos", Arg::Vec3)];
        let result = parse_args("10.5 64.0 -5.0", &schema).unwrap();
        assert_eq!(result.get_vec3("pos"), Some((10.5, 64.0, -5.0)));
        assert_eq!(result.get_string("pos"), None); // not stored as string
    }

    #[test]
    fn parse_vec3_invalid() {
        let schema = vec![arg("pos", Arg::Vec3)];
        let err = parse_args("10.5 abc -5.0", &schema).unwrap_err();
        assert!(err.contains("Invalid coordinate"));
    }

    #[test]
    fn parse_block_pos_typed() {
        let schema = vec![arg("pos", Arg::BlockPos)];
        let result = parse_args("10 64 -5", &schema).unwrap();
        assert_eq!(result.get_block_pos("pos"), Some((10, 64, -5)));
    }

    #[test]
    fn token_count_method() {
        assert_eq!(Arg::Vec3.token_count(), 3);
        assert_eq!(Arg::BlockPos.token_count(), 3);
        assert_eq!(Arg::Vec2.token_count(), 2);
        assert_eq!(Arg::Rotation.token_count(), 2);
        assert_eq!(Arg::Message.token_count(), 0);
        assert_eq!(Arg::String.token_count(), 1);
        assert_eq!(Arg::Boolean.token_count(), 1);
    }
}