rift-plugin 0.2.0

Guest SDK for Rift WebAssembly plugins (rift:plugin@0.2.0)
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
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
//! Guest SDK for Rift WebAssembly plugins.
//!
//! A Rift plugin is a WebAssembly component built for `wasm32-wasip2` against
//! the `plugin` world of `rift:plugin@0.2.0`. This crate ships that WIT,
//! generates the bindings and wraps them, so a plugin is an ordinary
//! `cdylib` crate:
//!
//! ```toml
//! [lib]
//! crate-type = ["cdylib"]
//!
//! [dependencies]
//! rift-plugin = "0.2"
//! ```
//!
//! ```no_run
//! use rift_plugin::{Action, CommandSpec, Context, Hook, Plugin, Registration, SuggestKind};
//!
//! #[derive(Default)]
//! struct Greeter;
//!
//! impl Plugin for Greeter {
//!     fn init(&mut self, _config: &str) -> Result<Registration, String> {
//!         Ok(Registration::new()
//!             .command(
//!                 CommandSpec::new("greet")
//!                     .alias("hi")
//!                     .permission("greeter.use")
//!                     .suggest(SuggestKind::Players),
//!             )
//!             .hooks([Hook::Command]))
//!     }
//!
//!     fn command(&mut self, ctx: Context) -> Action {
//!         Action::message(format!("Hi, {}!", ctx.name))
//!     }
//! }
//!
//! rift_plugin::export!(Greeter);
//! ```
//!
//! Build it with `cargo build --release --target wasm32-wasip2`. Rust's
//! linker for that target emits a component directly; no `cargo component`
//! or `wasm-tools component new` step is needed.
//!
//! # State
//!
//! The component model calls exports as free functions, so the SDK keeps the
//! single plugin instance for you: [`export!`] stores one value of your type
//! in a thread-local, created with [`Default`] right before
//! [`Plugin::init`], and every hook receives it as `&mut self`. Keep plugin
//! state in your struct's fields. This is sound because guests are
//! single-threaded and the host never calls one instance concurrently or
//! re-entrantly. [`Plugin::shutdown`] runs last and the instance is dropped
//! after it returns.
//!
//! # Hooks
//!
//! Every [`Plugin`] method has a default that does nothing (`continue`,
//! `default`, `none` or an empty list). List the hooks you implement in
//! [`Registration::hooks`] so the host skips the rest. An empty list delivers
//! every hook except [`Hook::Chat`] and [`Hook::Kick`], which are only ever
//! delivered when listed. [`Plugin::dialog`] and [`Plugin::job_done`] need no
//! entry.
//!
//! The decision hooks answer with an [`Action`]; each accepts a subset:
//!
//! | Hook | Accepts |
//! | --- | --- |
//! | `login`, `before_transfer`, `chat` | `Continue`, `deny` |
//! | `initial_server`, `kick` | `Continue`, `deny`, `server` |
//! | `command` | `Continue`, `message`, `server`, `queue`, `LeaveQueue` |
//!
//! # Host API
//!
//! [`players`], [`store`], [`permissions`], [`bus`], [`servers`], [`timers`],
//! [`background`], [`log`] and [`meta`] mirror the WIT interfaces of the same
//! names. Errors are the host's message as a `String`. [`log`] also installs
//! a [`::log`] logger before `init`, so `log::info!` and friends reach Rift's
//! log. Plugin configuration arrives as JSON; decode it with [`config()`].
//!
//! WASI 0.2 (`std::fs` on the granted directories, clocks, random) works
//! through the standard library. A `wasi:http` helper is not provided.
//!
//! # Text
//!
//! Everything a player reads is a [`Text`]: [`Text::Plain`], shown exactly
//! as written, or [`Text::Json`], a JSON text component with colours, line
//! breaks, hover text and click events. Every function and constructor that
//! shows text takes `impl Into<Text>`:
//!
//! - `&str` and `String` become plain text;
//! - the [`text`] builders ([`text::mini`] for Rift markup, [`text::legacy`]
//!   for `&c` codes, [`text::Component`] field by field) and a
//!   [`serde_json::Value`] become JSON text.
//!
//! ```no_run
//! use rift_plugin::{Action, TitleSpec, players, text};
//! use serde_json::json;
//!
//! players::message("Steve", "Shown <exactly> as written").ok();
//!
//! let welcome = text::mini("<gold>Welcome, <player>!</gold> <gray><click:run_command:/spawn>[Spawn]")
//!     .arg("player", "Steve");
//! players::message("Steve", welcome).ok();
//! players::title(
//!     "Steve",
//!     &TitleSpec::new(text::mini("<green>Lobby")).subtitle(text::legacy("&7Have fun")),
//! )
//! .ok();
//!
//! let reply = Action::message(
//!     text::Component::text("[Accept]")
//!         .color("green")
//!         .bold()
//!         .run_command("/party accept Alex")
//!         .hover_text("Join Alex's party"),
//! );
//! let banned = Action::deny(json!({
//!     "text": "You are banned\n", "color": "red",
//!     "extra": [{"text": "Reason: spam", "color": "gray"}],
//! }));
//! ```
//!
//! Rift spells hover and click events the way each player's client reads
//! them, so either the 1.21.5+ form (`click_event`, `hover_event`) or the
//! older one (`clickEvent`, `hoverEvent`) works for every client. Markup is
//! only ever read from an explicit `{"mini": ...}` object, which
//! [`text::mini`] writes; a string is always shown as written, so text from
//! players can be passed safely as plain text or as a markup argument.
//!
//! # Chat and kicks
//!
//! [`Plugin::chat`] sees every chat message, and every command that reaches
//! the backend, before the backend does, and may drop it. [`Plugin::kick`]
//! decides what happens to a player a backend kicked. Both are delivered
//! only to a registration that lists them:
//!
//! ```no_run
//! use rift_plugin::{Action, ChatAttempt, ChatKind, Context, Hook, Plugin, Registration};
//!
//! #[derive(Default)]
//! struct Mute {
//!     muted: Vec<String>,
//! }
//!
//! impl Plugin for Mute {
//!     fn init(&mut self, _config: &str) -> Result<Registration, String> {
//!         Ok(Registration::new().hooks([Hook::Chat, Hook::Kick]))
//!     }
//!
//!     fn chat(&mut self, attempt: ChatAttempt) -> Action {
//!         if attempt.kind == ChatKind::Message && self.muted.contains(&attempt.ctx.uuid) {
//!             return Action::deny("You are muted.");
//!         }
//!         Action::Continue
//!     }
//!
//!     fn kick(&mut self, ctx: Context) -> Action {
//!         match ctx.reason.as_deref() {
//!             Some(reason) if reason.contains("restarting") => Action::server("lobby"),
//!             _ => Action::Continue,
//!         }
//!     }
//! }
//!
//! rift_plugin::export!(Mute);
//! ```
//!
//! Rift asks a plugin that lists [`Hook::Chat`] about every message of every
//! player. Dropping one signed message breaks the player's signature chain,
//! so unless the proxy sets `authentication.signed_chat = false`, the first
//! deny costs that player their chat signing until they reconnect.
//!
//! # Background work
//!
//! A plugin runs one call at a time, so a slow lookup in `login` would keep
//! every other hook waiting. The [`background`] module moves such work to
//! worker instances (manifest `[background] workers = N`): the hook defers
//! its answer, queues a job and returns; a worker runs [`Plugin::work`];
//! [`Plugin::job_done`] receives the result and gives the answer.
//!
//! ```no_run
//! use rift_plugin::{Action, Context, Hook, Plugin, Registration, background};
//! use std::collections::HashMap;
//!
//! #[derive(Default)]
//! struct Bans {
//!     /// Job handle to the ticket of the login that waits for it.
//!     waiting: HashMap<u64, u64>,
//! }
//!
//! impl Plugin for Bans {
//!     fn init(&mut self, _config: &str) -> Result<Registration, String> {
//!         Ok(Registration::new().hooks([Hook::Login]))
//!     }
//!
//!     fn login(&mut self, ctx: Context) -> Action {
//!         let Ok(ticket) = background::defer() else {
//!             return Action::deny("Try again in a moment.");
//!         };
//!         match background::run(ctx.uuid.as_bytes()) {
//!             Ok(job) => {
//!                 self.waiting.insert(job, ticket);
//!             }
//!             Err(_) => {
//!                 let _ = background::resolve(ticket, Action::deny("Try again in a moment."));
//!             }
//!         }
//!         // Ignored: the answer is the one given to `resolve`.
//!         Action::Continue
//!     }
//!
//!     fn job_done(&mut self, job: u64, outcome: Result<Vec<u8>, String>) {
//!         let Some(ticket) = self.waiting.remove(&job) else { return };
//!         let action = match outcome {
//!             Ok(reason) if reason.is_empty() => Action::Continue,
//!             Ok(reason) => Action::deny(String::from_utf8_lossy(&reason).into_owned()),
//!             Err(_) => Action::deny("Try again in a moment."),
//!         };
//!         let _ = background::resolve(ticket, action);
//!     }
//!
//!     // Runs on a worker: another instance, with its own state.
//!     fn work(&mut self, uuid: Vec<u8>) -> Result<Vec<u8>, String> {
//!         let uuid = String::from_utf8(uuid).map_err(|error| error.to_string())?;
//!         // The slow part; an empty answer means "not banned".
//!         Ok(std::fs::read(format!("/data/bans/{uuid}")).unwrap_or_default())
//!     }
//! }
//!
//! rift_plugin::export!(Bans);
//! ```
//!
//! A worker is a separate instance of the same component with its own
//! memory: its state is its own `Default` value, [`Plugin::init`] never runs
//! there, and it receives no hooks. [`Plugin::work_init`] runs once per
//! worker before its first job, with the plugin's configuration. The
//! deferred hook's deadline keeps running while the job does.
//!
//! # Dialogs
//!
//! [`players::show_dialog`] shows a dialog (Minecraft 1.21.6+) in the
//! vanilla JSON format. A button whose `custom` or `dynamic/custom` action
//! has an `id` without a namespace comes back to [`Plugin::dialog`]:
//!
//! ```no_run
//! use rift_plugin::{Context, DialogResponse, Plugin, players};
//! use serde_json::json;
//!
//! #[derive(Default)]
//! struct Rules;
//!
//! impl Plugin for Rules {
//!     fn join(&mut self, ctx: Context) {
//!         let _ = players::show_dialog(&ctx.uuid, &json!({
//!             "type": "confirmation",
//!             "title": "Server rules",
//!             "body": "Be nice.",
//!             "yes": {"label": "Accept", "action": {"type": "custom", "id": "accept"}},
//!             "no": {"label": "Leave", "action": {"type": "custom", "id": "leave"}},
//!         }));
//!     }
//!
//!     fn dialog(&mut self, response: DialogResponse) {
//!         if response.action == "leave" {
//!             let _ = players::kick(&response.ctx.uuid, "You declined the rules.");
//!         }
//!     }
//! }
//! # rift_plugin::export!(Rules);
//! ```

