endpoint-libs 4.2.0

Launch MCP services fast: describe endpoints once in RON, and endpoint-gen generates the Rust models, docs and MCP tool schemas that this crate serves over WebSocket RPC, with roles and typed errors built in.
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
#![cfg_attr(test, allow(deprecated))]
#![cfg_attr(not(any(feature = "std", feature = "std-deps")), no_std)]

extern crate alloc;

#[cfg(not(any(feature = "std", feature = "std-deps")))]
#[doc(hidden)]
pub mod eyre {
    use alloc::boxed::Box;
    use alloc::format;
    use alloc::string::{String, ToString};
    use core::any::Any;
    use core::fmt::{self, Debug, Display};

    pub type Result<T, E = Report> = core::result::Result<T, E>;
    pub type Error = Report;

    pub trait EyreHandler: Any + Send + Sync {
        fn display(
            &self,
            error: &(dyn core::error::Error + 'static),
            f: &mut fmt::Formatter<'_>,
        ) -> fmt::Result;

        fn debug(
            &self,
            error: &(dyn core::error::Error + 'static),
            f: &mut fmt::Formatter<'_>,
        ) -> fmt::Result;

        fn track_caller(&mut self, _location: &'static core::panic::Location<'static>) {}
    }

    pub struct DefaultHandler;

    impl DefaultHandler {
        pub fn default_with(_error: &(dyn core::error::Error + 'static)) -> Box<dyn EyreHandler> {
            Box::new(DefaultHandler)
        }
    }

    impl EyreHandler for DefaultHandler {
        fn display(
            &self,
            error: &(dyn core::error::Error + 'static),
            f: &mut fmt::Formatter<'_>,
        ) -> fmt::Result {
            Display::fmt(error, f)
        }

        fn debug(
            &self,
            error: &(dyn core::error::Error + 'static),
            f: &mut fmt::Formatter<'_>,
        ) -> fmt::Result {
            Debug::fmt(error, f)
        }
    }

    trait ErrorObj: Any + Send + Sync + Display + Debug {
        fn as_any(&self) -> &(dyn Any + Send + Sync);
        fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync>;
        fn as_core_error(&self) -> &(dyn core::error::Error + 'static);
    }

    struct WrappedError<E>(E);

    impl<E: Display> Display for WrappedError<E> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            Display::fmt(&self.0, f)
        }
    }

    impl<E: Debug> Debug for WrappedError<E> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            Debug::fmt(&self.0, f)
        }
    }

    impl<E: Display + Debug> core::error::Error for WrappedError<E> {}

    impl<E: Display + Debug + Send + Sync + 'static> ErrorObj for WrappedError<E> {
        fn as_any(&self) -> &(dyn Any + Send + Sync) {
            &self.0
        }
        fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync> {
            Box::new(self.0)
        }
        fn as_core_error(&self) -> &(dyn core::error::Error + 'static) {
            self
        }
    }

    pub struct Report {
        inner: Box<dyn ErrorObj>,
        handler: Box<dyn EyreHandler>,
    }

    impl Report {
        #[track_caller]
        pub fn new<E>(error: E) -> Self
        where
            E: Display + Debug + Send + Sync + 'static,
        {
            let location = core::panic::Location::caller();
            let wrapped = Box::new(WrappedError(error));
            let mut handler = DefaultHandler::default_with(wrapped.as_core_error());
            handler.track_caller(location);
            Self {
                inner: wrapped,
                handler,
            }
        }

        #[track_caller]
        pub fn msg<M>(message: M) -> Self
        where
            M: Display + Debug + Send + Sync + 'static,
        {
            Self::new(message)
        }

        pub fn wrap_err<D>(self, msg: D) -> Self
        where
            D: Display + Send + Sync + 'static,
        {
            Self::msg(format!("{msg}: {}", self.inner))
        }

        pub fn handler(&self) -> &(dyn Any + Send + Sync) {
            &*self.handler
        }

        pub fn is<T: Any + Send + Sync + 'static>(&self) -> bool {
            self.inner.as_any().is::<T>()
        }

        pub fn downcast_ref<T: Any + Send + Sync + 'static>(&self) -> Option<&T> {
            self.inner.as_any().downcast_ref::<T>()
        }

