1use js_sys::{Function, Promise, Reflect};
5use serde::{Serialize, de::DeserializeOwned};
6use serde_wasm_bindgen::{from_value, to_value};
7use wasm_bindgen::{JsCast, JsValue, prelude::Closure};
8use wasm_bindgen_futures::JsFuture;
9use web_sys::window;
10
11#[derive(Clone, Debug, PartialEq)]
18pub struct EndpointError {
19 pub message: String,
21
22 pub kind: String,
26
27 pub status: u16,
30
31 pub parameters: Option<JsValue>
33}
34
35impl EndpointError {
36 #[must_use]
42 pub fn from_js_value(value: &JsValue) -> Self {
43 let read_string = |key: &str| {
44 Reflect::get(value, &JsValue::from_str(key))
45 .ok()
46 .and_then(|field| field.as_string())
47 };
48 let message = read_string("message")
49 .or_else(|| value.as_string())
50 .unwrap_or_else(|| "unknown Serverless failure".to_string());
51 let kind = read_string("type").unwrap_or_default();
52 let status = Reflect::get(value, &JsValue::from_str("status"))
53 .ok()
54 .and_then(|field| field.as_f64())
55 .and_then(|code| code.trunc().to_string().parse::<u16>().ok())
56 .unwrap_or(0);
57 let parameters = Reflect::get(value, &JsValue::from_str("parameters"))
58 .ok()
59 .filter(|field| !field.is_undefined() && !field.is_null());
60 Self {
61 message,
62 kind,
63 status,
64 parameters
65 }
66 }
67
68 const fn client_error(message: String) -> Self {
69 Self {
70 message,
71 kind: String::new(),
72 status: 0,
73 parameters: None
74 }
75 }
76
77 #[must_use]
97 pub fn hint(&self) -> &'static str {
98 match self.kind.as_str() {
99 "ENDPOINT_ERROR" => {
100 "the endpoint refused the call; show `message` to the user and branch on \
101 machine-readable codes placed inside `parameters`"
102 }
103 "UNAUTHORIZED" => {
104 "initData is missing or invalid; call init_sdk() before any Serverless call \
105 and reopen the Mini App link from the bot to obtain fresh initData"
106 }
107 "PAYMENT_REQUIRED" => {
108 "the Mini App paid membership is missing or expired; ask the user to renew \
109 via Telegram.WebApp.openInvoice"
110 }
111 "FORBIDDEN" => "the user blocked the bot or access to this endpoint was revoked",
112 "NOT_FOUND" => {
113 "no endpoint with this name is deployed; check the name against the bot's \
114 Serverless configuration in BotFather"
115 }
116 "TOO_MANY_REQUESTS" => {
117 "rate limited; back off and retry later, honoring retry_after in `parameters` \
118 when present"
119 }
120 _ if self.message.contains("InitDataUnavailable") => {
121 "call init_sdk() before any Serverless call so the bridge can send initData"
122 }
123 _ if self.status == 429 => "rate limited; back off and retry later",
124 _ if self.status >= 500 => {
125 "the endpoint or the platform failed on Telegram's side; retry with \
126 exponential backoff"
127 }
128 _ if self.status >= 400 => {
129 "the request was rejected; validate the input payload against the endpoint \
130 contract"
131 }
132 _ => {
133 "the call did not reach the endpoint; run inside Telegram with network access \
134 and make sure Serverless is enabled for the bot in BotFather"
135 }
136 }
137 }
138}
139
140impl std::fmt::Display for EndpointError {
141 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142 write!(f, "serverless call failed: {}", self.message)?;
143 if !self.kind.is_empty() {
144 write!(f, " [{}]", self.kind)?;
145 }
146 if self.status != 0 {
147 write!(f, " (status {})", self.status)?;
148 }
149 write!(f, " — {}", self.hint())
150 }
151}
152
153impl std::error::Error for EndpointError {}
154
155impl From<EndpointError> for JsValue {
156 fn from(error: EndpointError) -> Self {
157 Self::from_str(&error.to_string())
158 }
159}
160
161pub async fn call_raw(name: &str, input: &JsValue) -> Result<JsValue, EndpointError> {
184 let win = window().ok_or_else(|| EndpointError::client_error("no window".to_string()))?;
185 let serverless = Reflect::get(&win, &JsValue::from_str("Telegram"))
186 .and_then(|telegram| Reflect::get(&telegram, &JsValue::from_str("WebApp")))
187 .and_then(|webapp| Reflect::get(&webapp, &JsValue::from_str("Serverless")))
188 .map_err(|error| EndpointError::from_js_value(&error))?;
189 let call_fn = Reflect::get(&serverless, &JsValue::from_str("call"))
190 .and_then(JsCast::dyn_into::<Function>)
191 .map_err(|error| EndpointError::from_js_value(&error))?;
192 let endpoint = JsValue::from_str(name);
193 let input = if input.is_null() {
194 JsValue::UNDEFINED
195 } else {
196 input.clone()
197 };
198 let promise = Promise::new(&mut |resolve, reject| {
199 let callback = Closure::once_into_js({
200 let reject = reject.clone();
201 move |error: JsValue, result: JsValue| {
202 if error.is_null() || error.is_undefined() {
203 let _ = resolve.call1(&JsValue::NULL, &result);
204 } else {
205 let _ = reject.call1(&JsValue::NULL, &error);
206 }
207 }
208 });
209 if let Err(error) = call_fn.call3(&serverless, &endpoint, &input, &callback) {
210 let _ = reject.call1(&JsValue::NULL, &error);
211 }
212 });
213 JsFuture::from(promise)
214 .await
215 .map_err(|error| EndpointError::from_js_value(&error))
216}
217
218pub async fn call<I, O>(name: &str, input: &I) -> Result<O, EndpointError>
254where
255 I: Serialize + ?Sized,
256 O: DeserializeOwned
257{
258 let payload = to_value(input).map_err(|error| {
259 EndpointError::client_error(format!("failed to serialize input: {error}"))
260 })?;
261 let result = call_raw(name, &payload).await?;
262 from_value(result).map_err(|error| {
263 EndpointError::client_error(format!("failed to deserialize result: {error}"))
264 })
265}
266
267#[cfg(test)]
268mod tests {
269 use js_sys::Object;
270 use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure};
271
272 use super::*;
273
274 wasm_bindgen_test_configure!(run_in_browser);
275
276 #[derive(Debug, PartialEq, serde::Serialize)]
277 struct TypedInput {
278 lang: String
279 }
280
281 #[derive(Debug, PartialEq, serde::Deserialize)]
282 struct TypedOutput {
283 id: f64
284 }
285
286 fn install_serverless(body: &str) -> Result<Object, JsValue> {
287 let win = window().ok_or_else(|| JsValue::from_str("no window"))?;
288 let telegram = Object::new();
289 let webapp = Object::new();
290 let serverless = Object::new();
291 let func = Function::new_with_args("name, input, callback", body);
292 Reflect::set(&serverless, &"call".into(), &func)?;
293 Reflect::set(&webapp, &"Serverless".into(), &serverless)?;
294 Reflect::set(&telegram, &"WebApp".into(), &webapp)?;
295 Reflect::set(&win, &"Telegram".into(), &telegram)?;
296 Ok(serverless)
297 }
298
299 #[wasm_bindgen_test(async)]
300 async fn call_raw_resolves_with_endpoint_result() -> Result<(), JsValue> {
301 let serverless = install_serverless("this.lastName = name; callback(null, { id: 42 });")?;
302 let result = call_raw("getProfile", &JsValue::UNDEFINED).await?;
303 assert_eq!(Reflect::get(&result, &"id".into())?.as_f64(), Some(42.0));
304 assert_eq!(
305 Reflect::get(&serverless, &"lastName".into())?.as_string(),
306 Some("getProfile".to_string())
307 );
308 Ok(())
309 }
310
311 #[wasm_bindgen_test(async)]
312 async fn call_raw_rejects_with_endpoint_error() -> Result<(), JsValue> {
313 install_serverless(
314 "var err = Error('boom'); err.name = 'ServerlessError'; err.status = 403; \
315 err.type = 'UNAUTHORIZED'; err.parameters = { retryAfter: 5 }; callback(err, null);"
316 )?;
317 let error = call_raw("x", &JsValue::UNDEFINED)
318 .await
319 .expect_err("endpoint must fail");
320 assert_eq!(error.message, "boom");
321 assert_eq!(error.kind, "UNAUTHORIZED");
322 assert_eq!(error.status, 403);
323 assert!(error.parameters.is_some());
324 Ok(())
325 }
326
327 #[wasm_bindgen_test(async)]
328 async fn call_raw_maps_synchronous_throw() -> Result<(), JsValue> {
329 install_serverless("throw Error('WebAppServerlessInitDataUnavailable');")?;
330 let error = call_raw("x", &JsValue::UNDEFINED)
331 .await
332 .expect_err("throw must reject");
333 assert_eq!(error.message, "WebAppServerlessInitDataUnavailable");
334 assert_eq!(error.status, 0);
335 assert_eq!(error.kind, "");
336 Ok(())
337 }
338
339 #[wasm_bindgen_test(async)]
340 async fn call_raw_fails_without_serverless_object() -> Result<(), JsValue> {
341 let win = window().ok_or_else(|| JsValue::from_str("no window"))?;
342 Reflect::set(&win, &"Telegram".into(), &JsValue::UNDEFINED)?;
343 let error = call_raw("x", &JsValue::UNDEFINED)
344 .await
345 .expect_err("bridge must be missing");
346 assert_eq!(error.status, 0);
347 Ok(())
348 }
349
350 #[wasm_bindgen_test(async)]
351 async fn call_round_trips_typed_payload() -> Result<(), JsValue> {
352 install_serverless("callback(null, { id: input.lang === 'en' ? 7 : 0 });")?;
353 let out: TypedOutput = call(
354 "x",
355 &TypedInput {
356 lang: "en".into()
357 }
358 )
359 .await?;
360 assert_eq!(
361 out,
362 TypedOutput {
363 id: 7.0
364 }
365 );
366 Ok(())
367 }
368
369 #[wasm_bindgen_test(async)]
370 async fn call_reports_deserialization_failure() -> Result<(), JsValue> {
371 install_serverless("callback(null, 'not-an-object');")?;
372 let result: Result<TypedOutput, _> = call("x", &()).await;
373 let error = result.expect_err("shape mismatch must fail");
374 assert!(error.message.contains("deserialize"));
375 assert_eq!(error.status, 0);
376 Ok(())
377 }
378
379 #[wasm_bindgen_test]
380 fn endpoint_error_display_carries_kind_status_and_hint() {
381 let error = EndpointError {
382 message: "boom".to_string(),
383 kind: "UNAUTHORIZED".to_string(),
384 status: 401,
385 parameters: None
386 };
387 let text = error.to_string();
388 assert!(text.contains("serverless call failed: boom"));
389 assert!(text.contains("[UNAUTHORIZED]"));
390 assert!(text.contains("(status 401)"));
391 assert!(text.contains("initData"));
392 }
393
394 #[wasm_bindgen_test]
395 fn endpoint_error_hint_falls_back_to_status_class() {
396 let unclassified = EndpointError {
397 message: "gateway exploded".to_string(),
398 kind: String::new(),
399 status: 502,
400 parameters: None
401 };
402 assert!(unclassified.hint().contains("backoff"));
403 assert!(unclassified.to_string().contains("(status 502)"));
404
405 let unreach = EndpointError {
406 message: "bridge missing".to_string(),
407 kind: String::new(),
408 status: 0,
409 parameters: None
410 };
411 assert!(unreach.hint().contains("BotFather"));
412 }
413}