#![warn(missing_docs)]

/// The raw generated bindings for the `plugin` world, including WASI.
///
/// Prefer the wrappers at the crate root; this is an escape hatch.
#[allow(missing_docs, clippy::all)]
pub mod bindings {
    wit_bindgen::generate!({
        path: "wit",
        world: "rift:plugin/plugin@0.2.0",
        pub_export_macro: true,
        export_macro_name: "__export_rift_plugin",
        default_bindings_module: "rift_plugin::bindings",
        generate_all,
    });
}

pub use bindings::rift::plugin::types::{
    BossBarSpec, BusMessage, ChatAttempt, ChatKind, CommandSpec, Connection, Context,
    DialogResponse, Hook, HttpRequest, HttpResponse, Level, Ping, PlayerInfo, PlayerRecord,
    ProfileProperty, Registration, RiftEvent, RouteDecision, StatusOverride, SuggestKind,
    Suggestion, Text, TitleSpec,
};

/// The answer to a decision hook: the contract's `decision` variant.
///
/// Each hook accepts a subset; an answer outside it counts as a failed call:
/// - `login`, `before_transfer`, `chat`: `Continue`, [`deny`](Action::deny)
/// - `initial_server`, `kick`: `Continue`, [`deny`](Action::deny),
///   [`server`](Action::server)
/// - `command`: `Continue`, [`message`](Action::message),
///   [`server`](Action::server), [`queue`](Action::queue), `LeaveQueue`
pub type Action = bindings::rift::plugin::types::Decision;

use serde::de::DeserializeOwned;

