1pub const ID_ALPHABET: &[u8; 32] = b"0123456789abcdefghjkmnpqrstvwxyz";
18
19pub const ID_LEN: usize = 8;
21
22pub const TITLE_MAX: usize = 200;
24
25pub const BODY_MAX: usize = 2 * 1024 * 1024;
28
29pub const QUERY_MAX: usize = 200;
31
32macro_rules! text_type {
33 ($(#[$doc:meta])* $name:ident, $rule:expr) => {
34 $(#[$doc])*
35 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, schemars::JsonSchema)]
36 #[serde(transparent)]
37 pub struct $name(String);
38
39 impl $name {
40 pub fn as_str(&self) -> &str {
42 &self.0
43 }
44
45 pub fn into_string(self) -> String {
47 self.0
48 }
49 }
50
51 impl TryFrom<String> for $name {
52 type Error = String;
53 fn try_from(text: String) -> Result<Self, String> {
54 let rule: fn(&str) -> Result<String, String> = $rule;
55 rule(&text).map(Self)
56 }
57 }
58
59 impl std::str::FromStr for $name {
60 type Err = String;
61 fn from_str(text: &str) -> Result<Self, String> {
62 let rule: fn(&str) -> Result<String, String> = $rule;
63 rule(text).map(Self)
64 }
65 }
66
67 impl<'de> serde::Deserialize<'de> for $name {
68 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
69 Self::try_from(<String as serde::Deserialize>::deserialize(d)?).map_err(serde::de::Error::custom)
70 }
71 }
72
73 impl std::fmt::Display for $name {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 f.write_str(&self.0)
76 }
77 }
78
79 impl AsRef<str> for $name {
80 fn as_ref(&self) -> &str {
81 &self.0
82 }
83 }
84 };
85}
86
87fn not_a(text: &str, what: &str, shape: &str) -> String {
88 format!("`{text}` is not {what}: {shape}")
89}
90
91fn id(text: &str) -> Result<String, String> {
92 let t = text.trim();
93 let t = t.rsplit_once("#/note/").or_else(|| t.rsplit_once("#/doc/")).map_or(t, |(_, id)| id).trim_end_matches('/');
96 match t.len() == ID_LEN && t.bytes().all(|b| ID_ALPHABET.contains(&b.to_ascii_lowercase())) {
97 true => Ok(t.to_ascii_lowercase()),
98 false => Err(not_a(t, "a note's id", "8 characters of Crockford's base32 — digits and letters but i, l, o and u — as 7k3mq2xa")),
99 }
100}
101
102text_type!(
103 NoteId,
107 id
108);
109
110fn title(text: &str) -> Result<String, String> {
111 let t = text.split_whitespace().collect::<Vec<_>>().join(" ");
112 match (t.is_empty(), t.chars().count() > TITLE_MAX) {
113 (true, _) => Err("a title is some words: it is empty".to_string()),
114 (_, true) => Err(format!("a title is at most {TITLE_MAX} characters; this one is {}", t.chars().count())),
115 _ => Ok(t),
116 }
117}
118
119text_type!(
120 NoteTitle,
123 title
124);
125
126fn body(text: &str) -> Result<String, String> {
127 match text.len() <= BODY_MAX {
128 true => Ok(text.to_string()),
129 false => Err(format!("a body is at most {BODY_MAX} bytes; this one is {}", text.len())),
130 }
131}
132
133text_type!(
134 NoteBody,
136 body
137);
138
139fn query(text: &str) -> Result<String, String> {
140 let t = text.trim();
141 match t.chars().count() <= QUERY_MAX {
142 true => Ok(t.to_string()),
143 false => Err(format!("a search is at most {QUERY_MAX} characters")),
144 }
145}
146
147text_type!(
148 NoteQuery,
151 query
152);
153
154pub const UPDATE_MAX: usize = 8 * 1024 * 1024;
156pub const AWARENESS_MAX: usize = 64 * 1024;
158
159fn base64_of(text: &str, max: usize, what: &str) -> Result<String, String> {
160 let t = text.trim();
161 let ok = t.bytes().all(|b| b.is_ascii_alphanumeric() || b"+/=".contains(&b));
162 match (ok, t.len() <= max) {
163 (false, _) => Err(format!("{what} is standard base64")),
164 (_, false) => Err(format!("{what} is at most {max} bytes of base64; this is {}", t.len())),
165 _ => Ok(t.to_string()),
166 }
167}
168
169fn update(text: &str) -> Result<String, String> {
170 base64_of(text, UPDATE_MAX, "an update")
171}
172
173text_type!(
174 NoteUpdate,
177 update
178);
179
180fn vector(text: &str) -> Result<String, String> {
181 base64_of(text, AWARENESS_MAX, "a state vector")
182}
183
184text_type!(
185 NoteVector,
187 vector
188);
189
190fn awareness(text: &str) -> Result<String, String> {
191 base64_of(text, AWARENESS_MAX, "a caret")
192}
193
194text_type!(
195 NoteAwareness,
198 awareness
199);
200
201fn session(text: &str) -> Result<String, String> {
202 let t = text.trim();
203 match !t.is_empty() && t.len() <= 64 && t.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
204 true => Ok(t.to_string()),
205 false => Err(not_a(t, "a session", "1 to 64 letters, digits, - and _ — the page's own id, e.g. s-3f9a1c")),
206 }
207}
208
209text_type!(
210 NoteSession,
212 session
213);
214
215text_type!(
216 ThreadId,
218 id
219);
220
221pub const THREAD_TEXT_MAX: usize = 256 * 1024;
223
224fn thread_text(text: &str) -> Result<String, String> {
225 match (text.trim().is_empty(), text.len() <= THREAD_TEXT_MAX) {
226 (true, _) => Err("a question or an answer says something: it is empty".to_string()),
227 (_, false) => Err(format!("a question or an answer is at most {THREAD_TEXT_MAX} bytes; this one is {}", text.len())),
228 _ => Ok(text.trim_end().to_string()),
229 }
230}
231
232text_type!(
233 ThreadText,
236 thread_text
237);
238
239fn agent_name(text: &str) -> Result<String, String> {
240 let t = text.trim();
241 match !t.is_empty() && t.len() <= 64 && !t.chars().any(char::is_whitespace) {
242 true => Ok(t.to_string()),
243 false => Err(not_a(t, "a name", "an agent's name or a principal, one word, e.g. builder (or agent, for any)")),
244 }
245}
246
247text_type!(
248 AgentName,
251 agent_name
252);
253
254fn component_name(text: &str) -> Result<String, String> {
257 let t = text.trim();
258 let ok = t.len() <= 64 && t.starts_with(|c: char| c.is_ascii_lowercase()) && t.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') && !t.ends_with('-') && !t.contains("--");
259 match ok {
260 true => Ok(t.to_string()),
261 false => Err(not_a(t, "a component's name", "lower-case letters and digits, hyphen-separated, beginning with a letter, at most 64 — e.g. graph-nodes")),
262 }
263}
264
265text_type!(
266 ComponentName,
269 component_name
270);
271
272fn version_ref(text: &str) -> Result<String, String> {
273 let t = text.trim().to_ascii_lowercase();
274 match (6..=64).contains(&t.len()) && t.bytes().all(|b| b.is_ascii_hexdigit()) {
275 true => Ok(t),
276 false => Err(not_a(&t, "a version", "a kept version's hash, 64 hex digits (or at least its first 6), as ui.author answered it")),
277 }
278}
279
280text_type!(
281 VersionRef,
284 version_ref
285);
286
287pub const SAY_MAX: usize = 4 * 1024;
290
291fn slot_say(text: &str) -> Result<String, String> {
292 let t = text.trim();
293 match (t.is_empty(), t.len() <= SAY_MAX) {
294 (true, _) => Err("a line says something: it is empty".to_string()),
295 (_, false) => Err(format!("a line is at most {SAY_MAX} bytes; this one is {}", t.len())),
296 _ => Ok(t.to_string()),
297 }
298}
299
300text_type!(
301 SlotSay,
304 slot_say
305);
306
307pub const PROPS_MAX: usize = 64 * 1024;
309
310#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, schemars::JsonSchema)]
314#[serde(transparent)]
315pub struct SlotProps(serde_json::Map<String, serde_json::Value>);
316
317impl SlotProps {
318 pub fn into_map(self) -> serde_json::Map<String, serde_json::Value> {
320 self.0
321 }
322}
323
324impl<'de> serde::Deserialize<'de> for SlotProps {
325 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
326 use serde::de::Error;
327 let map = match <serde_json::Value as serde::Deserialize>::deserialize(d)? {
328 serde_json::Value::Object(map) => map,
329 serde_json::Value::String(text) => match serde_json::from_str(&text) {
331 Ok(serde_json::Value::Object(map)) => map,
332 _ => return Err(D::Error::custom(format!("props are a JSON object, e.g. {{\"nodes\": 6}}; this is {text:?}"))),
333 },
334 other => return Err(D::Error::custom(format!("props are a JSON object, e.g. {{\"nodes\": 6}}; this is {other}"))),
335 };
336 let size = serde_json::to_string(&map).map_or(usize::MAX, |s| s.len());
337 match size <= PROPS_MAX {
338 true => Ok(Self(map)),
339 false => Err(D::Error::custom(format!("props are at most {PROPS_MAX} bytes written as JSON; these are {size}"))),
340 }
341 }
342}
343
344#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
347#[serde(rename_all = "snake_case")]
348pub enum BuildStep {
349 Heard,
351 Written,
353 Compiled,
355}
356
357text_type!(
358 MarkId,
360 id
361);
362
363pub const LABEL_MAX: usize = 200;
365pub const LINK_MAX: usize = 2048;
367
368fn label(text: &str) -> Result<String, String> {
369 let t = text.trim();
370 match (t.contains(['\n', '\r']), t.chars().count() > LABEL_MAX) {
371 (true, _) => Err("a label is one line: it holds a line break".to_string()),
372 (_, true) => Err(format!("a label is at most {LABEL_MAX} characters; this one is {}", t.chars().count())),
373 _ => Ok(t.to_string()),
374 }
375}
376
377text_type!(
378 MarkLabel,
381 label
382);
383
384fn is_ticket(t: &str) -> bool {
388 let tail = t.rsplit(['/', ':']).next().unwrap_or(t);
389 let head = &t[..t.len() - tail.len()];
390 let Some((code, n)) = tail.rsplit_once('-') else { return false };
391 let code_ok = code.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) && code.chars().all(|c| c.is_ascii_alphanumeric() || c == '-');
392 let n_ok = !n.is_empty() && n.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()));
393 let head_ok = head.chars().all(|c| c.is_ascii_alphanumeric() || "-_:/".contains(c));
394 code_ok && n_ok && head_ok
395}
396
397fn link(text: &str) -> Result<String, String> {
398 let t = text.trim();
399 let https = t.get(..8).is_some_and(|s| s.eq_ignore_ascii_case("https://")) && t.len() > 8 && !t[8..].starts_with(['/', '?', '#']);
400 if t.is_empty() {
401 return Ok(String::new());
402 }
403 if t.len() > LINK_MAX {
404 return Err(format!("a link is at most {LINK_MAX} bytes; this one is {}", t.len()));
405 }
406 match !t.chars().any(|c| c.is_whitespace() || c.is_control()) && (t.starts_with("#/") || https || is_ticket(t)) {
407 true => Ok(t.to_string()),
408 false => Err(not_a(t, "a link", "a ticket (KILN-12), an address of the app (#/note/7k3mq2xa) or an https address")),
409 }
410}
411
412text_type!(
413 MarkLink,
417 link
418);
419
420pub fn id_of_bits(bits: u64) -> String {
422 (0..ID_LEN).map(|i| ID_ALPHABET[((bits >> (5 * (ID_LEN - 1 - i))) & 31) as usize] as char).collect()
423}
424
425pub fn draw() -> u64 {
428 let b = uuid::Uuid::new_v4().into_bytes();
429 u64::from_be_bytes([0, 0, 0, b[0], b[1], b[2], b[3], b[4]])
430}
431
432pub fn mint(taken: impl Fn(&str) -> bool) -> String {
434 loop {
435 let id = id_of_bits(draw());
436 if !taken(&id) {
437 return id;
438 }
439 }
440}
441
442#[cfg(test)]
443mod tests {
444 use super::*;
445
446 #[test]
447 fn the_spellings_hold_and_refuse() {
448 assert_eq!("7K3MQ2XA".parse::<NoteId>().unwrap().as_str(), "7k3mq2xa");
449 assert_eq!("/app/#/note/7k3mq2xa".parse::<NoteId>().unwrap().as_str(), "7k3mq2xa");
450 assert_eq!("/app/#/doc/7k3mq2xa".parse::<NoteId>().unwrap().as_str(), "7k3mq2xa", "an old link");
451 for bad in ["", "7k3mq2x", "7k3mq2xab", "7k3mq2xi", "7k3mq-xa"] {
452 assert!(bad.parse::<NoteId>().is_err(), "{bad:?}");
453 }
454 assert_eq!(" The kiln\n".parse::<NoteTitle>().unwrap().as_str(), "The kiln");
455 assert!(" ".parse::<NoteTitle>().is_err());
456 assert!("x".repeat(TITLE_MAX + 1).parse::<NoteTitle>().is_err());
457 assert!("x".repeat(BODY_MAX + 1).parse::<NoteBody>().is_err());
458 assert_eq!("".parse::<NoteBody>().unwrap().as_str(), "");
459 assert!(serde_json::from_str::<NoteId>("\"abc\"").is_err(), "deserializing is the check");
460 }
461
462 #[test]
463 fn a_link_is_a_ticket_an_address_of_the_app_or_https() {
464 for ok in ["KILN-12", "SYNAPSE-CC-10", "KILN-2.1", "MENGER/ORG-3", "acme:KILN-12", "#/note/7k3mq2xa", "#/code/plexus-registry", "https://example.com/a?b=c", "HTTPS://example.com"] {
465 assert_eq!(ok.parse::<MarkLink>().map(|l| l.into_string()), Ok(ok.to_string()), "{ok}");
466 }
467 for bad in ["http://example.com", "javascript:alert(1)", "https://", "https:///x", "KILN", "KILN-", "12-3", "#/a b", "/app/#/x", "mailto:a@b.c", "data:text/html,x", "KILN-1x"] {
468 assert!(bad.parse::<MarkLink>().is_err(), "{bad}");
469 }
470 assert_eq!("".parse::<MarkLink>().unwrap().as_str(), "", "empty takes it off");
471 assert_eq!(" built graph-nodes v2 ".parse::<MarkLabel>().unwrap().as_str(), "built graph-nodes v2");
472 assert!("two\nlines".parse::<MarkLabel>().is_err());
473 assert!("x".repeat(LABEL_MAX + 1).parse::<MarkLabel>().is_err());
474 }
475
476 #[test]
477 fn an_id_is_eight_digits_of_the_alphabet_and_minted_apart() {
478 assert_eq!(id_of_bits(0), "00000000");
479 assert_eq!(id_of_bits((1 << 40) - 1), "zzzzzzzz");
480 for _ in 0..200 {
481 let id = id_of_bits(draw());
482 assert!(id.parse::<NoteId>().is_ok(), "{id}");
483 }
484 let first = id_of_bits(draw());
485 let again = mint(|t| t == first);
486 assert_ne!(again, first);
487 }
488
489 #[test]
490 fn a_slots_words_hold_and_refuse() {
491 assert_eq!("graph-nodes".parse::<ComponentName>().unwrap().as_str(), "graph-nodes");
492 for bad in ["", "Graph", "1graph", "graph-", "gr--aph", "graph_nodes"] {
493 assert!(bad.parse::<ComponentName>().is_err(), "{bad:?}");
494 }
495 assert_eq!("ABCDEF".parse::<VersionRef>().unwrap().as_str(), "abcdef");
496 for bad in ["abcde", "xyzxyz", &"a".repeat(65)] {
497 assert!(bad.parse::<VersionRef>().is_err(), "{bad:?}");
498 }
499 assert!(" ".parse::<SlotSay>().is_err());
500 let props: SlotProps = serde_json::from_str(r#"{"nodes": 6, "gone": null}"#).unwrap();
501 assert_eq!(props.into_map().len(), 2);
502 assert!(serde_json::from_str::<SlotProps>("[1]").is_err(), "an object only");
503 let flag: SlotProps = serde_json::from_str(r#""{\"nodes\": 6}""#).unwrap();
504 assert_eq!(flag.into_map().len(), 1, "a flag's text holding an object");
505 assert!(serde_json::from_str::<SlotProps>(r#""six""#).is_err());
506 let big = format!("{{\"x\": \"{}\"}}", "y".repeat(PROPS_MAX));
507 assert!(serde_json::from_str::<SlotProps>(&big).is_err(), "64 KiB at most");
508 assert_eq!(serde_json::from_str::<BuildStep>("\"written\"").unwrap(), BuildStep::Written);
509 }
510}