1use rkyv::{Archive, Deserialize, Serialize};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Archive, Serialize, Deserialize)]
19pub enum AddressKind {
20 #[default]
22 Http,
23 File,
25 Data,
27 GraphshellClip,
29 Directory,
31 Unknown,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
46#[rkyv(derive(Debug, PartialEq))]
47pub enum Address {
48 Http(String),
50 File(String),
52 Data(String),
54 Clip(String),
57 Directory(String),
59 Custom(String),
61}
62
63impl Address {
64 pub fn as_url_str(&self) -> &str {
66 match self {
67 Address::Http(s)
68 | Address::File(s)
69 | Address::Data(s)
70 | Address::Directory(s)
71 | Address::Custom(s)
72 | Address::Clip(s) => s.as_str(),
73 }
74 }
75
76 pub fn address_kind(&self) -> AddressKind {
81 match self {
82 Address::Http(_) => AddressKind::Http,
83 Address::File(_) => AddressKind::File,
84 Address::Data(_) => AddressKind::Data,
85 Address::Clip(_) => AddressKind::GraphshellClip,
86 Address::Directory(_) => AddressKind::Directory,
87 Address::Custom(_) => AddressKind::Unknown,
88 }
89 }
90}
91
92impl chartulary::ContainerAddress for Address {
93 fn to_address(&self) -> chartulary::Address {
94 chartulary::Address::new(self.as_url_str())
95 }
96}
97
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
105#[rkyv(derive(Debug, PartialEq))]
106pub enum AddressRole {
107 Primary,
109 Alias,
112}
113
114#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
120#[rkyv(derive(Debug, PartialEq))]
121pub struct AddressClaim {
122 pub address: Address,
123 pub role: AddressRole,
124}
125
126impl AddressClaim {
127 pub fn primary(address: Address) -> Self {
129 Self {
130 address,
131 role: AddressRole::Primary,
132 }
133 }
134
135 pub fn alias(address: Address) -> Self {
137 Self {
138 address,
139 role: AddressRole::Alias,
140 }
141 }
142
143 pub fn is_primary(&self) -> bool {
145 matches!(self.role, AddressRole::Primary)
146 }
147}
148
149pub fn address_from_url(url: &str) -> Address {
154 let lower = url.to_ascii_lowercase();
155 if lower.starts_with("http://") || lower.starts_with("https://") {
156 Address::Http(url.to_owned())
157 } else if lower.starts_with("data:") {
158 Address::Data(url.to_owned())
159 } else if lower.starts_with("verso://clip/") || lower.starts_with("graphshell://clip/") {
160 Address::Clip(url.to_owned())
161 } else if lower.starts_with("file://") {
162 if file_url_uses_directory_syntax(url) {
163 Address::Directory(url.to_owned())
164 } else {
165 Address::File(url.to_owned())
166 }
167 } else {
168 Address::Custom(url.to_owned())
169 }
170}
171
172pub fn address_kind_from_url(url: &str) -> AddressKind {
174 let lower = url.to_ascii_lowercase();
175 if lower.starts_with("http://") || lower.starts_with("https://") {
176 AddressKind::Http
177 } else if lower.starts_with("data:") {
178 AddressKind::Data
179 } else if lower.starts_with("verso://clip/") || lower.starts_with("graphshell://clip/") {
180 AddressKind::GraphshellClip
181 } else if lower.starts_with("file://") {
182 if file_url_uses_directory_syntax(url) {
183 AddressKind::Directory
184 } else {
185 AddressKind::File
186 }
187 } else {
188 AddressKind::Unknown
189 }
190}
191
192fn file_url_uses_directory_syntax(url: &str) -> bool {
193 url::Url::parse(url)
196 .ok()
197 .is_some_and(|parsed| parsed.path().ends_with('/'))
198}
199
200pub fn cached_host_from_url(url: &str) -> Option<String> {
201 url::Url::parse(url)
202 .ok()
203 .and_then(|parsed| parsed.host_str().map(str::to_owned))
204}
205
206pub fn detect_mime(url: &str, content_bytes: Option<&[u8]>) -> Option<String> {
215 let no_fragment = url.split('#').next().unwrap_or(url);
216 let no_query = no_fragment.split('?').next().unwrap_or(no_fragment);
217 let path = no_query
219 .strip_prefix("file://")
220 .unwrap_or(no_query)
221 .trim_start_matches('/');
222 let guess_path = format!("/{path}");
224 let guessed: Vec<String> = mime_guess::from_path(&guess_path)
225 .into_iter()
226 .map(|m| m.to_string())
227 .collect();
228
229 let is_ambiguous = guessed.len() > 1
230 || guessed
231 .first()
232 .map(|m| m == "application/octet-stream")
233 .unwrap_or(false);
234
235 if !guessed.is_empty() && !is_ambiguous {
236 return guessed.first().cloned();
237 }
238
239 if let Some(bytes) = content_bytes {
240 if let Some(kind) = infer::get(bytes) {
241 return Some(kind.mime_type().to_string());
242 }
243 }
244
245 guessed.first().cloned()
246}
247
248#[cfg(test)]
249mod tests {
250 use super::*;
251
252 #[test]
253 fn detect_mime_returns_pdf_for_pdf_path() {
254 assert_eq!(
255 detect_mime("file:///home/user/document.pdf", None),
256 Some("application/pdf".to_string())
257 );
258 }
259
260 #[test]
261 fn detect_mime_returns_text_plain_for_txt_path() {
262 assert_eq!(
263 detect_mime("file:///notes/readme.txt", None),
264 Some("text/plain".to_string())
265 );
266 }
267
268 #[test]
269 fn detect_mime_returns_none_for_no_extension() {
270 assert!(detect_mime("https://example.com/page", None).is_none());
271 }
272
273 #[test]
274 fn detect_mime_uses_magic_bytes_when_extension_is_missing() {
275 let pdf_header = b"%PDF-1.7\n1 0 obj\n";
276 assert_eq!(
277 detect_mime("https://example.com/no-extension", Some(pdf_header)),
278 Some("application/pdf".to_string())
279 );
280 }
281
282 #[test]
283 fn detect_mime_prefers_extension_when_unambiguous() {
284 let pdf_header = b"%PDF-1.7\n1 0 obj\n";
285 assert_eq!(
286 detect_mime("file:///home/user/readme.txt", Some(pdf_header)),
287 Some("text/plain".to_string())
288 );
289 }
290
291 #[test]
292 fn detect_mime_falls_back_to_extension_when_magic_unknown() {
293 let unknown = b"not a known magic signature";
294 assert_eq!(
295 detect_mime("file:///home/user/data.json", Some(unknown)),
296 Some("application/json".to_string())
297 );
298 }
299
300 #[test]
301 fn address_kind_from_url_http() {
302 assert_eq!(
303 address_kind_from_url("http://example.com"),
304 AddressKind::Http
305 );
306 assert_eq!(
307 address_kind_from_url("https://example.com"),
308 AddressKind::Http
309 );
310 }
311
312 #[test]
313 fn address_kind_from_url_file() {
314 assert_eq!(
315 address_kind_from_url("file:///home/user/file.txt"),
316 AddressKind::File
317 );
318 }
319
320 #[test]
321 fn address_kind_from_url_data_clip_directory_and_unknown() {
322 assert_eq!(
323 address_kind_from_url("data:text/plain,hello"),
324 AddressKind::Data
325 );
326 assert_eq!(
327 address_kind_from_url("verso://clip/clip-123"),
328 AddressKind::GraphshellClip
329 );
330 assert_eq!(
331 address_kind_from_url("file:///tmp/sample-dir/"),
332 AddressKind::Directory
333 );
334 assert_eq!(
335 address_kind_from_url("gemini://gemini.circumlunar.space/"),
336 AddressKind::Unknown
337 );
338 assert_eq!(
339 address_kind_from_url("ftp://files.example.com/"),
340 AddressKind::Unknown
341 );
342 }
343
344 #[test]
345 fn address_kind_from_url_file_directory_classification_is_syntax_based() {
346 assert_eq!(
347 address_kind_from_url("file:///tmp/sample-dir/"),
348 AddressKind::Directory
349 );
350 assert_eq!(
351 address_kind_from_url("file:///tmp/sample-dir"),
352 AddressKind::File
353 );
354 }
355
356 #[test]
357 fn address_from_url_http() {
358 assert_eq!(
359 address_from_url("https://example.com"),
360 Address::Http("https://example.com".to_string())
361 );
362 assert_eq!(
363 address_from_url("http://example.com/path"),
364 Address::Http("http://example.com/path".to_string())
365 );
366 }
367
368 #[test]
369 fn address_from_url_file_and_directory() {
370 assert_eq!(
371 address_from_url("file:///home/user/file.txt"),
372 Address::File("file:///home/user/file.txt".to_string())
373 );
374 assert_eq!(
375 address_from_url("file:///tmp/mydir/"),
376 Address::Directory("file:///tmp/mydir/".to_string())
377 );
378 }
379
380 #[test]
381 fn address_from_url_data_and_custom() {
382 assert_eq!(
383 address_from_url("data:text/plain,hello"),
384 Address::Data("data:text/plain,hello".to_string())
385 );
386 assert_eq!(
387 address_from_url("gemini://gemini.circumlunar.space/"),
388 Address::Custom("gemini://gemini.circumlunar.space/".to_string())
389 );
390 }
391
392 #[test]
393 fn address_from_url_clip_stores_full_url() {
394 assert_eq!(
395 address_from_url("verso://clip/clip-abc-123"),
396 Address::Clip("verso://clip/clip-abc-123".to_string())
397 );
398 assert_eq!(
399 address_from_url("graphshell://clip/clip-xyz"),
400 Address::Clip("graphshell://clip/clip-xyz".to_string())
401 );
402 }
403
404 #[test]
405 fn address_as_url_str_roundtrips_for_all_variants() {
406 let cases = [
407 "https://example.com",
408 "file:///home/user/file.txt",
409 "file:///tmp/mydir/",
410 "data:text/plain,hello",
411 "gemini://example.com/",
412 "verso://clip/clip-abc",
413 "graphshell://clip/clip-xyz",
414 ];
415 for url in cases {
416 let addr = address_from_url(url);
417 assert_eq!(
418 addr.as_url_str(),
419 url,
420 "as_url_str should return the original URL for {url}"
421 );
422 }
423 }
424
425 #[test]
426 fn address_address_kind_bridge_matches_legacy_inference() {
427 let cases = [
428 ("https://example.com", AddressKind::Http),
429 ("http://example.com", AddressKind::Http),
430 ("file:///home/user/file.txt", AddressKind::File),
431 ("file:///tmp/mydir/", AddressKind::Directory),
432 ("data:text/plain,hello", AddressKind::Data),
433 ("verso://clip/clip-123", AddressKind::GraphshellClip),
434 ("graphshell://clip/clip-456", AddressKind::GraphshellClip),
435 ("gemini://example.com/", AddressKind::Unknown),
436 ];
437 for (url, expected_kind) in cases {
438 assert_eq!(
439 address_from_url(url).address_kind(),
440 expected_kind,
441 "address_kind() mismatch for {url}"
442 );
443 assert_eq!(
444 address_kind_from_url(url),
445 expected_kind,
446 "address_kind_from_url mismatch for {url}"
447 );
448 }
449 }
450}