/// A Rift plugin. Implement the hooks you need and pass the type to
/// [`export!`].
///
/// The instance is created with [`Default`] before [`Plugin::init`]; see the
/// [crate documentation](crate#state) for how state is kept.
#[allow(unused_variables)]
pub trait Plugin: Default + 'static {
    /// Called once per instance with the plugin's configuration as JSON
    /// (`{}` without one). Create timers and bus subscriptions here.
    fn init(&mut self, config: &str) -> Result<Registration, String> {
        Ok(Registration::new())
    }

    /// The configuration changed and the manifest sets `hot_reload = true`.
    fn reload(&mut self, config: &str) -> Result<(), String> {
        Ok(())
    }

    /// The instance is about to be dropped.
    fn shutdown(&mut self, reason: &str) {}

    /// A TCP connection was accepted, before any bytes are read.
    fn route(&mut self, connection: Connection) -> RouteDecision {
        RouteDecision::Default
    }

    /// A player authenticated. Accepts `continue` and `deny`.
    fn login(&mut self, ctx: Context) -> Action {
        Action::Continue
    }

    /// Choose the first backend. Accepts `continue`, `deny` and `server`.
    fn initial_server(&mut self, ctx: Context) -> Action {
        Action::Continue
    }

    /// A transfer is about to happen. Accepts `continue` and `deny`.
    fn before_transfer(&mut self, ctx: Context) -> Action {
        Action::Continue
    }

    /// A registered command ran; `ctx.command` is its name, also when an
    /// alias was typed, and `ctx.args` the text after it. Accepts
    /// `continue`, `message`, `server`, `queue` and `leave-queue`.
    ///
    /// For a command registered with [`CommandSpec::console`], `ctx.console`
    /// tells that the operator console runs it: there is no player then
    /// (`ctx.uuid` is empty and `ctx.name` is `CONSOLE`), and a `message`
    /// answer is shown to the operator.
    fn command(&mut self, ctx: Context) -> Action {
        Action::Continue
    }

    /// Complete an argument of a command registered with
    /// [`SuggestKind::Dynamic`].
    fn suggest(&mut self, ctx: Context) -> Vec<Suggestion> {
        Vec::new()
    }

    /// A server-list ping; return the fields to replace.
    fn status(&mut self, ping: Ping) -> Option<StatusOverride> {
        None
    }

    /// An authenticated request to `/ext` or `/ext/*` on the web server.
    fn http(&mut self, request: HttpRequest) -> Option<HttpResponse> {
        None
    }

    /// A player sent a chat message, or a command that neither Rift nor a
    /// plugin owns, and the backend has not seen it yet. Accepts `continue`,
    /// which lets it through unchanged, and `deny`, which drops it and shows
    /// the player the text.
    ///
    /// Delivered only when [`Registration::hooks`] lists [`Hook::Chat`]; see
    /// the [crate documentation](crate#chat-and-kicks) for what that
    /// requires of the proxy. For a command, `attempt.ctx.command` is the
    /// root name and `attempt.ctx.args` the rest.
    fn chat(&mut self, attempt: ChatAttempt) -> Action {
        Action::Continue
    }

    /// A backend kicked a player in play: `ctx.server` is the backend and
    /// `ctx.reason` its reason without formatting. `continue` leaves it to
    /// `network.on_kick`, `deny` disconnects the player with the text and
    /// `server` moves them there.
    ///
    /// Delivered only when [`Registration::hooks`] lists [`Hook::Kick`].
    fn kick(&mut self, ctx: Context) -> Action {
        Action::Continue
    }

    /// A player joined.
    fn join(&mut self, ctx: Context) {}

    /// A transfer finished (see `ctx.success`).
    fn after_transfer(&mut self, ctx: Context) {}

    /// A session closed (see `ctx.reason`).
    fn disconnect(&mut self, ctx: Context) {}

    /// A message arrived on a subscription made with [`bus::subscribe`].
    fn message(&mut self, message: BusMessage) {}

    /// A timer made with [`timers::every`] or [`timers::after`] fired.
    fn timer(&mut self, handle: u64) {}

    /// A Rift event (`rift.events.*`).
    fn event(&mut self, event: RiftEvent) {}

    /// A player clicked a plugin action of a dialog this plugin showed with
    /// [`players::show_dialog`]. Delivered without being listed in
    /// [`Registration::hooks`].
    fn dialog(&mut self, response: DialogResponse) {}

    /// A job started with [`background::run`] finished: `handle` is the one
    /// `run` returned and `outcome` what [`Plugin::work`] returned on the
    /// worker, or why the job failed. Delivered without being listed in
    /// [`Registration::hooks`].
    fn job_done(&mut self, handle: u64, outcome: Result<Vec<u8>, String>) {}

    /// Background workers only: called once per worker before its first
    /// job, with the plugin's configuration as JSON.
    ///
    /// A worker is a separate instance of the component. `self` is a fresh
    /// [`Default`] value that only `work_init` and [`Plugin::work`] ever
    /// see; [`Plugin::init`] is never called on it.
    fn work_init(&mut self, config: &str) -> Result<(), String> {
        Ok(())
    }

    /// Background workers only: one job queued with [`background::run`].
    /// It may block; the plugin's hooks keep running meanwhile. The result
    /// reaches [`Plugin::job_done`] on the plugin's main instance.
    fn work(&mut self, payload: Vec<u8>) -> Result<Vec<u8>, String> {
        Err("this plugin has no background work".into())
    }
}

/// Exports a [`Plugin`] implementation as the component's
/// `rift:plugin/handler` interface. Use it exactly once per plugin crate.
///
/// ```ignore
/// rift_plugin::export!(MyPlugin);
/// ```
#[macro_export]
macro_rules! export {
    ($plugin:ty) => {
        #[doc(hidden)]
        type __RiftPluginExport = $crate::__private::Adapter<$plugin>;
        $crate::bindings::__export_rift_plugin!(__RiftPluginExport with_types_in $crate::bindings);
    };
}

/// Decodes the JSON configuration `init`, `reload` and `work_init` receive.
///
/// The host passes `{}` when the plugin has no configuration, so mark
/// optional fields with `#[serde(default)]`.
pub fn config<T: DeserializeOwned>(json: &str) -> Result<T, String> {
    serde_json::from_str(json).map_err(|error| format!("invalid plugin configuration: {error}"))
}

impl Text {
    /// Plain text of 1..=1024 bytes, shown exactly as written. The same as
    /// converting a `&str` or `String`.
    pub fn plain(text: impl Into<String>) -> Self {
        Self::Plain(text.into())
    }

    /// A JSON text component of at most 32 KiB that is already JSON text.
    /// The [`text`] builders and [`serde_json::Value`] convert into this
    /// with `into()`.
    pub fn json(json: impl Into<String>) -> Self {
        Self::Json(json.into())
    }
}

impl From<&str> for Text {
    /// [`Text::Plain`].
    fn from(text: &str) -> Self {
        Self::Plain(text.to_owned())
    }
}

impl From<String> for Text {
    /// [`Text::Plain`].
    fn from(text: String) -> Self {
        Self::Plain(text)
    }
}

impl From<&String> for Text {
    /// [`Text::Plain`].
    fn from(text: &String) -> Self {
        Self::Plain(text.clone())
    }
}

impl From<serde_json::Value> for Text {
    /// [`Text::Json`]: the value is a JSON text component.
    fn from(component: serde_json::Value) -> Self {
        Self::Json(component.to_string())
    }
}

impl From<&serde_json::Value> for Text {
    /// [`Text::Json`]: the value is a JSON text component.
    fn from(component: &serde_json::Value) -> Self {
        Self::Json(component.to_string())
    }
}

impl PartialEq for Text {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Plain(a), Self::Plain(b)) | (Self::Json(a), Self::Json(b)) => a == b,
            _ => false,
        }
    }
}

impl Registration {
    /// No commands and no hooks, which delivers every hook except
    /// [`Hook::Chat`] and [`Hook::Kick`].
    pub fn new() -> Self {
        Self {
            commands: Vec::new(),
            hooks: Vec::new(),
        }
    }

    /// Registers a command.
    pub fn command(mut self, command: CommandSpec) -> Self {
        self.commands.push(command);
        self
    }

    /// Asks for one more hook to be delivered.
    pub fn hook(mut self, hook: Hook) -> Self {
        self.hooks.push(hook);
        self
    }