        pub fn downcast<T: Any + Send + Sync + 'static>(self) -> core::result::Result<T, Self> {
            if self.is::<T>() {
                match self.inner.into_any().downcast::<T>() {
                    Ok(boxed) => Ok(*boxed),
                    Err(_) => unreachable!(),
                }
            } else {
                Err(self)
            }
        }
    }

    impl AsRef<dyn core::error::Error + 'static> for Report {
        fn as_ref(&self) -> &(dyn core::error::Error + 'static) {
            self.inner.as_core_error()
        }
    }

    impl Display for Report {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.handler.display(self.inner.as_core_error(), f)
        }
    }

    impl Debug for Report {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.handler.debug(self.inner.as_core_error(), f)
        }
    }

    impl<E> From<E> for Report
    where
        E: core::error::Error + Send + Sync + 'static,
    {
        #[track_caller]
        fn from(error: E) -> Self {
            Self::new(error)
        }
    }

    pub trait WrapErr<T, E> {
        fn wrap_err<D>(self, msg: D) -> Result<T, Report>
        where
            D: Display + Send + Sync + 'static;

        fn wrap_err_with<D, F>(self, f: F) -> Result<T, Report>
        where
            D: Display + Send + Sync + 'static,
            F: FnOnce() -> D;

        fn context<D>(self, msg: D) -> Result<T, Report>
        where
            D: Display + Send + Sync + 'static,
            Self: Sized,
        {
            self.wrap_err(msg)
        }

        fn with_context<D, F>(self, f: F) -> Result<T, Report>
        where
            D: Display + Send + Sync + 'static,
            F: FnOnce() -> D,
            Self: Sized,
        {
            self.wrap_err_with(f)
        }
    }

    pub use WrapErr as Context;

    impl<T, E> WrapErr<T, E> for core::result::Result<T, E>
    where
        E: Into<Report>,
    {
        #[track_caller]
        fn wrap_err<D>(self, msg: D) -> Result<T, Report>
        where
            D: Display + Send + Sync + 'static,
        {
            match self {
                Ok(v) => Ok(v),
                Err(e) => Err(e.into().wrap_err(msg)),
            }
        }

        #[track_caller]
        fn wrap_err_with<D, F>(self, f: F) -> Result<T, Report>
        where
            D: Display + Send + Sync + 'static,
            F: FnOnce() -> D,
        {
            match self {
                Ok(v) => Ok(v),
                Err(e) => Err(e.into().wrap_err(f())),
            }
        }
    }

    pub trait ContextCompat<T> {
        fn context<D>(self, msg: D) -> Result<T, Report>
        where
            D: Display + Send + Sync + 'static;

        fn with_context<D, F>(self, f: F) -> Result<T, Report>
        where
            D: Display + Send + Sync + 'static,
            F: FnOnce() -> D;

        fn wrap_err<D>(self, msg: D) -> Result<T, Report>
        where
            D: Display + Send + Sync + 'static,
            Self: Sized,
        {
            self.context(msg)
        }

        fn wrap_err_with<D, F>(self, f: F) -> Result<T, Report>
        where
            D: Display + Send + Sync + 'static,
            F: FnOnce() -> D,
            Self: Sized,
        {
            self.with_context(f)
        }
    }

    impl<T> ContextCompat<T> for Option<T> {
        #[track_caller]
        fn context<D>(self, msg: D) -> Result<T, Report>
        where
            D: Display + Send + Sync + 'static,
        {
            match self {
                Some(v) => Ok(v),
                None => Err(Report::msg(msg.to_string())),
            }
        }

        #[track_caller]
        fn with_context<D, F>(self, f: F) -> Result<T, Report>
        where
            D: Display + Send + Sync + 'static,
            F: FnOnce() -> D,
        {
            match self {
                Some(v) => Ok(v),
                None => Err(Report::msg(f().to_string())),
            }
        }
    }

    pub use crate::{
        __endpoint_libs_bail as bail, __endpoint_libs_ensure as ensure,
        __endpoint_libs_eyre as eyre,
    };
}

#[cfg(not(any(feature = "std", feature = "std-deps")))]
#[doc(hidden)]
#[macro_export]
macro_rules! __endpoint_libs_eyre {
    ($msg:literal $(,)?) => {
        $crate::eyre::Report::msg(::alloc::format!($msg))
    };
    ($err:expr $(,)?) => {
        $crate::eyre::Report::msg(::alloc::format!("{}", $err))
    };
    ($fmt:expr, $($arg:tt)*) => {
        $crate::eyre::Report::msg(::alloc::format!($fmt, $($arg)*))
    };
}

#[cfg(not(any(feature = "std", feature = "std-deps")))]
#[doc(hidden)]
#[macro_export]
macro_rules! __endpoint_libs_bail {
    ($($tt:tt)*) => {
        return ::core::result::Result::Err($crate::__endpoint_libs_eyre!($($tt)*))
    };
}

#[cfg(not(any(feature = "std", feature = "std-deps")))]
#[doc(hidden)]
#[macro_export]
macro_rules! __endpoint_libs_ensure {
    ($cond:expr, $($tt:tt)*) => {
        if !($cond) {
            $crate::__endpoint_libs_bail!($($tt)*);
        }
    };
    ($cond:expr) => {
        if !($cond) {
            $crate::__endpoint_libs_bail!(concat!("Condition failed: `", stringify!($cond), "`"));
        }
    };
}

