modelith_plugin_protocol/
id.rs1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4
5pub const PLUGIN_ID_PATTERN: &str = r"^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$";
7
8#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
10#[cfg_attr(feature = "codegen", derive(ts_rs::TS))]
11#[cfg_attr(feature = "codegen", ts(type = "string"))]
12pub struct PluginId(String);
13
14impl<'de> Deserialize<'de> for PluginId {
15 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
16 String::deserialize(d)?
17 .try_into()
18 .map_err(serde::de::Error::custom)
19 }
20}
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct PluginIdError(pub String);
24
25impl fmt::Display for PluginIdError {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 write!(
28 f,
29 "invalid plugin id {:?}: expected reverse-domain form like \"com.example.my-plugin\"",
30 self.0
31 )
32 }
33}
34
35impl std::error::Error for PluginIdError {}
36
37impl PluginId {
38 pub fn as_str(&self) -> &str {
39 &self.0
40 }
41
42 fn is_valid(s: &str) -> bool {
43 let mut segments = 0;
44 for seg in s.split('.') {
45 let mut chars = seg.chars();
46 let ok = chars.next().is_some_and(|c| c.is_ascii_lowercase())
47 && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
48 if !ok {
49 return false;
50 }
51 segments += 1;
52 }
53 segments >= 2
54 }
55}
56
57impl TryFrom<String> for PluginId {
58 type Error = PluginIdError;
59 fn try_from(s: String) -> Result<Self, Self::Error> {
60 if Self::is_valid(&s) {
61 Ok(Self(s))
62 } else {
63 Err(PluginIdError(s))
64 }
65 }
66}
67
68impl std::str::FromStr for PluginId {
69 type Err = PluginIdError;
70 fn from_str(s: &str) -> Result<Self, Self::Err> {
71 s.to_owned().try_into()
72 }
73}
74
75impl From<PluginId> for String {
76 fn from(id: PluginId) -> Self {
77 id.0
78 }
79}
80
81impl fmt::Display for PluginId {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 f.write_str(&self.0)
84 }
85}
86
87#[cfg(feature = "codegen")]
88impl schemars::JsonSchema for PluginId {
89 fn schema_name() -> std::borrow::Cow<'static, str> {
90 "PluginId".into()
91 }
92
93 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
94 schemars::json_schema!({
95 "type": "string",
96 "pattern": PLUGIN_ID_PATTERN,
97 "description": "Reverse-domain plugin id, e.g. \"com.example.my-plugin\"."
98 })
99 }
100}
101
102#[cfg(test)]
103mod tests {
104 use super::*;
105
106 #[test]
109 fn accepts_reverse_domain_ids() {
110 let ids = ["com.example.fmea-check", "jp.modelith.iso15288-rules"];
112 let results: Vec<bool> = ids
114 .iter()
115 .map(|id| id.parse::<PluginId>().is_ok())
116 .collect();
117 assert_eq!(results, [true, true]);
119 }
120
121 #[test]
122 fn accepts_minimum_two_single_letter_segments() {
123 let id = "a.b";
125 let result = id.parse::<PluginId>();
127 assert!(result.is_ok());
129 }
130
131 #[test]
134 fn rejects_malformed_ids() {
135 let ids = [
137 "",
138 "single",
139 "Com.example",
140 "com..example",
141 "com.example.",
142 "1com.x",
143 "com.ex_ample",
144 ];
145 let accepted: Vec<&str> = ids
147 .iter()
148 .copied()
149 .filter(|id| id.parse::<PluginId>().is_ok())
150 .collect();
151 assert!(accepted.is_empty(), "accepted: {accepted:?}");
153 }
154
155 #[test]
156 fn deserialize_accepts_valid_id() {
157 let json = r#""com.example.ok""#;
159 let result = serde_json::from_str::<PluginId>(json);
161 assert_eq!(result.unwrap().as_str(), "com.example.ok");
163 }
164
165 #[test]
166 fn deserialize_rejects_invalid_id() {
167 let json = r#""NotValid""#;
169 let result = serde_json::from_str::<PluginId>(json);
171 assert!(result.is_err());
173 }
174}