    /// Asks for these hooks to be delivered.
    pub fn hooks(mut self, hooks: impl IntoIterator<Item = Hook>) -> Self {
        self.hooks.extend(hooks);
        self
    }
}

impl Default for Registration {
    fn default() -> Self {
        Self::new()
    }
}

impl CommandSpec {
    /// A command without aliases, permission node or suggestions, for
    /// players only. Without a permission every player may see and run it.
    ///
    /// Names are 1 to 64 bytes of `a-z0-9_-`; `server` and `hub` are
    /// reserved.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            aliases: Vec::new(),
            permission: String::new(),
            suggest: SuggestKind::None,
            console: false,
        }
    }

    /// Another name for the command, written like the name. A command has
    /// at most 16; the hooks always see the name in `ctx.command`.
    pub fn alias(mut self, alias: impl Into<String>) -> Self {
        self.aliases.push(alias.into());
        self
    }

    /// More names for the command; see [`CommandSpec::alias`].
    pub fn aliases<S: Into<String>>(mut self, aliases: impl IntoIterator<Item = S>) -> Self {
        self.aliases.extend(aliases.into_iter().map(Into::into));
        self
    }

    /// The permission node a player needs to see and run the command. An
    /// empty node opens the command to every player.
    pub fn permission(mut self, node: impl Into<String>) -> Self {
        self.permission = node.into();
        self
    }

    /// How the command's arguments are completed.
    pub fn suggest(mut self, kind: SuggestKind) -> Self {
        self.suggest = kind;
        self
    }

    /// Operators may run the command from the console (`rift admin plugins
    /// run`); [`Plugin::command`] then sees `ctx.console`.
    pub fn console(mut self) -> Self {
        self.console = true;
        self
    }
}

impl Action {
    /// `deny(reason)`: refuse, and show the player the reason.
    pub fn deny(reason: impl Into<Text>) -> Self {
        Self::Deny(reason.into())
    }

    /// `message(text)`: reply to whoever ran a command.
    pub fn message(text: impl Into<Text>) -> Self {
        Self::Message(text.into())
    }

    /// `server(name)`: send the player to a backend.
    pub fn server(name: impl Into<String>) -> Self {
        Self::Server(name.into())
    }

    /// `queue(name)`: put the player into the queue for a backend.
    pub fn queue(name: impl Into<String>) -> Self {
        Self::Queue(name.into())
    }
}

impl PartialEq for Action {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Continue, Self::Continue) | (Self::LeaveQueue, Self::LeaveQueue) => true,
            (Self::Deny(a), Self::Deny(b)) | (Self::Message(a), Self::Message(b)) => a == b,
            (Self::Server(a), Self::Server(b)) | (Self::Queue(a), Self::Queue(b)) => a == b,
            _ => false,
        }
    }
}

impl DialogResponse {
    /// The player's input values, decoded from `values_json`. They come from
    /// the client: validate them like any player input.
    pub fn values<T: DeserializeOwned>(&self) -> Result<T, String> {
        serde_json::from_str(&self.values_json)
            .map_err(|error| format!("invalid dialog values: {error}"))
    }

    /// The action's `payload` or `additions`, as the plugin wrote it; `None`
    /// when it had none.
    pub fn payload<T: DeserializeOwned>(&self) -> Result<Option<T>, String> {
        self.payload_json
            .as_deref()
            .map(serde_json::from_str)
            .transpose()
            .map_err(|error| format!("invalid dialog payload: {error}"))
    }
}

impl Suggestion {
    /// A suggestion without a tooltip.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            tooltip: None,
        }
    }

    /// The tooltip shown next to the suggestion.
    pub fn tooltip(mut self, tooltip: impl Into<Text>) -> Self {
        self.tooltip = Some(tooltip.into());
        self
    }
}

impl Default for StatusOverride {
    /// Replaces nothing. Set the fields to replace:
    ///
    /// ```
    /// use rift_plugin::{StatusOverride, text};
    ///
    /// let status = StatusOverride {
    ///     motd: Some(text::mini("<gold>Rift</gold>\n<gray>Now with plugins").into()),
    ///     max_players: Some(500),
    ///     ..Default::default()
    /// };
    /// ```
    fn default() -> Self {
        Self {
            motd: None,
            version: None,
            protocol: None,
            online: None,
            max_players: None,
            sample: None,
            favicon: None,
        }
    }
}

impl TitleSpec {
    /// A title with the vanilla times (10 ticks fade in, 70 stay, 20 fade
    /// out).
    pub fn new(title: impl Into<Text>) -> Self {
        Self {
            title: Some(title.into()),
            subtitle: None,
            fade_in: 10,
            stay: 70,
            fade_out: 20,
        }
    }

    /// Only a subtitle, with the vanilla times: the title above it stays
    /// empty.
    pub fn subtitle_only(subtitle: impl Into<Text>) -> Self {
        Self {
            title: None,
            subtitle: Some(subtitle.into()),
            fade_in: 10,
            stay: 70,
            fade_out: 20,
        }
    }

    /// The subtitle.
    pub fn subtitle(mut self, subtitle: impl Into<Text>) -> Self {
        self.subtitle = Some(subtitle.into());
        self
    }

    /// Fade-in, stay and fade-out times in ticks.
    pub fn times(mut self, fade_in: i32, stay: i32, fade_out: i32) -> Self {
        self.fade_in = fade_in;
        self.stay = stay;
        self.fade_out = fade_out;
        self
    }
}

/// The joined players, and what Rift remembers about those who left.
/// `target` is a name, a UUID or a connection id.
///
/// The functions that show text take anything that converts into a
/// [`Text`]: a string for plain text, a [`text`]
/// builder or a [`serde_json::Value`] for a JSON text component. Each
/// returns whether the player was online.
///
/// [`PlayerInfo`] carries what Rift knows about an online
/// player, including `ip`, the profile `properties`, `visible_to`, `locale`
/// (the language the client reported, `None` until the client has sent it:
/// never in [`Plugin::login`], and in
/// [`Plugin::join`] only for 1.20.2 and newer clients)
/// and `language` (the one set with [`set_language`](players::set_language), else `locale`).
///
/// [`lookup`](players::lookup) and [`search`](players::search) answer with a
/// [`PlayerRecord`] for every player who joined at
/// least once, online or not.
pub mod players {
    use crate::Text;
    use crate::bindings::rift::plugin::players as host;
    pub use host::{
        boss_bar, clear_dialog, dialog, get, list, lookup, names, search, set_language, title,
        transfer,
    };

    /// Send a chat message to a player.
    pub fn message(target: &str, text: impl Into<Text>) -> Result<bool, String> {
        host::message(target, &text.into())
    }

    /// Show text above a player's hotbar.
    pub fn action_bar(target: &str, text: impl Into<Text>) -> Result<bool, String> {
        host::action_bar(target, &text.into())
    }