#[cfg(not(feature = "std"))]
#[doc(hidden)]
pub mod convert_case {
    use alloc::string::String;
    use alloc::vec::Vec;

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub enum Case {
        Snake,
        Camel,
        Pascal,
    }

    fn split_words(input: &str) -> Vec<String> {
        let mut words = Vec::new();
        let mut current = String::new();
        let chars: Vec<char> = input.chars().collect();
        for i in 0..chars.len() {
            let ch = chars[i];
            if !ch.is_alphanumeric() {
                if !current.is_empty() {
                    words.push(core::mem::take(&mut current));
                }
                continue;
            }
            if i > 0 && ch.is_uppercase() {
                let prev = chars[i - 1];
                let next_lower = chars.get(i + 1).is_some_and(|n| n.is_lowercase());
                if prev.is_lowercase() || prev.is_numeric() || (prev.is_uppercase() && next_lower) {
                    if !current.is_empty() {
                        words.push(core::mem::take(&mut current));
                    }
                }
            }
            current.push(ch);
        }
        if !current.is_empty() {
            words.push(current);
        }
        words
    }

    fn capitalize(word: &str) -> String {
        let mut chars = word.chars();
        match chars.next() {
            None => String::new(),
            Some(first) => {
                let mut out = String::new();
                for c in first.to_uppercase() {
                    out.push(c);
                }
                for c in chars {
                    for lc in c.to_lowercase() {
                        out.push(lc);
                    }
                }
                out
            }
        }
    }

    fn lowercase(word: &str) -> String {
        let mut out = String::new();
        for c in word.chars() {
            for lc in c.to_lowercase() {
                out.push(lc);
            }
        }
        out
    }

    pub trait Casing {
        fn to_case(&self, case: Case) -> String;
    }

    impl<T: AsRef<str> + ?Sized> Casing for T {
        fn to_case(&self, case: Case) -> String {
            let words = split_words(self.as_ref());
            match case {
                Case::Snake => {
                    let mut out = String::new();
                    for (i, w) in words.iter().enumerate() {
                        if i > 0 {
                            out.push('_');
                        }
                        out.push_str(&lowercase(w));
                    }
                    out
                }
                Case::Pascal => {
                    let mut out = String::new();
                    for w in &words {
                        out.push_str(&capitalize(w));
                    }
                    out
                }
                Case::Camel => {
                    let mut out = String::new();
                    for (i, w) in words.iter().enumerate() {
                        if i == 0 {
                            out.push_str(&lowercase(w));
                        } else {
                            out.push_str(&capitalize(w));
                        }
                    }
                    out
                }
            }
        }
    }
}

#[cfg(not(feature = "std"))]
#[doc(hidden)]
pub mod urlencoding {
    use alloc::borrow::Cow;
    use alloc::string::String;
    use alloc::vec::Vec;
    use core::fmt;

    #[derive(Debug)]
    pub struct FromUrlEncodingError;

    impl fmt::Display for FromUrlEncodingError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("invalid percent-encoded UTF-8 sequence")
        }
    }

    impl core::error::Error for FromUrlEncodingError {}

    pub fn encode(data: &str) -> Cow<'_, str> {
        let bytes = data.as_bytes();
        let safe = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~');
        if bytes.iter().copied().all(safe) {
            return Cow::Borrowed(data);
        }
        const HEX: &[u8; 16] = b"0123456789ABCDEF";
        let mut out = String::with_capacity(bytes.len() * 3);
        for &b in bytes {
            if safe(b) {
                out.push(b as char);
            } else {
                out.push('%');
                out.push(HEX[(b >> 4) as usize] as char);
                out.push(HEX[(b & 0x0f) as usize] as char);
            }
        }
        Cow::Owned(out)
    }

    pub fn decode(data: &str) -> Result<Cow<'_, str>, FromUrlEncodingError> {
        let bytes = data.as_bytes();
        if !bytes.contains(&b'%') {
            return Ok(Cow::Borrowed(data));
        }
        let hex = |b: u8| -> Result<u8, FromUrlEncodingError> {
            match b {
                b'0'..=b'9' => Ok(b - b'0'),
                b'a'..=b'f' => Ok(b - b'a' + 10),
                b'A'..=b'F' => Ok(b - b'A' + 10),
                _ => Err(FromUrlEncodingError),
            }
        };
        let mut out = Vec::with_capacity(bytes.len());
        let mut i = 0;
        while i < bytes.len() {
            if bytes[i] == b'%' {
                if i + 2 >= bytes.len() {
                    return Err(FromUrlEncodingError);
                }
                out.push((hex(bytes[i + 1])? << 4) | hex(bytes[i + 2])?);
                i += 3;
            } else {
                out.push(bytes[i]);
                i += 1;
            }
        }
        String::from_utf8(out)
            .map(Cow::Owned)
            .map_err(|_| FromUrlEncodingError)
    }
}

pub mod libs;
#[cfg(feature = "types")]
pub mod model;