    /// Disconnect a player with a reason.
    pub fn kick(target: &str, reason: impl Into<Text>) -> Result<bool, String> {
        host::kick(target, &reason.into())
    }

    /// Send a chat message to every player. Returns how many received it.
    pub fn broadcast(text: impl Into<Text>) -> Result<u32, String> {
        host::broadcast(&text.into())
    }

    /// Replace a player's tab-list header and footer. Both `None` restores
    /// the configured tab list.
    ///
    /// ```no_run
    /// use rift_plugin::{players, text};
    ///
    /// players::tab_list("Steve", Some(text::mini("<gold>Rift").into()), Some("Have fun".into())).ok();
    /// players::tab_list("Steve", None, None).ok();
    /// ```
    pub fn tab_list(
        target: &str,
        header: Option<Text>,
        footer: Option<Text>,
    ) -> Result<bool, String> {
        host::tab_list(target, header.as_ref(), footer.as_ref())
    }

    /// Show a dialog in the vanilla JSON format (Minecraft 1.21.6+). Returns
    /// false when the player is offline, older than 1.21.6 or has too many
    /// undelivered actions; an invalid dialog is an error.
    pub fn show_dialog(target: &str, dialog: &serde_json::Value) -> Result<bool, String> {
        self::dialog(target, &dialog.to_string())
    }
}

/// The durable key-value store. Namespaces are prefixed with
/// `plugin.<name>.` by the host.
pub mod store {
    pub use crate::bindings::rift::plugin::store::{delete, get, increment, list, set};
    use serde::Serialize;
    use serde::de::DeserializeOwned;

    /// Reads a JSON-encoded entry.
    pub fn get_json<T: DeserializeOwned>(namespace: &str, key: &str) -> Result<Option<T>, String> {
        match get(namespace, key)? {
            Some(bytes) => serde_json::from_slice(&bytes)
                .map(Some)
                .map_err(|error| format!("invalid JSON in {namespace}/{key}: {error}")),
            None => Ok(None),
        }
    }

    /// Writes an entry as JSON.
    pub fn set_json<T: Serialize + ?Sized>(
        namespace: &str,
        key: &str,
        value: &T,
    ) -> Result<(), String> {
        let bytes = serde_json::to_vec(value).map_err(|error| error.to_string())?;
        set(namespace, key, &bytes)
    }
}

/// Rift's permission store: user nodes and group memberships.
///
/// `add_group(uuid, group, expires_at)` adds the user to a group, until
/// `expires_at` Unix seconds when given (see [`meta::time`]
/// for the current time).
pub mod permissions {
    pub use crate::bindings::rift::plugin::permissions::{
        add_group, groups, has, list_groups, meta, remove_group, set, set_meta,
    };

    /// The meta key that makes a player visible only to viewers holding the
    /// node in its value (see docs/permissions.md, "Visibility").
    pub const VISIBLE_TO: &str = "rift.visible-to";
}

/// The message bus. Subscriptions deliver to [`Plugin::message`].
pub mod bus {
    use crate::BusMessage;
    pub use crate::bindings::rift::plugin::bus::{
        publish, request, stream_publish, subscribe, unsubscribe,
    };

    /// Publishes `payload` to the message's reply subject. Returns `None`
    /// when the message has none, otherwise how many subscribers received it.
    pub fn reply(message: &BusMessage, payload: &[u8]) -> Result<Option<u32>, String> {
        match &message.reply {
            Some(subject) => publish(subject, payload, None).map(Some),
            None => Ok(None),
        }
    }
}

/// Managed servers, through the `rift.control.*` operations. Results are
/// the control service's JSON replies.
pub mod servers {
    pub use crate::bindings::rift::plugin::servers::{
        control, create, download, remove, start, stop,
    };
}

/// Timers fire through [`Plugin::timer`] with the
/// returned handle.
pub mod timers {
    pub use crate::bindings::rift::plugin::timers::{after, cancel, every};
}

/// Work that must not hold up the plugin's hooks.
///
/// A plugin runs one call at a time, so a hook that waits for a database or
/// a web service keeps every other hook waiting. Background workers take
/// that work: each is a separate instance of the component, started when the
/// manifest sets `[background] workers`. The pattern has three steps (the
/// [crate documentation](crate#background-work) has a complete example):
///
/// 1. In a decision hook (`login`, `initial_server`, `before_transfer`,
///    `command`, `chat` or `kick`), call [`defer`](background::defer) for a ticket and [`run`](background::run)
///    with the job's payload, remember the ticket under the job's handle and
///    return. The hook's own return value is ignored.
/// 2. A worker calls [`Plugin::work`] with the payload.
///    It may block.
/// 3. [`Plugin::job_done`] receives the handle and
///    the result on the main instance; call [`resolve`](background::resolve) with the ticket and
///    the answer.
///
/// The deferred hook's deadline keeps running: an answer that comes too late
/// counts as a missed deadline, and [`resolve`](background::resolve) then returns `false`. [`run`](background::run)
/// also works without [`defer`](background::defer), from any hook, for work nobody waits for.
pub mod background {
    use crate::Action;
    use crate::bindings::rift::plugin::background as host;
    pub use host::{defer, is_worker, run};

    /// Answer a deferred hook with the ticket [`defer`] returned. Returns
    /// `false` when nobody waits for the ticket any more: the deadline
    /// passed, or it was answered already.
    pub fn resolve(ticket: u64, action: Action) -> Result<bool, String> {
        host::resolve(ticket, &action)
    }
}

/// Plugin metadata and clocks. `api` is the `rift:plugin` version the host
/// implements, such as `0.2.0`.
pub mod meta {
    pub use crate::bindings::rift::plugin::meta::{
        api, clock, config_dir, data_dir, name, time, version,
    };
}

/// Rift's log stream, prefixed with the plugin name by the host.
///
/// The SDK installs a [`::log`] logger before [`Plugin::init`]
/// (and before [`Plugin::work_init`] on a worker),
/// so the `log` crate's macros work as usual. They are re-exported here for
/// plugins that do not depend on `log` themselves:
/// `rift_plugin::log::info!("ready")`.
pub mod log {
    pub use crate::bindings::rift::plugin::log::log;
    #[doc(no_inline)]
    pub use ::log::{debug, error, info, trace, warn};

    use crate::Level;

    struct HostLogger;

    static LOGGER: HostLogger = HostLogger;

    impl ::log::Log for HostLogger {
        fn enabled(&self, _metadata: &::log::Metadata) -> bool {
            true
        }

        fn log(&self, record: &::log::Record) {
            let level = match record.level() {
                ::log::Level::Trace => Level::Trace,
                ::log::Level::Debug => Level::Debug,
                ::log::Level::Info => Level::Info,
                ::log::Level::Warn => Level::Warn,
                ::log::Level::Error => Level::Error,
            };
            match record.args().as_str() {
                Some(message) => log(level, message),
                None => log(level, &record.args().to_string()),
            }
        }

        fn flush(&self) {}
    }

    /// Installs the host logger once. Later calls do nothing, so a plugin may
    /// lower the level with `log::set_max_level` in `init`.
    pub(crate) fn install() {
        if ::log::set_logger(&LOGGER).is_ok() {
            ::log::set_max_level(::log::LevelFilter::Trace);
        }
    }
}

/// Builders for JSON text: each converts into a [`Text::Json`](crate::Text),
/// so it can be passed wherever text is shown.
///
/// - [`text::mini`] writes Rift markup as `{"mini": "...", "args": {...}}`; Rift
///   turns it into a component. See `docs/text.md` for the tags.
/// - [`text::legacy`] writes `&c` codes as `{"legacy": "...", "marker": "&"}`.
/// - [`text::Component`] builds a JSON text component field by field, with the
///   1.21.5 spellings `click_event` and `hover_event` (Rift rewrites them
///   for older clients).
///
/// Every builder converts into [`Text`] and into a
/// [`serde_json::Value`] for use inside other components, and implements
/// [`Display`](std::fmt::Display) (its JSON text). A bare string is never
/// read as markup, so player input passed as an argument or as text cannot
/// add tags or click events.
pub mod text {
    use serde_json::{Map, Value};
    use std::fmt;

    /// Rift markup, such as `<gold>Hi <player>!`. Add arguments with
    /// [`Mini::arg`] and [`Mini::arg_component`].
    pub fn mini(markup: impl Into<String>) -> Mini {
        Mini {
            markup: markup.into(),
            args: Map::new(),
        }
    }

    /// Markup with named arguments; see [`mini`].
    #[derive(Debug, Clone, PartialEq)]
    pub struct Mini {
        markup: String,
        args: Map<String, Value>,
    }

    impl Mini {
        /// `<name>` shows `text` exactly as written: it is never parsed, so
        /// a player name cannot add tags.
        pub fn arg(mut self, name: impl Into<String>, text: impl Into<String>) -> Self {
            self.args.insert(name.into(), Value::String(text.into()));
            self
        }

        /// `<name>` shows a component with its own formatting, such as a
        /// [`Component`], a [`legacy`] object or a [`serde_json::Value`].
        pub fn arg_component(
            mut self,
            name: impl Into<String>,
            component: impl Into<Value>,
        ) -> Self {
            self.args.insert(name.into(), component.into());
            self
        }

        /// The authoring object as JSON.
        pub fn to_value(&self) -> Value {
            let mut object = Map::new();
            object.insert("mini".into(), Value::String(self.markup.clone()));
            if !self.args.is_empty() {
                object.insert("args".into(), Value::Object(self.args.clone()));
            }
            Value::Object(object)
        }
    }

    /// Legacy formatting codes with the `&` marker, such as `&cRed &lbold`;
    /// `&#rrggbb` writes a hex colour. Use [`Legacy::marker`] for another
    /// marker.
    pub fn legacy(text: impl Into<String>) -> Legacy {
        Legacy {
            text: text.into(),
            marker: '&',
        }
    }

    /// Legacy codes; see [`legacy`].
    #[derive(Debug, Clone, PartialEq)]
    pub struct Legacy {
        text: String,
        marker: char,
    }

    impl Legacy {
        /// The character that starts a code, such as `§`; one symbol, not a
        /// letter, digit or space.
        pub fn marker(mut self, marker: char) -> Self {
            self.marker = marker;
            self
        }

        /// The authoring object as JSON.
        pub fn to_value(&self) -> Value {
            let mut object = Map::new();
            object.insert("legacy".into(), Value::String(self.text.clone()));
            object.insert("marker".into(), Value::String(self.marker.to_string()));
            Value::Object(object)
        }
    }

    /// A JSON text component, built field by field.
    ///
    /// ```
    /// use rift_plugin::text::Component;
    ///
    /// let invite = Component::text("Alex invited you. ")
    ///     .extra(Component::text("[Accept]").color("green").bold().run_command("/party accept Alex"));
    /// assert_eq!(
    ///     serde_json::Value::from(invite),
    ///     serde_json::json!({
    ///         "text": "Alex invited you. ",
    ///         "extra": [{
    ///             "text": "[Accept]", "color": "green", "bold": true,
    ///             "click_event": {"action": "run_command", "command": "/party accept Alex"},
    ///         }],
    ///     })
    /// );
    /// ```
    #[derive(Debug, Clone, PartialEq)]
    pub struct Component(Map<String, Value>);

    impl Component {
        /// A component showing `text`.
        pub fn text(text: impl Into<String>) -> Self {
            let mut fields = Map::new();
            fields.insert("text".into(), Value::String(text.into()));
            Self(fields)
        }

        /// A colour name such as `red` or `#ff8800`.
        pub fn color(self, color: impl Into<String>) -> Self {
            self.field("color", color.into())
        }

        /// Bold text.
        pub fn bold(self) -> Self {
            self.field("bold", true)
        }

        /// Italic text.
        pub fn italic(self) -> Self {
            self.field("italic", true)
        }

        /// Underlined text.
        pub fn underlined(self) -> Self {
            self.field("underlined", true)
        }

        /// Struck-through text.
        pub fn strikethrough(self) -> Self {
            self.field("strikethrough", true)
        }

        /// Obfuscated (scrambling) text.
        pub fn obfuscated(self) -> Self {
            self.field("obfuscated", true)
        }

        fn click(self, action: &str, key: &str, value: impl Into<String>) -> Self {
            let mut click = Map::new();
            click.insert("action".into(), Value::String(action.into()));
            click.insert(key.into(), Value::String(value.into()));
            self.field("click_event", Value::Object(click))
        }

        /// A click runs `command` (with its leading `/`) as the player.
        pub fn run_command(self, command: impl Into<String>) -> Self {
            self.click("run_command", "command", command)
        }

        /// A click puts `command` into the player's chat box.
        pub fn suggest_command(self, command: impl Into<String>) -> Self {
            self.click("suggest_command", "command", command)
        }

        /// A click opens `url` (`http` or `https`) after a confirmation.
        pub fn open_url(self, url: impl Into<String>) -> Self {
            self.click("open_url", "url", url)
        }

        /// A click copies `text` to the clipboard.
        pub fn copy_to_clipboard(self, text: impl Into<String>) -> Self {
            self.click("copy_to_clipboard", "value", text)
        }

        /// Hover text shown as written.
        pub fn hover_text(self, text: impl Into<String>) -> Self {
            self.hover(Value::String(text.into()))
        }

        /// Hover text as a component, such as another [`Component`] or a
        /// [`mini`] object.
        pub fn hover(self, component: impl Into<Value>) -> Self {
            let mut hover = Map::new();
            hover.insert("action".into(), Value::String("show_text".into()));
            hover.insert("value".into(), component.into());
            self.field("hover_event", Value::Object(hover))
        }

        /// Text inserted into the chat box on shift-click.
        pub fn insertion(self, text: impl Into<String>) -> Self {
            self.field("insertion", text.into())
        }

        /// Appends a child: a [`Component`], an authoring object or a string
        /// shown as written. Children inherit this component's style.
        pub fn extra(mut self, child: impl Into<Value>) -> Self {
            let child = child.into();
            match self.0.get_mut("extra") {
                Some(Value::Array(children)) => children.push(child),
                _ => {
                    self.0.insert("extra".into(), Value::Array(vec![child]));
                }
            }
            self
        }

        /// Sets any other field, such as `font`, `shadow_color` or
        /// `"italic": false`.
        pub fn field(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
            self.0.insert(key.into(), value.into());
            self
        }

        /// The component as JSON.
        pub fn to_value(&self) -> Value {
            Value::Object(self.0.clone())
        }
    }

    macro_rules! json_text {
        ($($builder:ty),*) => {$(
            impl fmt::Display for $builder {
                /// The JSON text.
                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                    fmt::Display::fmt(&self.to_value(), f)
                }
            }

            impl From<$builder> for Value {
                fn from(builder: $builder) -> Value {
                    builder.to_value()
                }
            }

            impl From<$builder> for crate::Text {
                /// [`Text::Json`](crate::Text::Json) with the builder's JSON.
                fn from(builder: $builder) -> crate::Text {
                    crate::Text::Json(builder.to_string())
                }
            }

            impl From<&$builder> for crate::Text {
                /// [`Text::Json`](crate::Text::Json) with the builder's JSON.
                fn from(builder: &$builder) -> crate::Text {
                    crate::Text::Json(builder.to_string())
                }
            }
        )*};
    }

    json_text!(Mini, Legacy, Component);
}

#[doc(hidden)]
pub mod __private {
    use crate::bindings::exports::rift::plugin::handler::Guest;
    use crate::*;
    use std::any::Any;
    use std::cell::RefCell;
    use std::marker::PhantomData;

    thread_local! {
        static INSTANCE: RefCell<Option<Box<dyn Any>>> = const { RefCell::new(None) };
    }

    /// Runs `f` on the instance, creating it first when there is none: a
    /// background worker never sees `init`.
    fn with<P: Plugin, R>(f: impl FnOnce(&mut P) -> R) -> R {
        INSTANCE.with(|slot| {
            let mut slot = slot.borrow_mut();
            let plugin = slot
                .get_or_insert_with(|| Box::new(P::default()))
                .downcast_mut::<P>()
                .expect("one plugin type per component");
            f(plugin)
        })
    }

    /// Connects a [`Plugin`] to the generated `Guest` trait.
    pub struct Adapter<P>(PhantomData<P>);

    impl<P: Plugin> Guest for Adapter<P> {
        fn init(config_json: String) -> Result<Registration, String> {
            crate::log::install();
            INSTANCE.with(|slot| *slot.borrow_mut() = Some(Box::new(P::default())));
            with(|p: &mut P| p.init(&config_json))
        }

        fn reload(config_json: String) -> Result<(), String> {
            with(|p: &mut P| p.reload(&config_json))
        }

        fn shutdown(reason: String) {
            with(|p: &mut P| p.shutdown(&reason));
            let instance = INSTANCE.with(|slot| slot.borrow_mut().take());
            drop(instance);
        }

        fn route(connection: Connection) -> RouteDecision {
            with(|p: &mut P| p.route(connection))
        }

        fn login(ctx: Context) -> Action {
            with(|p: &mut P| p.login(ctx))
        }

        fn initial_server(ctx: Context) -> Action {
            with(|p: &mut P| p.initial_server(ctx))
        }

        fn before_transfer(ctx: Context) -> Action {
            with(|p: &mut P| p.before_transfer(ctx))
        }

        fn command(ctx: Context) -> Action {
            with(|p: &mut P| p.command(ctx))
        }

        fn suggest(ctx: Context) -> Vec<Suggestion> {
            with(|p: &mut P| p.suggest(ctx))
        }

        fn status(ping: Ping) -> Option<StatusOverride> {
            with(|p: &mut P| p.status(ping))
        }

        fn http(request: HttpRequest) -> Option<HttpResponse> {
            with(|p: &mut P| p.http(request))
        }

        fn chat(attempt: ChatAttempt) -> Action {
            with(|p: &mut P| p.chat(attempt))
        }

        fn kick(ctx: Context) -> Action {
            with(|p: &mut P| p.kick(ctx))
        }

        fn join(ctx: Context) {
            with(|p: &mut P| p.join(ctx))
        }

        fn after_transfer(ctx: Context) {
            with(|p: &mut P| p.after_transfer(ctx))
        }

        fn disconnect(ctx: Context) {
            with(|p: &mut P| p.disconnect(ctx))
        }

        fn message(message: BusMessage) {
            with(|p: &mut P| p.message(message))
        }

        fn timer(handle: u64) {
            with(|p: &mut P| p.timer(handle))
        }

        fn event(event: RiftEvent) {
            with(|p: &mut P| p.event(event))
        }

        fn dialog(response: DialogResponse) {
            with(|p: &mut P| p.dialog(response))
        }

        fn job_done(handle: u64, outcome: Result<Vec<u8>, String>) {
            with(|p: &mut P| p.job_done(handle, outcome))
        }

        // A worker instance: `init` never ran here, so the logger is
        // installed and the instance created on the first of these calls.
        fn work_init(config_json: String) -> Result<(), String> {
            crate::log::install();
            with(|p: &mut P| p.work_init(&config_json))
        }

        fn work(payload: Vec<u8>) -> Result<Vec<u8>, String> {
            crate::log::install();
            with(|p: &mut P| p.work(payload))
        }
    }
}

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

    #[test]
    fn builders_fill_the_wit_records() {
        let registration = Registration::new()
            .command(
                CommandSpec::new("hello")
                    .alias("hi")
                    .aliases(["hey", "yo"])
                    .permission("hello.use")
                    .suggest(SuggestKind::Players)
                    .console(),
            )
            .command(CommandSpec::new("plain"))
            .hooks([Hook::Login, Hook::Command])
            .hook(Hook::Chat);
        let hello = &registration.commands[0];
        assert_eq!(hello.name, "hello");
        assert_eq!(hello.aliases, ["hi", "hey", "yo"]);
        assert_eq!(hello.permission, "hello.use");
        assert!(matches!(hello.suggest, SuggestKind::Players));
        assert!(hello.console);
        let plain = &registration.commands[1];
        assert!(plain.aliases.is_empty() && plain.permission.is_empty() && !plain.console);
        assert!(matches!(plain.suggest, SuggestKind::None));
        assert_eq!(
            registration.hooks,
            vec![Hook::Login, Hook::Command, Hook::Chat]
        );
        assert!(Registration::default().commands.is_empty());
        assert!(Registration::default().hooks.is_empty());
    }

    #[test]
    fn strings_are_plain_and_builders_are_json() {
        assert_eq!(Text::from("<red>hi"), Text::Plain("<red>hi".into()));
        assert_eq!(Text::from(String::from("a")), Text::plain("a"));
        assert_eq!(Text::from(&String::from("a")), Text::plain("a"));
        assert_eq!(
            Text::from(text::mini("<red>x")),
            Text::Json(r#"{"mini":"<red>x"}"#.into())
        );
        assert_eq!(
            Text::from(text::legacy("&cx")),
            Text::json(r#"{"legacy":"&cx","marker":"&"}"#)
        );
        assert_eq!(
            Text::from(&text::Component::text("x").bold()),
            Text::json(r#"{"bold":true,"text":"x"}"#)
        );
        assert_eq!(
            Text::from(json!({"text": "x"})),
            Text::json(r#"{"text":"x"}"#)
        );
        // A JSON string is still JSON text: shown as written by the host.
        assert_eq!(Text::from(&json!("a\"b")), Text::json(r#""a\"b""#));
        assert_ne!(Text::plain("x"), Text::json("x"));
    }

    #[test]
    fn actions_take_any_text() {
        assert_eq!(Action::deny("no"), Action::Deny(Text::Plain("no".into())));
        assert_eq!(
            Action::deny(json!({"text": "Banned", "color": "red"})),
            Action::Deny(Text::Json(r#"{"color":"red","text":"Banned"}"#.into()))
        );
        assert_eq!(
            Action::message(format!("Hi, {}!", "Alex")),
            Action::Message(Text::Plain("Hi, Alex!".into()))
        );
        assert_eq!(
            Action::message(text::mini("<gold>Hi")),
            Action::Message(Text::Json(r#"{"mini":"<gold>Hi"}"#.into()))
        );
        assert_eq!(Action::server("lobby"), Action::Server("lobby".into()));
        assert_eq!(Action::queue("game"), Action::Queue("game".into()));
        assert_ne!(Action::server("a"), Action::queue("a"));
        assert_ne!(Action::deny("a"), Action::message("a"));
        assert_ne!(Action::Continue, Action::LeaveQueue);
    }

    #[test]
    fn titles_suggestions_and_status_take_any_text() {
        let title = TitleSpec::new(text::mini("<red>T"))
            .subtitle("sub")
            .times(1, 2, 3);
        assert_eq!(title.title, Some(Text::json(r#"{"mini":"<red>T"}"#)));
        assert_eq!(title.subtitle, Some(Text::plain("sub")));
        assert_eq!((title.fade_in, title.stay, title.fade_out), (1, 2, 3));
        let plain = TitleSpec::new("T");
        assert_eq!(plain.subtitle, None);
        assert_eq!((plain.fade_in, plain.stay, plain.fade_out), (10, 70, 20));
        let subtitle = TitleSpec::subtitle_only("only").times(0, 20, 0);
        assert_eq!(subtitle.title, None);
        assert_eq!(subtitle.subtitle, Some(Text::plain("only")));
        assert_eq!(subtitle.stay, 20);

        assert_eq!(Suggestion::new("a").tooltip, None);
        assert_eq!(
            Suggestion::new("a").tooltip("tip").tooltip,
            Some(Text::plain("tip"))
        );
        assert_eq!(
            Suggestion::new("a").tooltip(text::legacy("&7tip")).tooltip,
            Some(Text::json(r#"{"legacy":"&7tip","marker":"&"}"#))
        );

        let status = StatusOverride {
            version: Some("Rift".into()),
            sample: Some(vec!["one".into(), text::mini("<green>two").into()]),
            ..Default::default()
        };
        assert_eq!(status.version, Some(Text::plain("Rift")));
        assert_eq!(status.sample.map(|lines| lines.len()), Some(2));
        let nothing = StatusOverride::default();
        assert!(nothing.motd.is_none() && nothing.version.is_none() && nothing.sample.is_none());
        assert!(nothing.protocol.is_none() && nothing.online.is_none());
        assert!(nothing.max_players.is_none() && nothing.favicon.is_none());
    }

    #[test]
    fn hooks_have_defaults() {
        #[derive(Default)]
        struct Nothing;
        impl Plugin for Nothing {}
        let mut plugin = Nothing;
        let registration = plugin.init("{}").unwrap();
        assert!(registration.commands.is_empty() && registration.hooks.is_empty());
        assert_eq!(plugin.work_init("{}"), Ok(()));
        assert_eq!(
            plugin.work(b"job".to_vec()),
            Err("this plugin has no background work".to_owned())
        );
        plugin.job_done(1, Ok(Vec::new()));
        plugin.job_done(2, Err("failed".into()));
    }

    #[test]
    fn text_builders_write_escaped_json() {
        let welcome = text::mini("<gold>Hi \"<player>\"</gold>")
            .arg("player", "St<b>eve\n")
            .arg_component("rank", text::legacy("&cAdmin"));
        let value: serde_json::Value = serde_json::from_str(&welcome.to_string()).unwrap();
        assert_eq!(
            value,
            json!({
                "mini": "<gold>Hi \"<player>\"</gold>",
                "args": {"player": "St<b>eve\n", "rank": {"legacy": "&cAdmin", "marker": "&"}},
            })
        );
        assert_eq!(text::mini("<red>x").to_string(), r#"{"mini":"<red>x"}"#);
        assert_eq!(
            text::legacy("§aHi").marker('§').to_string(),
            r#"{"legacy":"§aHi","marker":"§"}"#
        );
        let component = text::Component::text("[a\"b]")
            .color("#ff8800")
            .bold()
            .italic()
            .underlined()
            .strikethrough()
            .obfuscated()
            .suggest_command("/msg ")
            .hover(text::mini("<green>Hover"))
            .insertion("ins")
            .extra("plain")
            .extra(text::Component::text("child").open_url("https://example.org"))
            .field("font", "minecraft:uniform");
        let value: serde_json::Value = serde_json::from_str(&component.to_string()).unwrap();
        assert_eq!(
            value,
            json!({
                "text": "[a\"b]", "color": "#ff8800", "bold": true, "italic": true,
                "underlined": true, "strikethrough": true, "obfuscated": true,
                "click_event": {"action": "suggest_command", "command": "/msg "},
                "hover_event": {"action": "show_text", "value": {"mini": "<green>Hover"}},
                "insertion": "ins",
                "extra": ["plain", {"text": "child", "click_event": {"action": "open_url", "url": "https://example.org"}}],
                "font": "minecraft:uniform",
            })
        );
        let value: serde_json::Value = text::Component::text("c")
            .copy_to_clipboard("v")
            .run_command("/x")
            .hover_text("t")
            .into();
        assert_eq!(
            value["click_event"],
            json!({"action": "run_command", "command": "/x"})
        );
        assert_eq!(
            value["hover_event"],
            json!({"action": "show_text", "value": "t"})
        );
    }

    #[test]
    fn config_decodes_json() {
        #[derive(serde::Deserialize)]
        struct Config {
            #[serde(default)]
            deny: Option<String>,
        }
        let config: Config = config(r#"{"deny":"Mallory"}"#).unwrap();
        assert_eq!(config.deny.as_deref(), Some("Mallory"));
        let empty: Config = super::config("{}").unwrap();
        assert_eq!(empty.deny, None);
        assert!(super::config::<Config>("nope").is_err());
    }
}