@tma.js/sdk-react 2.0.3 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/dts/SDKProvider/SDKContext.d.ts +8 -0
  2. package/dist/dts/SDKProvider/SDKProvider.d.ts +7 -0
  3. package/dist/dts/SDKProvider/SDKProvider.types.d.ts +39 -0
  4. package/dist/dts/createHOCs.d.ts +28 -0
  5. package/dist/dts/createHooks.d.ts +24 -0
  6. package/dist/dts/hooks-hocs/back-button.d.ts +2 -0
  7. package/dist/dts/hooks-hocs/biometry-manager.d.ts +2 -0
  8. package/dist/dts/hooks-hocs/closing-behavior.d.ts +2 -0
  9. package/dist/dts/hooks-hocs/cloud-storage.d.ts +2 -0
  10. package/dist/dts/hooks-hocs/haptic-feedback.d.ts +2 -0
  11. package/dist/dts/hooks-hocs/init-data.d.ts +2 -0
  12. package/dist/dts/hooks-hocs/invoice.d.ts +8 -0
  13. package/dist/dts/hooks-hocs/launch-params.d.ts +6 -0
  14. package/dist/dts/hooks-hocs/main-button.d.ts +2 -0
  15. package/dist/dts/hooks-hocs/mini-app.d.ts +2 -0
  16. package/dist/dts/hooks-hocs/popup.d.ts +2 -0
  17. package/dist/dts/hooks-hocs/qr-scanner.d.ts +2 -0
  18. package/dist/dts/hooks-hocs/settings-button.d.ts +2 -0
  19. package/dist/dts/hooks-hocs/theme-params.d.ts +2 -0
  20. package/dist/dts/hooks-hocs/utils.d.ts +2 -0
  21. package/dist/dts/hooks-hocs/viewport.d.ts +2 -0
  22. package/dist/dts/index.d.ts +20 -4
  23. package/dist/index.cjs +2 -1
  24. package/dist/index.cjs.map +1 -0
  25. package/dist/index.js +2991 -0
  26. package/dist/index.js.map +1 -0
  27. package/package.json +9 -7
  28. package/dist/dts/DisplayGate.d.ts +0 -24
  29. package/dist/dts/createHoc.d.ts +0 -12
  30. package/dist/dts/createHook.d.ts +0 -13
  31. package/dist/dts/provider/SDKContext.d.ts +0 -3
  32. package/dist/dts/provider/SDKProvider.d.ts +0 -6
  33. package/dist/dts/provider/index.d.ts +0 -7
  34. package/dist/dts/provider/types.d.ts +0 -30
  35. package/dist/dts/provider/useInitResultDynamicValue.d.ts +0 -2
  36. package/dist/dts/provider/useInitResultValue.d.ts +0 -7
  37. package/dist/dts/provider/useSDKContext.d.ts +0 -5
  38. package/dist/dts/provider/withSDKContext.d.ts +0 -9
  39. package/dist/dts/tools/back-button.d.ts +0 -8
  40. package/dist/dts/tools/closing-behavior.d.ts +0 -8
  41. package/dist/dts/tools/cloud-storage.d.ts +0 -8
  42. package/dist/dts/tools/haptic-feedback.d.ts +0 -8
  43. package/dist/dts/tools/index.d.ts +0 -17
  44. package/dist/dts/tools/init-data-raw.d.ts +0 -8
  45. package/dist/dts/tools/init-data.d.ts +0 -8
  46. package/dist/dts/tools/invoice.d.ts +0 -8
  47. package/dist/dts/tools/launch-params.d.ts +0 -13
  48. package/dist/dts/tools/main-button.d.ts +0 -8
  49. package/dist/dts/tools/mini-app.d.ts +0 -8
  50. package/dist/dts/tools/popup.d.ts +0 -8
  51. package/dist/dts/tools/post-event.d.ts +0 -8
  52. package/dist/dts/tools/qr-scanner.d.ts +0 -8
  53. package/dist/dts/tools/settings-button.d.ts +0 -8
  54. package/dist/dts/tools/theme-params.d.ts +0 -8
  55. package/dist/dts/tools/utils.d.ts +0 -8
  56. package/dist/dts/tools/viewport.d.ts +0 -8
  57. package/dist/dts/types.d.ts +0 -23
  58. package/dist/index.mjs +0 -138
package/dist/index.js ADDED
@@ -0,0 +1,2991 @@
1
+ import { jsx as vt } from "react/jsx-runtime";
2
+ import { createContext as te, useContext as ee, useMemo as st, useRef as lt, useState as se, useCallback as _t, useEffect as M } from "react";
3
+ var ne = Object.defineProperty, re = (e, t, s) => t in e ? ne(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s, c = (e, t, s) => (re(e, typeof t != "symbol" ? t + "" : t, s), s);
4
+ function yt(e, t) {
5
+ let s;
6
+ const n = () => {
7
+ s !== void 0 && t && t(s), s = void 0;
8
+ };
9
+ return [() => s === void 0 ? s = e(n) : s, n];
10
+ }
11
+ function Et(e) {
12
+ const t = G(), { count: s } = t;
13
+ t.unsubscribe(e), s && !t.count && Te();
14
+ }
15
+ function ie(e) {
16
+ return G().subscribe(e), () => Et(e);
17
+ }
18
+ class oe {
19
+ constructor(t, s = {}) {
20
+ this.scope = t, this.options = s;
21
+ }
22
+ /**
23
+ * Prints message into a console in case, logger is currently enabled.
24
+ * @param level - log level.
25
+ * @param args - arguments.
26
+ */
27
+ print(t, ...s) {
28
+ const n = /* @__PURE__ */ new Date(), r = Intl.DateTimeFormat("en-GB", {
29
+ hour: "2-digit",
30
+ minute: "2-digit",
31
+ second: "2-digit",
32
+ fractionalSecondDigits: 3,
33
+ timeZone: "UTC"
34
+ }).format(n), { textColor: i, bgColor: o } = this.options, a = "font-weight: bold;padding: 0 5px;border-radius:5px";
35
+ console[t](
36
+ `%c${r}%c / %c${this.scope}`,
37
+ `${a};background-color: lightblue;color:black`,
38
+ "",
39
+ `${a};${i ? `color:${i};` : ""}${o ? `background-color:${o}` : ""}`,
40
+ ...s
41
+ );
42
+ }
43
+ /**
44
+ * Prints error message into a console.
45
+ * @param args
46
+ */
47
+ error(...t) {
48
+ this.print("error", ...t);
49
+ }
50
+ /**
51
+ * Prints log message into a console.
52
+ * @param args
53
+ */
54
+ log(...t) {
55
+ this.print("log", ...t);
56
+ }
57
+ }
58
+ const H = new oe("SDK", {
59
+ bgColor: "forestgreen",
60
+ textColor: "white"
61
+ });
62
+ let X = !1;
63
+ const gt = ({ event: e, args: [t] }) => {
64
+ H.log("Event received:", t === void 0 ? { name: e } : { name: e, data: t });
65
+ };
66
+ function ae(e) {
67
+ X !== e && (X = e, e ? ie(gt) : Et(gt));
68
+ }
69
+ function ce(...e) {
70
+ X && H.log(...e);
71
+ }
72
+ class U {
73
+ constructor() {
74
+ c(this, "listeners", /* @__PURE__ */ new Map()), c(this, "listenersCount", 0), c(this, "subscribeListeners", []);
75
+ }
76
+ /**
77
+ * Removes all event listeners.
78
+ */
79
+ clear() {
80
+ this.listeners.clear(), this.subscribeListeners = [];
81
+ }
82
+ /**
83
+ * Returns count of bound listeners.
84
+ */
85
+ get count() {
86
+ return this.listenersCount + this.subscribeListeners.length;
87
+ }
88
+ emit(t, ...s) {
89
+ this.subscribeListeners.forEach((n) => n({
90
+ event: t,
91
+ args: s
92
+ })), (this.listeners.get(t) || []).forEach(([n, r]) => {
93
+ n(...s), r && this.off(t, n);
94
+ });
95
+ }
96
+ /**
97
+ * Adds new event listener.
98
+ * @param event - event name.
99
+ * @param listener - event listener.
100
+ * @param once - should listener be called only once.
101
+ * @returns Function to remove bound event listener.
102
+ */
103
+ on(t, s, n) {
104
+ let r = this.listeners.get(t);
105
+ return r || this.listeners.set(t, r = []), r.push([s, n]), this.listenersCount += 1, () => this.off(t, s);
106
+ }
107
+ /**
108
+ * Removes event listener. In case, specified listener was bound several times, it removes
109
+ * only a single one.
110
+ * @param event - event name.
111
+ * @param listener - event listener.
112
+ */
113
+ off(t, s) {
114
+ const n = this.listeners.get(t) || [];
115
+ for (let r = 0; r < n.length; r += 1)
116
+ if (s === n[r][0]) {
117
+ n.splice(r, 1), this.listenersCount -= 1;
118
+ return;
119
+ }
120
+ }
121
+ /**
122
+ * Adds a new event listener for all events.
123
+ * @param listener - event listener.
124
+ * @returns Function to remove event listener.
125
+ */
126
+ subscribe(t) {
127
+ return this.subscribeListeners.push(t), () => this.unsubscribe(t);
128
+ }
129
+ /**
130
+ * Removes global event listener. In case, specified listener was bound several times, it removes
131
+ * only a single one.
132
+ * @param listener - event listener.
133
+ */
134
+ unsubscribe(t) {
135
+ for (let s = 0; s < this.subscribeListeners.length; s += 1)
136
+ if (this.subscribeListeners[s] === t) {
137
+ this.subscribeListeners.splice(s, 1);
138
+ return;
139
+ }
140
+ }
141
+ }
142
+ function tt(e, t, s) {
143
+ return window.addEventListener(e, t, s), () => window.removeEventListener(e, t, s);
144
+ }
145
+ class W extends Error {
146
+ constructor(t, s, n) {
147
+ super(s, { cause: n }), this.type = t, Object.setPrototypeOf(this, W.prototype);
148
+ }
149
+ }
150
+ function l(e, t, s) {
151
+ return new W(e, t, s);
152
+ }
153
+ const he = "ERR_METHOD_UNSUPPORTED", pe = "ERR_METHOD_PARAMETER_UNSUPPORTED", ue = "ERR_UNKNOWN_ENV", de = "ERR_INVOKE_CUSTOM_METHOD_RESPONSE", le = "ERR_TIMED_OUT", _e = "ERR_UNEXPECTED_TYPE", Pt = "ERR_PARSE", ge = "ERR_NAVIGATION_LIST_EMPTY", we = "ERR_NAVIGATION_CURSOR_INVALID", _n = "ERR_NAVIGATION_ITEM_INVALID", nt = "ERR_SSR_INIT", fe = "ERR_SSR_POST_EVENT", me = "ERR_INVALID_PATH_BASE";
154
+ function T() {
155
+ return l(_e, "Value has unexpected type");
156
+ }
157
+ class j {
158
+ constructor(t, s, n) {
159
+ this.parser = t, this.isOptional = s, this.type = n;
160
+ }
161
+ /**
162
+ * Attempts to parse passed value
163
+ * @param value - value to parse.
164
+ * @throws {SDKError} ERR_PARSE
165
+ * @see ERR_PARSE
166
+ */
167
+ parse(t) {
168
+ if (!(this.isOptional && t === void 0))
169
+ try {
170
+ return this.parser(t);
171
+ } catch (s) {
172
+ throw l(
173
+ Pt,
174
+ `Unable to parse value${this.type ? ` as ${this.type}` : ""}`,
175
+ s
176
+ );
177
+ }
178
+ }
179
+ optional() {
180
+ return this.isOptional = !0, this;
181
+ }
182
+ }
183
+ function A(e, t) {
184
+ return () => new j(e, !1, t);
185
+ }
186
+ const P = A((e) => {
187
+ if (typeof e == "boolean")
188
+ return e;
189
+ const t = String(e);
190
+ if (t === "1" || t === "true")
191
+ return !0;
192
+ if (t === "0" || t === "false")
193
+ return !1;
194
+ throw T();
195
+ }, "boolean");
196
+ function Rt(e, t) {
197
+ const s = {};
198
+ for (const n in e) {
199
+ const r = e[n];
200
+ if (!r)
201
+ continue;
202
+ let i, o;
203
+ if (typeof r == "function" || "parse" in r)
204
+ i = n, o = typeof r == "function" ? r : r.parse.bind(r);
205
+ else {
206
+ const { type: a } = r;
207
+ i = r.from || n, o = typeof a == "function" ? a : a.parse.bind(a);
208
+ }
209
+ try {
210
+ const a = o(t(i));
211
+ a !== void 0 && (s[n] = a);
212
+ } catch (a) {
213
+ throw l(Pt, `Unable to parse field "${n}"`, a);
214
+ }
215
+ }
216
+ return s;
217
+ }
218
+ function rt(e) {
219
+ let t = e;
220
+ if (typeof t == "string" && (t = JSON.parse(t)), typeof t != "object" || t === null || Array.isArray(t))
221
+ throw T();
222
+ return t;
223
+ }
224
+ function f(e, t) {
225
+ return new j((s) => {
226
+ const n = rt(s);
227
+ return Rt(e, (r) => n[r]);
228
+ }, !1, t);
229
+ }
230
+ const x = A((e) => {
231
+ if (typeof e == "number")
232
+ return e;
233
+ if (typeof e == "string") {
234
+ const t = Number(e);
235
+ if (!Number.isNaN(t))
236
+ return t;
237
+ }
238
+ throw T();
239
+ }, "number");
240
+ function it(e) {
241
+ return /^#[\da-f]{6}$/i.test(e);
242
+ }
243
+ function be(e) {
244
+ return /^#[\da-f]{3}$/i.test(e);
245
+ }
246
+ function xt(e) {
247
+ const t = e.replace(/\s/g, "").toLowerCase();
248
+ if (it(t))
249
+ return t;
250
+ if (be(t)) {
251
+ let n = "#";
252
+ for (let r = 0; r < 3; r += 1)
253
+ n += t[1 + r].repeat(2);
254
+ return n;
255
+ }
256
+ const s = t.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/) || t.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);
257
+ if (!s)
258
+ throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);
259
+ return s.slice(1).reduce((n, r) => {
260
+ const i = parseInt(r, 10).toString(16);
261
+ return n + (i.length === 1 ? "0" : "") + i;
262
+ }, "#");
263
+ }
264
+ const h = A((e) => {
265
+ if (typeof e == "string" || typeof e == "number")
266
+ return e.toString();
267
+ throw T();
268
+ }, "string"), St = A((e) => xt(h().parse(e)), "rgb");
269
+ function ve(e) {
270
+ return f({
271
+ eventType: h(),
272
+ eventData: (t) => t
273
+ }).parse(e);
274
+ }
275
+ function ye() {
276
+ ["TelegramGameProxy_receiveEvent", "TelegramGameProxy", "Telegram"].forEach((e) => {
277
+ delete window[e];
278
+ });
279
+ }
280
+ function Ee(e, t) {
281
+ window.dispatchEvent(new MessageEvent("message", {
282
+ data: JSON.stringify({ eventType: e, eventData: t }),
283
+ // We specify window.parent to imitate the case, the parent iframe sent us this event.
284
+ source: window.parent
285
+ }));
286
+ }
287
+ function Pe() {
288
+ [
289
+ ["TelegramGameProxy_receiveEvent"],
290
+ // Windows Phone.
291
+ ["TelegramGameProxy", "receiveEvent"],
292
+ // Desktop.
293
+ ["Telegram", "WebView", "receiveEvent"]
294
+ // Android and iOS.
295
+ ].forEach((e) => {
296
+ let t = window;
297
+ e.forEach((s, n, r) => {
298
+ if (n === r.length - 1) {
299
+ t[s] = Ee;
300
+ return;
301
+ }
302
+ s in t || (t[s] = {}), t = t[s];
303
+ });
304
+ });
305
+ }
306
+ const Re = f({
307
+ button_id: (e) => e == null ? void 0 : h().parse(e)
308
+ }), xe = {
309
+ clipboard_text_received: f({
310
+ req_id: h(),
311
+ data: (e) => e === null ? e : h().optional().parse(e)
312
+ }),
313
+ custom_method_invoked: f({
314
+ req_id: h(),
315
+ result: (e) => e,
316
+ error: h().optional()
317
+ }),
318
+ invoice_closed: f({
319
+ slug: h(),
320
+ status: h()
321
+ }),
322
+ phone_requested: f({
323
+ status: h()
324
+ }),
325
+ popup_closed: {
326
+ parse: (e) => Re.parse(e ?? {})
327
+ },
328
+ qr_text_received: f({
329
+ data: h().optional()
330
+ }),
331
+ theme_changed: f({
332
+ theme_params: (e) => {
333
+ const t = St().optional();
334
+ return Object.entries(rt(e)).reduce((s, [n, r]) => (s[n] = t.parse(r), s), {});
335
+ }
336
+ }),
337
+ viewport_changed: f({
338
+ height: x(),
339
+ width: (e) => e == null ? window.innerWidth : x().parse(e),
340
+ is_state_stable: P(),
341
+ is_expanded: P()
342
+ }),
343
+ write_access_requested: f({
344
+ status: h()
345
+ })
346
+ };
347
+ function Se() {
348
+ const e = new U();
349
+ Pe();
350
+ let t = [
351
+ // Don't forget to remove created handlers.
352
+ ye,
353
+ // Add "resize" event listener to make sure, we always have fresh viewport information.
354
+ // Desktop version of Telegram is sometimes not sending the viewport_changed
355
+ // event. For example, when the MainButton is shown. That's why we should
356
+ // add our own listener to make sure, viewport information is always fresh.
357
+ // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/10
358
+ tt("resize", () => {
359
+ e.emit("viewport_changed", {
360
+ width: window.innerWidth,
361
+ height: window.innerHeight,
362
+ is_state_stable: !0,
363
+ is_expanded: !0
364
+ });
365
+ }),
366
+ // Add listener, which handles events sent from the Telegram web application and also events
367
+ // generated by the local emitEvent function.
368
+ tt("message", (s) => {
369
+ if (s.source !== window.parent)
370
+ return;
371
+ let n;
372
+ try {
373
+ n = ve(s.data);
374
+ } catch {
375
+ return;
376
+ }
377
+ const { eventType: r, eventData: i } = n, o = xe[r];
378
+ try {
379
+ const a = o ? o.parse(i) : i;
380
+ e.emit(...a ? [r, a] : [r]);
381
+ } catch (a) {
382
+ H.error(
383
+ `An error occurred processing the "${r}" event from the Telegram application. Please, file an issue here: https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,
384
+ n,
385
+ a
386
+ );
387
+ }
388
+ }),
389
+ // Clear emitter bound events.
390
+ () => e.clear()
391
+ ];
392
+ return [e, () => {
393
+ t.forEach((s) => s()), t = [];
394
+ }];
395
+ }
396
+ const [Ce, Te] = yt(
397
+ (e) => {
398
+ const [t, s] = Se(), n = t.off.bind(t);
399
+ return t.off = (r, i) => {
400
+ const { count: o } = t;
401
+ n(r, i), o && !t.count && e();
402
+ }, [t, s];
403
+ },
404
+ ([, e]) => e()
405
+ );
406
+ function G() {
407
+ return Ce()[0];
408
+ }
409
+ function z(e, t) {
410
+ G().off(e, t);
411
+ }
412
+ function E(e, t, s) {
413
+ return G().on(e, t, s);
414
+ }
415
+ function D(e) {
416
+ return typeof e == "object" && e !== null && !Array.isArray(e);
417
+ }
418
+ function Ae(e, t) {
419
+ const s = e.split("."), n = t.split("."), r = Math.max(s.length, n.length);
420
+ for (let i = 0; i < r; i += 1) {
421
+ const o = parseInt(s[i] || "0", 10), a = parseInt(n[i] || "0", 10);
422
+ if (o !== a)
423
+ return o > a ? 1 : -1;
424
+ }
425
+ return 0;
426
+ }
427
+ function y(e, t) {
428
+ return Ae(e, t) <= 0;
429
+ }
430
+ function S(e, t, s) {
431
+ if (typeof s == "string") {
432
+ if (e === "web_app_open_link" && t === "try_instant_view")
433
+ return y("6.4", s);
434
+ if (e === "web_app_set_header_color" && t === "color")
435
+ return y("6.9", s);
436
+ }
437
+ switch (e) {
438
+ case "web_app_open_tg_link":
439
+ case "web_app_open_invoice":
440
+ case "web_app_setup_back_button":
441
+ case "web_app_set_background_color":
442
+ case "web_app_set_header_color":
443
+ case "web_app_trigger_haptic_feedback":
444
+ return y("6.1", t);
445
+ case "web_app_open_popup":
446
+ return y("6.2", t);
447
+ case "web_app_close_scan_qr_popup":
448
+ case "web_app_open_scan_qr_popup":
449
+ case "web_app_read_text_from_clipboard":
450
+ return y("6.4", t);
451
+ case "web_app_switch_inline_query":
452
+ return y("6.7", t);
453
+ case "web_app_invoke_custom_method":
454
+ case "web_app_request_write_access":
455
+ case "web_app_request_phone":
456
+ return y("6.9", t);
457
+ case "web_app_setup_settings_button":
458
+ return y("6.10", t);
459
+ case "web_app_biometry_get_info":
460
+ case "web_app_biometry_open_settings":
461
+ case "web_app_biometry_request_access":
462
+ case "web_app_biometry_request_auth":
463
+ case "web_app_biometry_update_token":
464
+ return y("7.2", t);
465
+ default:
466
+ return [
467
+ "iframe_ready",
468
+ "iframe_will_reload",
469
+ "web_app_close",
470
+ "web_app_data_send",
471
+ "web_app_expand",
472
+ "web_app_open_link",
473
+ "web_app_ready",
474
+ "web_app_request_theme",
475
+ "web_app_request_viewport",
476
+ "web_app_setup_main_button",
477
+ "web_app_setup_closing_behavior"
478
+ ].includes(e);
479
+ }
480
+ }
481
+ function ke(e) {
482
+ return "external" in e && D(e.external) && "notify" in e.external && typeof e.external.notify == "function";
483
+ }
484
+ function Ct(e) {
485
+ return "TelegramWebviewProxy" in e && D(e.TelegramWebviewProxy) && "postEvent" in e.TelegramWebviewProxy && typeof e.TelegramWebviewProxy.postEvent == "function";
486
+ }
487
+ function Tt() {
488
+ try {
489
+ return window.self !== window.top;
490
+ } catch {
491
+ return !0;
492
+ }
493
+ }
494
+ let At = "https://web.telegram.org";
495
+ function gn(e) {
496
+ At = e;
497
+ }
498
+ function Ie() {
499
+ return At;
500
+ }
501
+ function q(e, t, s) {
502
+ let n = {}, r;
503
+ t === void 0 && s === void 0 ? n = {} : t !== void 0 && s !== void 0 ? (n = s, r = t) : t !== void 0 && ("targetOrigin" in t ? n = t : r = t);
504
+ const { targetOrigin: i = Ie() } = n;
505
+ if (ce("Posting event:", r ? { event: e, data: r } : { event: e }), Tt()) {
506
+ window.parent.postMessage(JSON.stringify({ eventType: e, eventData: r }), i);
507
+ return;
508
+ }
509
+ if (ke(window)) {
510
+ window.external.notify(JSON.stringify({ eventType: e, eventData: r }));
511
+ return;
512
+ }
513
+ if (Ct(window)) {
514
+ window.TelegramWebviewProxy.postEvent(e, JSON.stringify(r));
515
+ return;
516
+ }
517
+ throw l(
518
+ ue,
519
+ "Unable to determine current environment and possible way to send event. You are probably trying to use Mini Apps method outside of Telegram application environment."
520
+ );
521
+ }
522
+ function Oe(e) {
523
+ return (t, s) => {
524
+ if (!S(t, e))
525
+ throw l(he, `Method "${t}" is unsupported in Mini Apps version ${e}`);
526
+ if (D(s)) {
527
+ let n;
528
+ if (t === "web_app_open_link" && "try_instant_view" in s ? n = "try_instant_view" : t === "web_app_set_header_color" && "color" in s && (n = "color"), n && !S(t, n, e))
529
+ throw l(
530
+ pe,
531
+ `Parameter "${n}" of "${t}" method is unsupported in Mini Apps version ${e}`
532
+ );
533
+ }
534
+ return q(t, s);
535
+ };
536
+ }
537
+ function kt(e) {
538
+ return ({ req_id: t }) => t === e;
539
+ }
540
+ function It(e) {
541
+ return l(le, `Timeout reached: ${e}ms`);
542
+ }
543
+ function Ot(e, t) {
544
+ return Promise.race([
545
+ typeof e == "function" ? e() : e,
546
+ new Promise((s, n) => {
547
+ setTimeout(() => {
548
+ n(It(t));
549
+ }, t);
550
+ })
551
+ ]);
552
+ }
553
+ async function m(e) {
554
+ let t;
555
+ const s = new Promise((u) => {
556
+ t = u;
557
+ }), {
558
+ method: n,
559
+ event: r,
560
+ capture: i,
561
+ postEvent: o = q,
562
+ timeout: a
563
+ } = e, p = (Array.isArray(r) ? r : [r]).map(
564
+ (u) => E(u, (d) => (!i || i(d)) && t(d))
565
+ );
566
+ try {
567
+ return o(n, e.params), await (a ? Ot(s, a) : s);
568
+ } finally {
569
+ p.forEach((u) => u());
570
+ }
571
+ }
572
+ async function I(e, t, s, n = {}) {
573
+ const {
574
+ result: r,
575
+ error: i
576
+ } = await m({
577
+ ...n,
578
+ method: "web_app_invoke_custom_method",
579
+ event: "custom_method_invoked",
580
+ params: {
581
+ method: e,
582
+ params: t,
583
+ req_id: s
584
+ },
585
+ capture: kt(s)
586
+ });
587
+ if (i)
588
+ throw l(de, i);
589
+ return r;
590
+ }
591
+ function et(...e) {
592
+ return e.map((t) => {
593
+ if (typeof t == "string")
594
+ return t;
595
+ if (D(t))
596
+ return et(Object.entries(t).map((s) => s[1] && s[0]));
597
+ if (Array.isArray(t))
598
+ return et(...t);
599
+ }).filter(Boolean).join(" ");
600
+ }
601
+ function wn(...e) {
602
+ return e.reduce((t, s) => (D(s) && Object.entries(s).forEach(([n, r]) => {
603
+ const i = et(t[n], r);
604
+ i.length && (t[n] = i);
605
+ }), t), {});
606
+ }
607
+ function qt(e) {
608
+ const t = xt(e);
609
+ return Math.sqrt(
610
+ [0.299, 0.587, 0.114].reduce((s, n, r) => {
611
+ const i = parseInt(t.slice(1 + r * 2, 1 + (r + 1) * 2), 16);
612
+ return s + i * i * n;
613
+ }, 0)
614
+ ) < 120;
615
+ }
616
+ class qe {
617
+ constructor(t) {
618
+ c(this, "ee", new U()), c(this, "on", this.ee.on.bind(this.ee)), c(this, "off", this.ee.off.bind(this.ee)), this.state = t;
619
+ }
620
+ /**
621
+ * Clones current state and returns its copy.
622
+ */
623
+ clone() {
624
+ return { ...this.state };
625
+ }
626
+ set(t, s) {
627
+ Object.entries(typeof t == "string" ? { [t]: s } : t).reduce((n, [r, i]) => this.state[r] === i || i === void 0 ? n : (this.state[r] = i, this.ee.emit(`change:${r}`, i), !0), !1) && this.ee.emit("change", this.state);
628
+ }
629
+ /**
630
+ * Returns value by specified key.
631
+ * @param key - state key.
632
+ */
633
+ get(t) {
634
+ return this.state[t];
635
+ }
636
+ }
637
+ class ot {
638
+ constructor(t) {
639
+ c(this, "state"), c(this, "get"), c(this, "set"), c(this, "clone"), this.state = new qe(t), this.set = this.state.set.bind(this.state), this.get = this.state.get.bind(this.state), this.clone = this.state.clone.bind(this.state);
640
+ }
641
+ }
642
+ function Nt(e, t) {
643
+ return (s) => S(t[s], e);
644
+ }
645
+ class at extends ot {
646
+ constructor(t, s, n) {
647
+ super(t), c(this, "supports"), this.supports = Nt(s, n);
648
+ }
649
+ }
650
+ class Ne extends at {
651
+ constructor(t, s, n) {
652
+ super({ isVisible: t }, s, {
653
+ show: "web_app_setup_back_button",
654
+ hide: "web_app_setup_back_button"
655
+ }), c(this, "on", (r, i) => r === "click" ? E("back_button_pressed", i) : this.state.on(r, i)), c(this, "off", (r, i) => r === "click" ? z("back_button_pressed", i) : this.state.off(r, i)), this.postEvent = n;
656
+ }
657
+ set isVisible(t) {
658
+ this.set("isVisible", t), this.postEvent("web_app_setup_back_button", { is_visible: t });
659
+ }
660
+ /**
661
+ * True if BackButton is currently visible.
662
+ */
663
+ get isVisible() {
664
+ return this.get("isVisible");
665
+ }
666
+ /**
667
+ * Hides the BackButton.
668
+ */
669
+ hide() {
670
+ this.isVisible = !1;
671
+ }
672
+ /**
673
+ * Shows the BackButton.
674
+ */
675
+ show() {
676
+ this.isVisible = !0;
677
+ }
678
+ }
679
+ function C() {
680
+ return typeof window > "u";
681
+ }
682
+ const Dt = A((e) => e instanceof Date ? e : new Date(x().parse(e) * 1e3), "Date");
683
+ function ct(e, t) {
684
+ return new j((s) => {
685
+ if (typeof s != "string" && !(s instanceof URLSearchParams))
686
+ throw T();
687
+ const n = typeof s == "string" ? new URLSearchParams(s) : s;
688
+ return Rt(e, (r) => {
689
+ const i = n.get(r);
690
+ return i === null ? void 0 : i;
691
+ });
692
+ }, !1, t);
693
+ }
694
+ const De = f({
695
+ id: x(),
696
+ type: h(),
697
+ title: h(),
698
+ photoUrl: {
699
+ type: h().optional(),
700
+ from: "photo_url"
701
+ },
702
+ username: h().optional()
703
+ }, "Chat").optional(), wt = f({
704
+ addedToAttachmentMenu: {
705
+ type: P().optional(),
706
+ from: "added_to_attachment_menu"
707
+ },
708
+ allowsWriteToPm: {
709
+ type: P().optional(),
710
+ from: "allows_write_to_pm"
711
+ },
712
+ firstName: {
713
+ type: h(),
714
+ from: "first_name"
715
+ },
716
+ id: x(),
717
+ isBot: {
718
+ type: P().optional(),
719
+ from: "is_bot"
720
+ },
721
+ isPremium: {
722
+ type: P().optional(),
723
+ from: "is_premium"
724
+ },
725
+ languageCode: {
726
+ type: h().optional(),
727
+ from: "language_code"
728
+ },
729
+ lastName: {
730
+ type: h().optional(),
731
+ from: "last_name"
732
+ },
733
+ photoUrl: {
734
+ type: h().optional(),
735
+ from: "photo_url"
736
+ },
737
+ username: h().optional()
738
+ }, "User").optional();
739
+ function Vt() {
740
+ return ct({
741
+ authDate: {
742
+ type: Dt(),
743
+ from: "auth_date"
744
+ },
745
+ canSendAfter: {
746
+ type: x().optional(),
747
+ from: "can_send_after"
748
+ },
749
+ chat: De,
750
+ chatInstance: {
751
+ type: h().optional(),
752
+ from: "chat_instance"
753
+ },
754
+ chatType: {
755
+ type: h().optional(),
756
+ from: "chat_type"
757
+ },
758
+ hash: h(),
759
+ queryId: {
760
+ type: h().optional(),
761
+ from: "query_id"
762
+ },
763
+ receiver: wt,
764
+ startParam: {
765
+ type: h().optional(),
766
+ from: "start_param"
767
+ },
768
+ user: wt
769
+ }, "InitData");
770
+ }
771
+ function Ve(e) {
772
+ return e.replace(/_[a-z]/g, (t) => t[1].toUpperCase());
773
+ }
774
+ function Be(e) {
775
+ return e.replace(/[A-Z]/g, (t) => `_${t.toLowerCase()}`);
776
+ }
777
+ const Bt = A(
778
+ (e) => {
779
+ const t = St().optional();
780
+ return Object.entries(rt(e)).reduce((s, [n, r]) => (s[Ve(n)] = t.parse(r), s), {});
781
+ },
782
+ "ThemeParams"
783
+ );
784
+ function Mt(e) {
785
+ return ct({
786
+ botInline: {
787
+ type: P().optional(),
788
+ from: "tgWebAppBotInline"
789
+ },
790
+ initData: {
791
+ type: Vt().optional(),
792
+ from: "tgWebAppData"
793
+ },
794
+ initDataRaw: {
795
+ type: h().optional(),
796
+ from: "tgWebAppData"
797
+ },
798
+ platform: {
799
+ type: h(),
800
+ from: "tgWebAppPlatform"
801
+ },
802
+ showSettings: {
803
+ type: P().optional(),
804
+ from: "tgWebAppShowSettings"
805
+ },
806
+ startParam: {
807
+ type: h().optional(),
808
+ from: "tgWebAppStartParam"
809
+ },
810
+ themeParams: {
811
+ type: Bt(),
812
+ from: "tgWebAppThemeParams"
813
+ },
814
+ version: {
815
+ type: h(),
816
+ from: "tgWebAppVersion"
817
+ }
818
+ }).parse(e);
819
+ }
820
+ function $t(e) {
821
+ return Mt(
822
+ e.replace(/^[^?#]*[?#]/, "").replace(/[?#]/g, "&")
823
+ );
824
+ }
825
+ function Me() {
826
+ return $t(window.location.href);
827
+ }
828
+ function Lt() {
829
+ return performance.getEntriesByType("navigation")[0];
830
+ }
831
+ function $e() {
832
+ const e = Lt();
833
+ if (!e)
834
+ throw new Error("Unable to get first navigation entry.");
835
+ return $t(e.name);
836
+ }
837
+ function Ht(e) {
838
+ return `tma.js/${e.replace(/[A-Z]/g, (t) => `-${t.toLowerCase()}`)}`;
839
+ }
840
+ function Ut(e, t) {
841
+ sessionStorage.setItem(Ht(e), JSON.stringify(t));
842
+ }
843
+ function Wt(e) {
844
+ const t = sessionStorage.getItem(Ht(e));
845
+ try {
846
+ return t ? JSON.parse(t) : void 0;
847
+ } catch {
848
+ }
849
+ }
850
+ function Le() {
851
+ return Mt(Wt("launchParams") || "");
852
+ }
853
+ function He(e) {
854
+ return JSON.stringify(
855
+ Object.fromEntries(
856
+ Object.entries(e).map(([t, s]) => [Be(t), s])
857
+ )
858
+ );
859
+ }
860
+ function Ue(e) {
861
+ const {
862
+ initDataRaw: t,
863
+ themeParams: s,
864
+ platform: n,
865
+ version: r,
866
+ showSettings: i,
867
+ startParam: o,
868
+ botInline: a
869
+ } = e, p = new URLSearchParams();
870
+ return p.set("tgWebAppPlatform", n), p.set("tgWebAppThemeParams", He(s)), p.set("tgWebAppVersion", r), t && p.set("tgWebAppData", t), o && p.set("tgWebAppStartParam", o), typeof i == "boolean" && p.set("tgWebAppShowSettings", i ? "1" : "0"), typeof a == "boolean" && p.set("tgWebAppBotInline", a ? "1" : "0"), p.toString();
871
+ }
872
+ function We(e) {
873
+ Ut("launchParams", Ue(e));
874
+ }
875
+ function jt() {
876
+ for (const e of [
877
+ // Try to retrieve launch parameters from the current location. This method can return
878
+ // nothing in case, location was changed and then page was reloaded.
879
+ Me,
880
+ // Then, try using the lower level API - window.performance.
881
+ $e,
882
+ // Finally, try to extract launch parameters from the session storage.
883
+ Le
884
+ ])
885
+ try {
886
+ const t = e();
887
+ return We(t), t;
888
+ } catch {
889
+ }
890
+ throw new Error("Unable to retrieve launch parameters from any known source.");
891
+ }
892
+ function Gt() {
893
+ const e = Lt();
894
+ return !!(e && e.type === "reload");
895
+ }
896
+ function je() {
897
+ let e = 0;
898
+ return () => (e += 1).toString();
899
+ }
900
+ const [Ge] = yt(je);
901
+ function _(e, t) {
902
+ return ({ ssr: s } = {}) => {
903
+ let n;
904
+ if (C()) {
905
+ if (!s)
906
+ throw l(
907
+ nt,
908
+ "ssr.options must be specified to initialize component on the server side"
909
+ );
910
+ n = s;
911
+ } else
912
+ n = jt();
913
+ const r = {
914
+ ...n,
915
+ postEvent: "version" in n ? Oe(n.version) : () => {
916
+ throw l(
917
+ fe,
918
+ "postEvent function is forbidden to be called on the server side."
919
+ );
920
+ },
921
+ createRequestId: Ge()
922
+ };
923
+ if (C() || typeof e == "function")
924
+ return typeof e == "function" ? e(r) : t(r);
925
+ const i = t({
926
+ ...r,
927
+ state: Gt() ? Wt(e) : void 0
928
+ }), o = (a) => (a.on("change", (p) => {
929
+ Ut(e, p);
930
+ }), a);
931
+ return i instanceof Promise ? i.then(o) : o(i);
932
+ };
933
+ }
934
+ const ze = _("backButton", ({
935
+ postEvent: e,
936
+ version: t,
937
+ state: s = { isVisible: !1 }
938
+ }) => new Ne(s.isVisible, t, e));
939
+ class V extends at {
940
+ constructor() {
941
+ super(...arguments), c(this, "on", this.state.on.bind(this.state)), c(this, "off", this.state.off.bind(this.state));
942
+ }
943
+ }
944
+ function zt(e) {
945
+ const t = e.available ? e : {
946
+ available: !1,
947
+ device_id: "",
948
+ token_saved: !1,
949
+ access_requested: !1,
950
+ access_granted: !1,
951
+ type: ""
952
+ };
953
+ return {
954
+ available: !0,
955
+ type: t.type,
956
+ deviceId: t.device_id,
957
+ tokenSaved: t.token_saved,
958
+ accessRequested: t.access_requested,
959
+ accessGranted: t.access_granted
960
+ };
961
+ }
962
+ class ft extends V {
963
+ constructor({ postEvent: t, version: s, ...n }) {
964
+ super(n, s, {
965
+ auth: "web_app_biometry_request_auth",
966
+ openSettings: "web_app_biometry_open_settings",
967
+ requestAccess: "web_app_biometry_request_access",
968
+ updateToken: "web_app_biometry_update_token"
969
+ }), c(this, "postEvent"), c(this, "authPromise"), c(this, "accessPromise"), this.postEvent = t;
970
+ }
971
+ /**
972
+ * Shows whether biometry is available.
973
+ */
974
+ get available() {
975
+ return this.get("available");
976
+ }
977
+ /**
978
+ * Shows whether permission to use biometrics has been granted.
979
+ */
980
+ get accessGranted() {
981
+ return this.get("accessGranted");
982
+ }
983
+ /**
984
+ * Shows whether if permission to use biometrics has been requested.
985
+ */
986
+ get accessRequested() {
987
+ return this.get("accessRequested");
988
+ }
989
+ /**
990
+ * Authenticates the user using biometrics.
991
+ * @param options - method options.
992
+ * @since 7.2
993
+ * @returns Token from the local secure storage, if authentication was successful.
994
+ */
995
+ async authenticate({
996
+ reason: t,
997
+ ...s
998
+ }) {
999
+ return this.authPromise || (this.authPromise = m({
1000
+ ...s,
1001
+ method: "web_app_biometry_request_auth",
1002
+ event: "biometry_auth_requested",
1003
+ postEvent: this.postEvent,
1004
+ params: {
1005
+ // TODO: Check if reason is empty works fine.
1006
+ reason: (t || "").trim()
1007
+ }
1008
+ }).then(({ token: n }) => n).finally(() => this.authPromise = void 0)), this.authPromise;
1009
+ }
1010
+ /**
1011
+ * A unique device identifier that can be used to match the token to the device.
1012
+ */
1013
+ get deviceId() {
1014
+ return this.get("deviceId");
1015
+ }
1016
+ /**
1017
+ * Opens the biometric access settings for bots. Useful when you need to request biometrics
1018
+ * access to users who haven't granted it yet.
1019
+ *
1020
+ * _Note that this method can be called only in response to user interaction with the Mini App
1021
+ * interface (e.g. a click inside the Mini App or on the main button)_.
1022
+ * @since 7.2
1023
+ */
1024
+ openSettings() {
1025
+ this.postEvent("web_app_biometry_open_settings");
1026
+ }
1027
+ /**
1028
+ * Requests permission to use biometrics.
1029
+ * @since 7.2
1030
+ * @returns Promise with true, if access was granted.
1031
+ */
1032
+ requestAccess({ reason: t, ...s } = {}) {
1033
+ return this.accessPromise || (this.accessPromise = m({
1034
+ ...s,
1035
+ postEvent: this.postEvent,
1036
+ method: "web_app_biometry_request_access",
1037
+ event: "biometry_info_received",
1038
+ params: { reason: t || "" }
1039
+ }).then((n) => {
1040
+ const r = zt(n);
1041
+ return this.set(r), r.accessGranted;
1042
+ }).finally(() => this.accessPromise = void 0)), this.accessPromise;
1043
+ }
1044
+ /**
1045
+ * The type of biometrics currently available on the device.
1046
+ */
1047
+ get biometryType() {
1048
+ return this.get("biometryType");
1049
+ }
1050
+ /**
1051
+ * Shows whether token was saved previously in the local secure storage.
1052
+ */
1053
+ get tokenSaved() {
1054
+ return this.get("tokenSaved");
1055
+ }
1056
+ /**
1057
+ * Updates the biometric token in a secure storage on the device.
1058
+ * @returns Promise with `true`, if token was updated.
1059
+ */
1060
+ async updateToken({ token: t, ...s } = {}) {
1061
+ return ["removed", "updated"].includes(
1062
+ (await m({
1063
+ ...s,
1064
+ postEvent: this.postEvent,
1065
+ method: "web_app_biometry_update_token",
1066
+ event: "biometry_token_updated",
1067
+ params: { token: t || "" }
1068
+ })).status
1069
+ );
1070
+ }
1071
+ }
1072
+ async function Ke(e) {
1073
+ return zt(
1074
+ await m({
1075
+ ...e || {},
1076
+ method: "web_app_biometry_get_info",
1077
+ event: "biometry_info_received"
1078
+ })
1079
+ );
1080
+ }
1081
+ const Je = _("biometryManager", async ({ postEvent: e, version: t, state: s }) => {
1082
+ if (s)
1083
+ return new ft({ ...s, version: t, postEvent: e });
1084
+ if (C())
1085
+ throw l(
1086
+ nt,
1087
+ "BiometryManager cannot be instantiated on the server side without passing the ssr.state object."
1088
+ );
1089
+ return new ft({
1090
+ ...await Ke({ timeout: 1e3 }),
1091
+ version: t,
1092
+ postEvent: e
1093
+ });
1094
+ });
1095
+ class ht extends ot {
1096
+ constructor() {
1097
+ super(...arguments), c(this, "on", this.state.on.bind(this.state)), c(this, "off", this.state.off.bind(this.state));
1098
+ }
1099
+ }
1100
+ class Qe extends ht {
1101
+ constructor(t, s) {
1102
+ super({ isConfirmationNeeded: t }), this.postEvent = s;
1103
+ }
1104
+ set isConfirmationNeeded(t) {
1105
+ this.set("isConfirmationNeeded", t), this.postEvent("web_app_setup_closing_behavior", { need_confirmation: t });
1106
+ }
1107
+ /**
1108
+ * True, if the confirmation dialog should be shown while the user is trying to close
1109
+ * the Mini App.
1110
+ */
1111
+ get isConfirmationNeeded() {
1112
+ return this.get("isConfirmationNeeded");
1113
+ }
1114
+ /**
1115
+ * Disables the confirmation dialog when closing the Mini App.
1116
+ */
1117
+ disableConfirmation() {
1118
+ this.isConfirmationNeeded = !1;
1119
+ }
1120
+ /**
1121
+ * Enables the confirmation dialog when closing the Mini App.
1122
+ */
1123
+ enableConfirmation() {
1124
+ this.isConfirmationNeeded = !0;
1125
+ }
1126
+ }
1127
+ const Fe = _("closingBehavior", ({
1128
+ postEvent: e,
1129
+ state: t = { isConfirmationNeeded: !1 }
1130
+ }) => new Qe(t.isConfirmationNeeded, e));
1131
+ class pt {
1132
+ constructor(t, s) {
1133
+ c(this, "supports"), this.supports = Nt(t, s);
1134
+ }
1135
+ }
1136
+ function Ye(e) {
1137
+ if (Array.isArray(e))
1138
+ return e;
1139
+ if (typeof e == "string")
1140
+ try {
1141
+ const t = JSON.parse(e);
1142
+ if (Array.isArray(t))
1143
+ return t;
1144
+ } catch {
1145
+ }
1146
+ throw T();
1147
+ }
1148
+ class Ze extends j {
1149
+ constructor(t, s, n) {
1150
+ super(Ye, s, n), c(this, "itemParser"), this.itemParser = typeof t == "function" ? t : t.parse.bind(t);
1151
+ }
1152
+ /**
1153
+ * Attempts to parse passed value
1154
+ * @param value - value to parse.
1155
+ * @throws {SDKError} ERR_PARSE
1156
+ * @see ERR_PARSE
1157
+ */
1158
+ parse(t) {
1159
+ const s = super.parse(t);
1160
+ return s === void 0 ? s : s.map(this.itemParser);
1161
+ }
1162
+ of(t) {
1163
+ return this.itemParser = typeof t == "function" ? t : t.parse.bind(t), this;
1164
+ }
1165
+ }
1166
+ function Xe(e) {
1167
+ return new Ze((t) => t, !1, e);
1168
+ }
1169
+ function mt(e, t) {
1170
+ return Object.fromEntries(e.map((s) => [s, t]));
1171
+ }
1172
+ class ts extends pt {
1173
+ constructor(t, s, n) {
1174
+ super(t, {
1175
+ delete: "web_app_invoke_custom_method",
1176
+ get: "web_app_invoke_custom_method",
1177
+ getKeys: "web_app_invoke_custom_method",
1178
+ set: "web_app_invoke_custom_method"
1179
+ }), this.createRequestId = s, this.postEvent = n;
1180
+ }
1181
+ /**
1182
+ * Deletes specified key or keys from the cloud storage.
1183
+ * @param keyOrKeys - key or keys to delete.
1184
+ * @param options - request execution options.
1185
+ */
1186
+ async delete(t, s = {}) {
1187
+ const n = Array.isArray(t) ? t : [t];
1188
+ n.length && await I(
1189
+ "deleteStorageValues",
1190
+ { keys: n },
1191
+ this.createRequestId(),
1192
+ { ...s, postEvent: this.postEvent }
1193
+ );
1194
+ }
1195
+ /**
1196
+ * Returns list of all keys presented in the cloud storage.
1197
+ * @param options - request execution options.
1198
+ */
1199
+ async getKeys(t = {}) {
1200
+ return Xe().of(h()).parse(
1201
+ await I(
1202
+ "getStorageKeys",
1203
+ {},
1204
+ this.createRequestId(),
1205
+ { ...t, postEvent: this.postEvent }
1206
+ )
1207
+ );
1208
+ }
1209
+ async get(t, s = {}) {
1210
+ const n = Array.isArray(t) ? t : [t];
1211
+ if (!n.length)
1212
+ return mt(n, "");
1213
+ const r = await I(
1214
+ "getStorageValues",
1215
+ { keys: n },
1216
+ this.createRequestId(),
1217
+ { ...s, postEvent: this.postEvent }
1218
+ ), i = f(mt(n, h()), "CloudStorageData").parse(r);
1219
+ return Array.isArray(t) ? i : i[t];
1220
+ }
1221
+ /**
1222
+ * Saves specified value by key.
1223
+ * @param key - storage key.
1224
+ * @param value - storage value.
1225
+ * @param options - request execution options.
1226
+ */
1227
+ async set(t, s, n = {}) {
1228
+ await I(
1229
+ "saveStorageValue",
1230
+ { key: t, value: s },
1231
+ this.createRequestId(),
1232
+ { ...n, postEvent: this.postEvent }
1233
+ );
1234
+ }
1235
+ }
1236
+ const es = _(
1237
+ ({ createRequestId: e, postEvent: t, version: s }) => new ts(s, e, t)
1238
+ );
1239
+ class ss extends pt {
1240
+ constructor(t, s) {
1241
+ super(t, {
1242
+ impactOccurred: "web_app_trigger_haptic_feedback",
1243
+ notificationOccurred: "web_app_trigger_haptic_feedback",
1244
+ selectionChanged: "web_app_trigger_haptic_feedback"
1245
+ }), this.postEvent = s;
1246
+ }
1247
+ /**
1248
+ * A method tells that an impact occurred. The Telegram app may play the
1249
+ * appropriate haptics based on style value passed.
1250
+ * @param style - impact style.
1251
+ */
1252
+ impactOccurred(t) {
1253
+ this.postEvent("web_app_trigger_haptic_feedback", {
1254
+ type: "impact",
1255
+ impact_style: t
1256
+ });
1257
+ }
1258
+ /**
1259
+ * A method tells that a task or action has succeeded, failed, or produced
1260
+ * a warning. The Telegram app may play the appropriate haptics based on
1261
+ * type value passed.
1262
+ * @param type - notification type.
1263
+ */
1264
+ notificationOccurred(t) {
1265
+ this.postEvent("web_app_trigger_haptic_feedback", {
1266
+ type: "notification",
1267
+ notification_type: t
1268
+ });
1269
+ }
1270
+ /**
1271
+ * A method tells that the user has changed a selection. The Telegram app
1272
+ * may play the appropriate haptics.
1273
+ *
1274
+ * Do not use this feedback when the user makes or confirms a selection;
1275
+ * use it only when the selection changes.
1276
+ */
1277
+ selectionChanged() {
1278
+ this.postEvent("web_app_trigger_haptic_feedback", { type: "selection_change" });
1279
+ }
1280
+ }
1281
+ const ns = _(
1282
+ ({ version: e, postEvent: t }) => new ss(e, t)
1283
+ );
1284
+ class rs {
1285
+ constructor(t) {
1286
+ this.initData = t;
1287
+ }
1288
+ /**
1289
+ * @see InitDataParsed.authDate
1290
+ */
1291
+ get authDate() {
1292
+ return this.initData.authDate;
1293
+ }
1294
+ /**
1295
+ * @see InitDataParsed.canSendAfter
1296
+ */
1297
+ get canSendAfter() {
1298
+ return this.initData.canSendAfter;
1299
+ }
1300
+ /**
1301
+ * Date after which it is allowed to call
1302
+ * the [answerWebAppQuery](https://core.telegram.org/bots/api#answerwebappquery) method.
1303
+ */
1304
+ get canSendAfterDate() {
1305
+ const { canSendAfter: t } = this;
1306
+ return t ? new Date(this.authDate.getTime() + t * 1e3) : void 0;
1307
+ }
1308
+ /**
1309
+ * @see InitDataParsed.chat
1310
+ */
1311
+ get chat() {
1312
+ return this.initData.chat;
1313
+ }
1314
+ /**
1315
+ * @see InitDataParsed.chatType
1316
+ */
1317
+ get chatType() {
1318
+ return this.initData.chatType;
1319
+ }
1320
+ /**
1321
+ * @see InitDataParsed.chatInstance
1322
+ */
1323
+ get chatInstance() {
1324
+ return this.initData.chatInstance;
1325
+ }
1326
+ /**
1327
+ * @see InitDataParsed.hash
1328
+ */
1329
+ get hash() {
1330
+ return this.initData.hash;
1331
+ }
1332
+ /**
1333
+ * @see InitDataParsed.queryId
1334
+ */
1335
+ get queryId() {
1336
+ return this.initData.queryId;
1337
+ }
1338
+ /**
1339
+ * @see InitDataParsed.receiver
1340
+ */
1341
+ get receiver() {
1342
+ return this.initData.receiver;
1343
+ }
1344
+ /**
1345
+ * @see InitDataParsed.startParam
1346
+ */
1347
+ get startParam() {
1348
+ return this.initData.startParam;
1349
+ }
1350
+ /**
1351
+ * @see InitDataParsed.user
1352
+ */
1353
+ get user() {
1354
+ return this.initData.user;
1355
+ }
1356
+ }
1357
+ const is = _(
1358
+ ({ initData: e }) => e ? new rs(e) : void 0
1359
+ );
1360
+ function fn(e) {
1361
+ return Vt().parse(e);
1362
+ }
1363
+ class os extends V {
1364
+ constructor(t, s, n) {
1365
+ super({ isOpened: t }, s, { open: "web_app_open_invoice" }), this.postEvent = n;
1366
+ }
1367
+ set isOpened(t) {
1368
+ this.set("isOpened", t);
1369
+ }
1370
+ /**
1371
+ * True if invoice is currently opened.
1372
+ */
1373
+ get isOpened() {
1374
+ return this.get("isOpened");
1375
+ }
1376
+ async open(t, s) {
1377
+ if (this.isOpened)
1378
+ throw new Error("Invoice is already opened");
1379
+ let n;
1380
+ if (!s)
1381
+ n = t;
1382
+ else {
1383
+ const { hostname: r, pathname: i } = new URL(t, window.location.href);
1384
+ if (r !== "t.me")
1385
+ throw new Error(`Incorrect hostname: ${r}`);
1386
+ const o = i.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);
1387
+ if (!o)
1388
+ throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');
1389
+ [, , n] = o;
1390
+ }
1391
+ this.isOpened = !0;
1392
+ try {
1393
+ return (await m({
1394
+ method: "web_app_open_invoice",
1395
+ event: "invoice_closed",
1396
+ params: { slug: n },
1397
+ postEvent: this.postEvent,
1398
+ capture(r) {
1399
+ return n === r.slug;
1400
+ }
1401
+ })).status;
1402
+ } finally {
1403
+ this.isOpened = !1;
1404
+ }
1405
+ }
1406
+ }
1407
+ const as = _(
1408
+ ({ version: e, postEvent: t }) => new os(!1, e, t)
1409
+ );
1410
+ class cs extends ot {
1411
+ constructor({ postEvent: t, ...s }) {
1412
+ super(s), c(this, "postEvent"), c(this, "on", (n, r) => n === "click" ? E("main_button_pressed", r) : this.state.on(n, r)), c(this, "off", (n, r) => n === "click" ? z("main_button_pressed", r) : this.state.off(n, r)), this.postEvent = t;
1413
+ }
1414
+ /**
1415
+ * Sends current local state to the Telegram application.
1416
+ */
1417
+ commit() {
1418
+ this.text !== "" && this.postEvent("web_app_setup_main_button", {
1419
+ is_visible: this.isVisible,
1420
+ is_active: this.isEnabled,
1421
+ is_progress_visible: this.isLoaderVisible,
1422
+ text: this.text,
1423
+ color: this.backgroundColor,
1424
+ text_color: this.textColor
1425
+ });
1426
+ }
1427
+ set isEnabled(t) {
1428
+ this.setParams({ isEnabled: t });
1429
+ }
1430
+ /**
1431
+ * True if the MainButton is enabled.
1432
+ */
1433
+ get isEnabled() {
1434
+ return this.get("isEnabled");
1435
+ }
1436
+ set isLoaderVisible(t) {
1437
+ this.setParams({ isLoaderVisible: t });
1438
+ }
1439
+ /**
1440
+ * True if the MainButton loader is visible.
1441
+ */
1442
+ get isLoaderVisible() {
1443
+ return this.get("isLoaderVisible");
1444
+ }
1445
+ set isVisible(t) {
1446
+ this.setParams({ isVisible: t });
1447
+ }
1448
+ /**
1449
+ * True if the MainButton is visible.
1450
+ */
1451
+ get isVisible() {
1452
+ return this.get("isVisible");
1453
+ }
1454
+ /**
1455
+ * The MainButton background color.
1456
+ */
1457
+ get backgroundColor() {
1458
+ return this.get("backgroundColor");
1459
+ }
1460
+ /**
1461
+ * The MainButton text.
1462
+ */
1463
+ get text() {
1464
+ return this.get("text");
1465
+ }
1466
+ /**
1467
+ * The MainButton text color.
1468
+ */
1469
+ get textColor() {
1470
+ return this.get("textColor");
1471
+ }
1472
+ /**
1473
+ * Disables the MainButton.
1474
+ * @see Does not work on Android: https://github.com/Telegram-Mini-Apps/issues/issues/1
1475
+ */
1476
+ disable() {
1477
+ return this.isEnabled = !1, this;
1478
+ }
1479
+ /**
1480
+ * Enables the MainButton.
1481
+ */
1482
+ enable() {
1483
+ return this.isEnabled = !0, this;
1484
+ }
1485
+ /**
1486
+ * Hides the MainButton.
1487
+ */
1488
+ hide() {
1489
+ return this.isVisible = !1, this;
1490
+ }
1491
+ /**
1492
+ * Hides the MainButton loading indicator.
1493
+ */
1494
+ hideLoader() {
1495
+ return this.isLoaderVisible = !1, this;
1496
+ }
1497
+ /**
1498
+ * Shows the MainButton.
1499
+ *
1500
+ * Note that opening the Mini App from the attachment menu hides the main button until the
1501
+ * user interacts with the Mini App interface.
1502
+ */
1503
+ show() {
1504
+ return this.isVisible = !0, this;
1505
+ }
1506
+ /**
1507
+ * Shows a loading indicator on the Main Button.
1508
+ */
1509
+ showLoader() {
1510
+ return this.isLoaderVisible = !0, this;
1511
+ }
1512
+ /**
1513
+ * Sets a new MainButton text. Minimal length for the text is 1 symbol, and maximum is 64 symbols.
1514
+ * @param text - a new text.
1515
+ */
1516
+ setText(t) {
1517
+ return this.setParams({ text: t });
1518
+ }
1519
+ /**
1520
+ * Sets a new Main Button text color.
1521
+ * @param textColor - new text color.
1522
+ */
1523
+ setTextColor(t) {
1524
+ return this.setParams({ textColor: t });
1525
+ }
1526
+ /**
1527
+ * Updates current Main Button color.
1528
+ * @param backgroundColor - color to set.
1529
+ */
1530
+ setBackgroundColor(t) {
1531
+ return this.setParams({ backgroundColor: t });
1532
+ }
1533
+ /**
1534
+ * Allows setting multiple Main Button parameters.
1535
+ * @param params - Main Button parameters.
1536
+ */
1537
+ setParams(t) {
1538
+ return this.set(t), this.commit(), this;
1539
+ }
1540
+ }
1541
+ const hs = _("mainButton", ({
1542
+ postEvent: e,
1543
+ themeParams: t,
1544
+ state: s = {
1545
+ isVisible: !1,
1546
+ isEnabled: !1,
1547
+ text: "",
1548
+ isLoaderVisible: !1,
1549
+ textColor: t.buttonTextColor || "#ffffff",
1550
+ backgroundColor: t.buttonColor || "#000000"
1551
+ }
1552
+ }) => new cs({ ...s, postEvent: e }));
1553
+ function ps() {
1554
+ return ct({
1555
+ contact: f({
1556
+ userId: {
1557
+ type: x(),
1558
+ from: "user_id"
1559
+ },
1560
+ phoneNumber: {
1561
+ type: h(),
1562
+ from: "phone_number"
1563
+ },
1564
+ firstName: {
1565
+ type: h(),
1566
+ from: "first_name"
1567
+ },
1568
+ lastName: {
1569
+ type: h().optional(),
1570
+ from: "last_name"
1571
+ }
1572
+ }),
1573
+ authDate: {
1574
+ type: Dt(),
1575
+ from: "auth_date"
1576
+ },
1577
+ hash: h()
1578
+ }, "RequestedContact");
1579
+ }
1580
+ function Kt(e, t) {
1581
+ return (s) => {
1582
+ const [n, r] = t[s];
1583
+ return S(n, r, e);
1584
+ };
1585
+ }
1586
+ function us(e) {
1587
+ return new Promise((t) => {
1588
+ setTimeout(t, e);
1589
+ });
1590
+ }
1591
+ class ds extends V {
1592
+ constructor({ postEvent: t, createRequestId: s, version: n, botInline: r, ...i }) {
1593
+ super(i, n, {
1594
+ requestPhoneAccess: "web_app_request_phone",
1595
+ requestWriteAccess: "web_app_request_write_access",
1596
+ switchInlineQuery: "web_app_switch_inline_query",
1597
+ setHeaderColor: "web_app_set_header_color",
1598
+ setBackgroundColor: "web_app_set_background_color"
1599
+ }), c(this, "botInline"), c(this, "postEvent"), c(this, "createRequestId"), c(this, "requestPhoneAccessPromise"), c(this, "requestWriteAccessPromise"), c(this, "supportsParam"), this.createRequestId = s, this.postEvent = t, this.botInline = r;
1600
+ const o = this.supports.bind(this);
1601
+ this.supports = (a) => o(a) ? a !== "switchInlineQuery" || r : !1, this.supportsParam = Kt(n, {
1602
+ "setHeaderColor.color": ["web_app_set_header_color", "color"]
1603
+ });
1604
+ }
1605
+ /**
1606
+ * Attempts to get requested contact.
1607
+ * @param timeout - request timeout.
1608
+ */
1609
+ async getRequestedContact({
1610
+ timeout: t = 1e4
1611
+ } = {}) {
1612
+ return ps().parse(
1613
+ await I(
1614
+ "getRequestedContact",
1615
+ {},
1616
+ this.createRequestId(),
1617
+ { postEvent: this.postEvent, timeout: t }
1618
+ )
1619
+ );
1620
+ }
1621
+ /**
1622
+ * The Mini App background color.
1623
+ * @example "#ffaabb"
1624
+ */
1625
+ get bgColor() {
1626
+ return this.get("bgColor");
1627
+ }
1628
+ /**
1629
+ * Closes the Mini App.
1630
+ */
1631
+ close() {
1632
+ this.postEvent("web_app_close");
1633
+ }
1634
+ /**
1635
+ * The Mini App header color.
1636
+ * @example "#ffaabb"
1637
+ * @example "bg_color"
1638
+ */
1639
+ get headerColor() {
1640
+ return this.get("headerColor");
1641
+ }
1642
+ /**
1643
+ * True if the Mini App is currently launched in bot inline mode.
1644
+ */
1645
+ get isBotInline() {
1646
+ return this.botInline;
1647
+ }
1648
+ /**
1649
+ * True if current Mini App background color is recognized as dark.
1650
+ */
1651
+ get isDark() {
1652
+ return qt(this.bgColor);
1653
+ }
1654
+ /**
1655
+ * Informs the Telegram app that the Mini App is ready to be displayed.
1656
+ *
1657
+ * It is recommended to call this method as early as possible, as soon as all essential
1658
+ * interface elements loaded. Once this method called, the loading placeholder is hidden
1659
+ * and the Mini App shown.
1660
+ *
1661
+ * If the method not called, the placeholder will be hidden only when the page fully loaded.
1662
+ */
1663
+ ready() {
1664
+ this.postEvent("web_app_ready");
1665
+ }
1666
+ /**
1667
+ * Requests current user contact information. In contrary to requestPhoneAccess, this method
1668
+ * returns promise with contact information that rejects in case, user denied access, or request
1669
+ * failed.
1670
+ * @param options - additional options.
1671
+ */
1672
+ async requestContact({ timeout: t = 5e3 } = {}) {
1673
+ try {
1674
+ return await this.getRequestedContact();
1675
+ } catch {
1676
+ }
1677
+ if (await this.requestPhoneAccess() !== "sent")
1678
+ throw new Error("Access denied.");
1679
+ const s = Date.now() + t;
1680
+ let n = 50;
1681
+ return Ot(async () => {
1682
+ for (; Date.now() < s; ) {
1683
+ try {
1684
+ return await this.getRequestedContact();
1685
+ } catch {
1686
+ }
1687
+ await us(n), n += 50;
1688
+ }
1689
+ throw It(t);
1690
+ }, t);
1691
+ }
1692
+ /**
1693
+ * Requests current user phone access. Method returns promise, which resolves
1694
+ * status of the request. In case, user accepted the request, Mini App bot will receive
1695
+ * the according notification.
1696
+ *
1697
+ * To obtain the retrieved information instead, utilize the `requestContact` method.
1698
+ * @param options - additional options.
1699
+ * @see requestContact
1700
+ */
1701
+ async requestPhoneAccess(t = {}) {
1702
+ return this.requestPhoneAccessPromise || (this.requestPhoneAccessPromise = m({
1703
+ ...t,
1704
+ method: "web_app_request_phone",
1705
+ event: "phone_requested",
1706
+ postEvent: this.postEvent
1707
+ }).then(({ status: s }) => s).finally(() => this.requestPhoneAccessPromise = void 0)), this.requestPhoneAccessPromise;
1708
+ }
1709
+ /**
1710
+ * Requests write message access to current user.
1711
+ * @param options - additional options.
1712
+ */
1713
+ async requestWriteAccess(t = {}) {
1714
+ return this.requestWriteAccessPromise || (this.requestWriteAccessPromise = m({
1715
+ ...t,
1716
+ method: "web_app_request_write_access",
1717
+ event: "write_access_requested",
1718
+ postEvent: this.postEvent
1719
+ }).then(({ status: s }) => s).finally(() => this.requestWriteAccessPromise = void 0)), this.requestWriteAccessPromise;
1720
+ }
1721
+ /**
1722
+ * A method used to send data to the bot. When this method called, a service message sent to
1723
+ * the bot containing the data of the length up to 4096 bytes, and the Mini App closed. See the
1724
+ * field `web_app_data` in the class [Message](https://core.telegram.org/bots/api#message).
1725
+ *
1726
+ * This method is only available for Mini Apps launched via a Keyboard button.
1727
+ * @param data - data to send to bot.
1728
+ * @throws {Error} data has incorrect size.
1729
+ */
1730
+ sendData(t) {
1731
+ const { size: s } = new Blob([t]);
1732
+ if (!s || s > 4096)
1733
+ throw new Error(`Passed data has incorrect size: ${s}`);
1734
+ this.postEvent("web_app_data_send", { data: t });
1735
+ }
1736
+ /**
1737
+ * Updates current Mini App header color.
1738
+ *
1739
+ * @see No effect on desktop: https://github.com/Telegram-Mini-Apps/tma.js/issues/9
1740
+ * @see Works incorrectly in Android: https://github.com/Telegram-Mini-Apps/tma.js/issues/8
1741
+ * @param color - color key or RGB color.
1742
+ */
1743
+ setHeaderColor(t) {
1744
+ this.postEvent("web_app_set_header_color", it(t) ? { color: t } : { color_key: t }), this.set("headerColor", t);
1745
+ }
1746
+ /**
1747
+ * Updates current Mini App background color.
1748
+ *
1749
+ * @see No effect on desktop: https://github.com/Telegram-Mini-Apps/tma.js/issues/9
1750
+ * @see Works incorrectly in Android: https://github.com/Telegram-Mini-Apps/tma.js/issues/8
1751
+ * @param color - RGB color.
1752
+ */
1753
+ setBgColor(t) {
1754
+ this.postEvent("web_app_set_background_color", { color: t }), this.set("bgColor", t);
1755
+ }
1756
+ /**
1757
+ * Inserts the bot's username and the specified inline query in the current chat's input field.
1758
+ * Query may be empty, in which case only the bot's username will be inserted. The client prompts
1759
+ * the user to choose a specific chat, then opens that chat and inserts the bot's username and
1760
+ * the specified inline query in the input field.
1761
+ * @param text - text which should be inserted in the input after the current bot name. Max
1762
+ * length is 256 symbols.
1763
+ * @param chatTypes - List of chat types which could be chosen to send the message. Could be
1764
+ * empty list.
1765
+ */
1766
+ switchInlineQuery(t, s = []) {
1767
+ if (!this.supports("switchInlineQuery") && !this.isBotInline)
1768
+ throw new Error("Method is unsupported because Mini App should be launched in inline mode.");
1769
+ this.postEvent("web_app_switch_inline_query", { query: t, chat_types: s });
1770
+ }
1771
+ }
1772
+ const ls = _("miniApp", ({
1773
+ themeParams: e,
1774
+ botInline: t = !1,
1775
+ state: s = {
1776
+ bgColor: e.bgColor || "#ffffff",
1777
+ headerColor: e.headerBgColor || "#000000"
1778
+ },
1779
+ ...n
1780
+ }) => new ds({ ...n, ...s, botInline: t }));
1781
+ function _s(e) {
1782
+ const t = e.message.trim(), s = (e.title || "").trim(), n = e.buttons || [];
1783
+ let r;
1784
+ if (s.length > 64)
1785
+ throw new Error(`Title has incorrect size: ${s.length}`);
1786
+ if (!t.length || t.length > 256)
1787
+ throw new Error(`Message has incorrect size: ${t.length}`);
1788
+ if (n.length > 3)
1789
+ throw new Error(`Buttons have incorrect size: ${n.length}`);
1790
+ return n.length ? r = n.map((i) => {
1791
+ const { id: o = "" } = i;
1792
+ if (o.length > 64)
1793
+ throw new Error(`Button ID has incorrect size: ${o}`);
1794
+ if (!i.type || i.type === "default" || i.type === "destructive") {
1795
+ const a = i.text.trim();
1796
+ if (!a.length || a.length > 64) {
1797
+ const p = i.type || "default";
1798
+ throw new Error(`Button text with type "${p}" has incorrect size: ${i.text.length}`);
1799
+ }
1800
+ return { ...i, text: a, id: o };
1801
+ }
1802
+ return { ...i, id: o };
1803
+ }) : r = [{ type: "close", id: "" }], { title: s, message: t, buttons: r };
1804
+ }
1805
+ class gs extends V {
1806
+ constructor(t, s, n) {
1807
+ super({ isOpened: t }, s, { open: "web_app_open_popup" }), this.postEvent = n;
1808
+ }
1809
+ set isOpened(t) {
1810
+ this.set("isOpened", t);
1811
+ }
1812
+ /**
1813
+ * True if the Popup is opened.
1814
+ */
1815
+ get isOpened() {
1816
+ return this.get("isOpened");
1817
+ }
1818
+ /**
1819
+ * A method that shows a native popup described by the `params` argument.
1820
+ * Promise will be resolved when popup is closed. Resolved value will have
1821
+ * an identifier of pressed button.
1822
+ *
1823
+ * In case, user clicked outside the popup or clicked top right popup close
1824
+ * button, null will be returned.
1825
+ *
1826
+ * @param options - popup parameters.
1827
+ * @throws {Error} Popup is already opened.
1828
+ */
1829
+ async open(t) {
1830
+ if (this.isOpened)
1831
+ throw new Error("Popup is already opened.");
1832
+ this.isOpened = !0;
1833
+ try {
1834
+ const { button_id: s = null } = await m({
1835
+ event: "popup_closed",
1836
+ method: "web_app_open_popup",
1837
+ postEvent: this.postEvent,
1838
+ params: _s(t)
1839
+ });
1840
+ return s;
1841
+ } finally {
1842
+ this.isOpened = !1;
1843
+ }
1844
+ }
1845
+ }
1846
+ const ws = _(
1847
+ ({ postEvent: e, version: t }) => new gs(!1, t, e)
1848
+ );
1849
+ class fs extends V {
1850
+ constructor(t, s, n) {
1851
+ super({ isOpened: t }, s, {
1852
+ close: "web_app_close_scan_qr_popup",
1853
+ open: "web_app_open_scan_qr_popup"
1854
+ }), this.postEvent = n;
1855
+ }
1856
+ /**
1857
+ * Closes scanner.
1858
+ */
1859
+ close() {
1860
+ this.postEvent("web_app_close_scan_qr_popup"), this.isOpened = !1;
1861
+ }
1862
+ set isOpened(t) {
1863
+ this.set("isOpened", t);
1864
+ }
1865
+ /**
1866
+ * Returns true in case, QR scanner is currently opened.
1867
+ */
1868
+ get isOpened() {
1869
+ return this.get("isOpened");
1870
+ }
1871
+ /**
1872
+ * Opens scanner with specified title shown to user. Method returns promise
1873
+ * with scanned QR content in case, it was scanned. It will contain null in
1874
+ * case, scanner was closed.
1875
+ * @param text - title to display.
1876
+ */
1877
+ async open(t) {
1878
+ if (this.isOpened)
1879
+ throw new Error("QR scanner is already opened.");
1880
+ this.isOpened = !0;
1881
+ try {
1882
+ return (await m({
1883
+ method: "web_app_open_scan_qr_popup",
1884
+ event: ["qr_text_received", "scan_qr_popup_closed"],
1885
+ postEvent: this.postEvent,
1886
+ params: { text: t }
1887
+ }) || {}).data || null;
1888
+ } finally {
1889
+ this.isOpened = !1;
1890
+ }
1891
+ }
1892
+ }
1893
+ const ms = _(
1894
+ ({ version: e, postEvent: t }) => new fs(!1, e, t)
1895
+ );
1896
+ class bs extends at {
1897
+ constructor(t, s, n) {
1898
+ super({ isVisible: t }, s, {
1899
+ show: "web_app_setup_settings_button",
1900
+ hide: "web_app_setup_settings_button"
1901
+ }), c(this, "on", (r, i) => r === "click" ? E("settings_button_pressed", i) : this.state.on(r, i)), c(this, "off", (r, i) => r === "click" ? z("settings_button_pressed", i) : this.state.off(r, i)), this.postEvent = n;
1902
+ }
1903
+ set isVisible(t) {
1904
+ this.set("isVisible", t), this.postEvent("web_app_setup_settings_button", { is_visible: t });
1905
+ }
1906
+ /**
1907
+ * True if the SettingsButton is visible.
1908
+ */
1909
+ get isVisible() {
1910
+ return this.get("isVisible");
1911
+ }
1912
+ /**
1913
+ * Hides the SettingsButton.
1914
+ */
1915
+ hide() {
1916
+ this.isVisible = !1;
1917
+ }
1918
+ /**
1919
+ * Shows the SettingsButton.
1920
+ */
1921
+ show() {
1922
+ this.isVisible = !0;
1923
+ }
1924
+ }
1925
+ const vs = _("settingsButton", ({
1926
+ version: e,
1927
+ postEvent: t,
1928
+ state: s = { isVisible: !1 }
1929
+ }) => new bs(s.isVisible, e, t));
1930
+ function Jt(e) {
1931
+ return Bt().parse(e);
1932
+ }
1933
+ class ys extends ht {
1934
+ /**
1935
+ * @since v6.10
1936
+ */
1937
+ get accentTextColor() {
1938
+ return this.get("accentTextColor");
1939
+ }
1940
+ get bgColor() {
1941
+ return this.get("bgColor");
1942
+ }
1943
+ get buttonColor() {
1944
+ return this.get("buttonColor");
1945
+ }
1946
+ get buttonTextColor() {
1947
+ return this.get("buttonTextColor");
1948
+ }
1949
+ get destructiveTextColor() {
1950
+ return this.get("destructiveTextColor");
1951
+ }
1952
+ /**
1953
+ * Returns the copy of the internal state of the current component instance.
1954
+ */
1955
+ getState() {
1956
+ return this.clone();
1957
+ }
1958
+ /**
1959
+ * @since v6.10
1960
+ */
1961
+ get headerBgColor() {
1962
+ return this.get("headerBgColor");
1963
+ }
1964
+ get hintColor() {
1965
+ return this.get("hintColor");
1966
+ }
1967
+ /**
1968
+ * @returns True in case, current color scheme is recognized as dark. This
1969
+ * value is calculated according to theme bg color.
1970
+ */
1971
+ get isDark() {
1972
+ return !this.bgColor || qt(this.bgColor);
1973
+ }
1974
+ get linkColor() {
1975
+ return this.get("linkColor");
1976
+ }
1977
+ get secondaryBgColor() {
1978
+ return this.get("secondaryBgColor");
1979
+ }
1980
+ /**
1981
+ * @since v6.10
1982
+ */
1983
+ get sectionBgColor() {
1984
+ return this.get("sectionBgColor");
1985
+ }
1986
+ /**
1987
+ * @since v6.10
1988
+ */
1989
+ get sectionHeaderTextColor() {
1990
+ return this.get("sectionHeaderTextColor");
1991
+ }
1992
+ /**
1993
+ * Starts listening to the external theme changes and applies them.
1994
+ * @returns Function to stop listening.
1995
+ */
1996
+ listen() {
1997
+ return E("theme_changed", (t) => {
1998
+ this.set(Jt(t.theme_params));
1999
+ });
2000
+ }
2001
+ /**
2002
+ * @since v6.10
2003
+ */
2004
+ get subtitleTextColor() {
2005
+ return this.get("subtitleTextColor");
2006
+ }
2007
+ get textColor() {
2008
+ return this.get("textColor");
2009
+ }
2010
+ }
2011
+ const Es = _("themeParams", ({ themeParams: e, state: t = e }) => {
2012
+ const s = new ys(t);
2013
+ return C() || s.listen(), s;
2014
+ });
2015
+ function mn(e = {}) {
2016
+ return m({
2017
+ ...e,
2018
+ method: "web_app_request_theme",
2019
+ event: "theme_changed"
2020
+ }).then(Jt);
2021
+ }
2022
+ class Ps extends pt {
2023
+ constructor(t, s, n) {
2024
+ super(t, { readTextFromClipboard: "web_app_read_text_from_clipboard" }), c(this, "supportsParam"), this.version = t, this.createRequestId = s, this.postEvent = n, this.supportsParam = Kt(t, {
2025
+ "openLink.tryInstantView": ["web_app_open_link", "try_instant_view"]
2026
+ });
2027
+ }
2028
+ /**
2029
+ * Opens a link in an external browser. The Mini App will not be closed.
2030
+ *
2031
+ * Note that this method can be called only in response to the user
2032
+ * interaction with the Mini App interface (e.g. click inside the Mini App
2033
+ * or on the main button).
2034
+ * @param url - URL to be opened.
2035
+ * @param tryInstantView
2036
+ */
2037
+ openLink(t, s) {
2038
+ const n = new URL(t, window.location.href).toString();
2039
+ if (!S("web_app_open_link", this.version)) {
2040
+ window.open(n, "_blank");
2041
+ return;
2042
+ }
2043
+ this.postEvent("web_app_open_link", {
2044
+ url: n,
2045
+ ...typeof s == "boolean" ? { try_instant_view: s } : {}
2046
+ });
2047
+ }
2048
+ /**
2049
+ * Opens a Telegram link inside Telegram app. The Mini App will be closed. It expects passing
2050
+ * link in full format, with hostname "t.me".
2051
+ * @param url - URL to be opened.
2052
+ * @throws {Error} URL has not allowed hostname.
2053
+ */
2054
+ openTelegramLink(t) {
2055
+ const { hostname: s, pathname: n, search: r } = new URL(t, window.location.href);
2056
+ if (s !== "t.me")
2057
+ throw new Error(`URL has not allowed hostname: ${s}. Only "t.me" is allowed`);
2058
+ if (!S("web_app_open_tg_link", this.version)) {
2059
+ window.location.href = t;
2060
+ return;
2061
+ }
2062
+ this.postEvent("web_app_open_tg_link", { path_full: n + r });
2063
+ }
2064
+ /**
2065
+ * Reads text from clipboard and returns string or null. null is returned
2066
+ * in cases:
2067
+ * - Value in clipboard is not text
2068
+ * - Access to clipboard is not allowed
2069
+ */
2070
+ async readTextFromClipboard() {
2071
+ const t = this.createRequestId(), {
2072
+ data: s = null
2073
+ } = await m({
2074
+ method: "web_app_read_text_from_clipboard",
2075
+ event: "clipboard_text_received",
2076
+ postEvent: this.postEvent,
2077
+ params: { req_id: t },
2078
+ capture: kt(t)
2079
+ });
2080
+ return s;
2081
+ }
2082
+ }
2083
+ const Rs = _(
2084
+ ({ version: e, postEvent: t, createRequestId: s }) => new Ps(e, s, t)
2085
+ );
2086
+ async function Qt(e = {}) {
2087
+ const {
2088
+ is_expanded: t,
2089
+ is_state_stable: s,
2090
+ ...n
2091
+ } = await m({
2092
+ ...e,
2093
+ method: "web_app_request_viewport",
2094
+ event: "viewport_changed"
2095
+ });
2096
+ return { ...n, isExpanded: t, isStateStable: s };
2097
+ }
2098
+ function k(e) {
2099
+ return e < 0 ? 0 : e;
2100
+ }
2101
+ class Ft extends ht {
2102
+ constructor({ postEvent: t, stableHeight: s, height: n, width: r, isExpanded: i }) {
2103
+ super({
2104
+ height: k(n),
2105
+ isExpanded: i,
2106
+ stableHeight: k(s),
2107
+ width: k(r)
2108
+ }), c(this, "postEvent"), this.postEvent = t;
2109
+ }
2110
+ /**
2111
+ * Requests viewport information from the Telegram application and updates current Viewport
2112
+ * instance.
2113
+ * @param options - options to request fresh data.
2114
+ */
2115
+ async sync(t) {
2116
+ const { isStateStable: s, ...n } = await Qt(t);
2117
+ this.set({
2118
+ ...n,
2119
+ stableHeight: s ? n.height : this.get("stableHeight")
2120
+ });
2121
+ }
2122
+ /**
2123
+ * The current height of the **visible area** of the Mini App.
2124
+ *
2125
+ * The application can display just the top part of the Mini App, with its lower part remaining
2126
+ * outside the screen area. From this position, the user can "pull" the Mini App to its
2127
+ * maximum height, while the bot can do the same by calling `expand` method. As the position of
2128
+ * the Mini App changes, the current height value of the visible area will be updated in real
2129
+ * time.
2130
+ *
2131
+ * Please note that the refresh rate of this value is not sufficient to smoothly follow the
2132
+ * lower border of the window. It should not be used to pin interface elements to the bottom
2133
+ * of the visible area. It's more appropriate to use the value of the `stableHeight`
2134
+ * field for this purpose.
2135
+ *
2136
+ * @see stableHeight
2137
+ */
2138
+ get height() {
2139
+ return this.get("height");
2140
+ }
2141
+ /**
2142
+ * The height of the visible area of the Mini App in its last stable state.
2143
+ *
2144
+ * The application can display just the top part of the Mini App, with its lower part remaining
2145
+ * outside the screen area. From this position, the user can "pull" the Mini App to its
2146
+ * maximum height, while the application can do the same by calling `expand` method.
2147
+ *
2148
+ * Unlike the value of `height`, the value of `stableHeight` does not change as the position
2149
+ * of the Mini App changes with user gestures or during animations. The value of `stableHeight`
2150
+ * will be updated after all gestures and animations are completed and
2151
+ * the Mini App reaches its final size.
2152
+ *
2153
+ * @see height
2154
+ */
2155
+ get stableHeight() {
2156
+ return this.get("stableHeight");
2157
+ }
2158
+ /**
2159
+ * Starts listening to viewport changes and applies them.
2160
+ * @returns Function to stop listening.
2161
+ */
2162
+ listen() {
2163
+ return E("viewport_changed", (t) => {
2164
+ const {
2165
+ height: s,
2166
+ width: n,
2167
+ is_expanded: r,
2168
+ is_state_stable: i
2169
+ } = t, o = k(s);
2170
+ this.set({
2171
+ height: o,
2172
+ isExpanded: r,
2173
+ width: k(n),
2174
+ ...i ? { stableHeight: o } : {}
2175
+ });
2176
+ });
2177
+ }
2178
+ /**
2179
+ * True if the Mini App is expanded to the maximum available height. Otherwise, if
2180
+ * the Mini App occupies part of the screen and can be expanded to the full height using
2181
+ * `expand` method.
2182
+ * @see expand
2183
+ */
2184
+ get isExpanded() {
2185
+ return this.get("isExpanded");
2186
+ }
2187
+ /**
2188
+ * Current visible area width.
2189
+ */
2190
+ get width() {
2191
+ return this.get("width");
2192
+ }
2193
+ /**
2194
+ * A method that expands the Mini App to the maximum available height. To find out if the Mini
2195
+ * App is expanded to the maximum height, refer to the value of the `isExpanded`.
2196
+ * @see isExpanded
2197
+ */
2198
+ expand() {
2199
+ this.postEvent("web_app_expand"), this.set("isExpanded", !0);
2200
+ }
2201
+ /**
2202
+ * True if the current viewport height is stable and is not going to change in the next moment.
2203
+ */
2204
+ get isStable() {
2205
+ return this.stableHeight === this.height;
2206
+ }
2207
+ }
2208
+ async function xs(e, t = {}) {
2209
+ const {
2210
+ height: s,
2211
+ width: n,
2212
+ isExpanded: r,
2213
+ isStateStable: i
2214
+ } = await Qt({ ...t, postEvent: e });
2215
+ return new Ft({
2216
+ postEvent: e,
2217
+ height: s,
2218
+ width: n,
2219
+ isExpanded: r,
2220
+ stableHeight: i ? s : 0
2221
+ });
2222
+ }
2223
+ function Ss({
2224
+ state: e,
2225
+ platform: t,
2226
+ postEvent: s
2227
+ }) {
2228
+ let n = !1, r = 0, i = 0, o = 0;
2229
+ return e ? (n = e.isExpanded, r = e.height, i = e.width, o = e.stableHeight) : ["macos", "tdesktop", "unigram", "webk", "weba", "web"].includes(t) && (n = !0, r = window.innerHeight, i = window.innerWidth, o = window.innerHeight), new Ft({
2230
+ postEvent: s,
2231
+ height: r,
2232
+ width: i,
2233
+ stableHeight: o,
2234
+ isExpanded: n
2235
+ });
2236
+ }
2237
+ const Cs = _(
2238
+ "viewport",
2239
+ async (e) => {
2240
+ if (C() && !e.state)
2241
+ throw l(
2242
+ nt,
2243
+ "Viewport cannot be instantiated on the server side without passing the ssr.state object."
2244
+ );
2245
+ let t = Ss(e);
2246
+ return C() || (t.width === 0 && await xs(e.postEvent, { timeout: 1e3 }).then((s) => t = s).catch((s) => H.error("Unable to sync viewport state", s)), t.listen()), t;
2247
+ }
2248
+ );
2249
+ function R(e, t) {
2250
+ document.documentElement.style.setProperty(e, t);
2251
+ }
2252
+ function bn(e, t, s) {
2253
+ s || (s = (a) => `--tg-${a}-color`);
2254
+ const n = s("header"), r = s("bg"), i = () => {
2255
+ const { headerColor: a } = e;
2256
+ if (it(a))
2257
+ R(n, a);
2258
+ else {
2259
+ const { bgColor: p, secondaryBgColor: u } = t;
2260
+ a === "bg_color" && p ? R(n, p) : a === "secondary_bg_color" && u && R(n, u);
2261
+ }
2262
+ R(r, e.bgColor);
2263
+ }, o = [
2264
+ t.on("change", i),
2265
+ e.on("change", i)
2266
+ ];
2267
+ return i(), () => o.forEach((a) => a());
2268
+ }
2269
+ function vn(e, t) {
2270
+ t || (t = (n) => `--tg-theme-${n.replace(/[A-Z]/g, (r) => `-${r.toLowerCase()}`)}`);
2271
+ const s = () => {
2272
+ Object.entries(e.getState()).forEach(([n, r]) => {
2273
+ r && R(t(n), r);
2274
+ });
2275
+ };
2276
+ return s(), e.on("change", s);
2277
+ }
2278
+ function yn(e, t) {
2279
+ t || (t = (u) => `--tg-viewport-${u}`);
2280
+ const [
2281
+ s,
2282
+ n,
2283
+ r
2284
+ ] = ["height", "width", "stable-height"].map((u) => t(u)), i = () => R(s, `${e.height}px`), o = () => R(n, `${e.width}px`), a = () => R(r, `${e.stableHeight}px`), p = [
2285
+ e.on("change:height", i),
2286
+ e.on("change:width", o),
2287
+ e.on("change:stableHeight", a)
2288
+ ];
2289
+ return i(), o(), a(), () => p.forEach((u) => u());
2290
+ }
2291
+ function Ts(e = !0) {
2292
+ const t = [
2293
+ E("reload_iframe", () => {
2294
+ q("iframe_will_reload"), window.location.reload();
2295
+ })
2296
+ ], s = () => t.forEach((n) => n());
2297
+ if (e) {
2298
+ const n = document.createElement("style");
2299
+ n.id = "telegram-custom-styles", document.head.appendChild(n), t.push(
2300
+ E("set_custom_style", (r) => {
2301
+ n.innerHTML = r;
2302
+ }),
2303
+ () => document.head.removeChild(n)
2304
+ );
2305
+ }
2306
+ return q("iframe_ready", { reload_supported: !0 }), s;
2307
+ }
2308
+ async function En() {
2309
+ if (Ct(window))
2310
+ return !0;
2311
+ try {
2312
+ return await m({ method: "web_app_request_theme", event: "theme_changed", timeout: 100 }), !0;
2313
+ } catch {
2314
+ return !1;
2315
+ }
2316
+ }
2317
+ function As(e) {
2318
+ return e instanceof W;
2319
+ }
2320
+ function Pn(e, t) {
2321
+ return As(e) && e.type === t;
2322
+ }
2323
+ function J(e, t) {
2324
+ let s, n, r;
2325
+ return typeof e == "string" ? s = e : (s = e.pathname === void 0 ? t : e.pathname, n = e.params, r = e.id), Object.freeze({
2326
+ id: r || (Math.random() * 2 ** 14 | 0).toString(16),
2327
+ pathname: s,
2328
+ params: n
2329
+ });
2330
+ }
2331
+ class ks {
2332
+ constructor(t, s, n = q) {
2333
+ if (c(this, "history"), c(this, "ee", new U()), c(this, "attached", !1), c(this, "back", () => this.go(-1)), c(this, "on", this.ee.on.bind(this.ee)), c(this, "off", this.ee.off.bind(this.ee)), this._index = s, this.postEvent = n, t.length === 0)
2334
+ throw l(ge, "History should not be empty.");
2335
+ if (s < 0 || s >= t.length)
2336
+ throw l(
2337
+ we,
2338
+ "Index should not be zero and higher or equal than history size."
2339
+ );
2340
+ this.history = t.map((r) => J(r, ""));
2341
+ }
2342
+ /**
2343
+ * Allows this navigator to control the `BackButton` visibility state. It also tracks the
2344
+ * `BackButton` clicks and calls the `back` method.
2345
+ */
2346
+ attach() {
2347
+ this.attached || (this.attached = !0, this.sync(), E("back_button_pressed", this.back));
2348
+ }
2349
+ /**
2350
+ * Currently active history item.
2351
+ */
2352
+ get current() {
2353
+ return this.history[this.index];
2354
+ }
2355
+ /**
2356
+ * Prevents current navigator from controlling the BackButton visibility state.
2357
+ */
2358
+ detach() {
2359
+ this.attached = !1, z("back_button_pressed", this.back);
2360
+ }
2361
+ /**
2362
+ * Goes to the next history item.
2363
+ */
2364
+ forward() {
2365
+ this.go(1);
2366
+ }
2367
+ /**
2368
+ * Changes currently active history item index by the specified delta. This method doesn't
2369
+ * change index in case, the updated index points to the non-existing history item. This behavior
2370
+ * is preserved until the `fit` argument is specified.
2371
+ * @param delta - index delta.
2372
+ * @param fit - cuts the delta argument to fit the bounds `[0, history.length - 1]`.
2373
+ */
2374
+ go(t, s) {
2375
+ const n = this.index + t, r = Math.min(
2376
+ Math.max(0, n),
2377
+ this.history.length - 1
2378
+ );
2379
+ (n === r || s) && this.replaceAndMove(r, this.history[r]);
2380
+ }
2381
+ /**
2382
+ * Goes to the specified index. Method does nothing in case, passed index is out of bounds.
2383
+ *
2384
+ * If "fit" option was specified and index is out of bounds, it will be cut to the nearest
2385
+ * bound.
2386
+ * @param index - target index.
2387
+ * @param fit - cuts the index argument to fit the bounds `[0, history.length - 1]`.
2388
+ */
2389
+ goTo(t, s) {
2390
+ this.go(t - this.index, s);
2391
+ }
2392
+ /**
2393
+ * True if navigator has items before the current item.
2394
+ */
2395
+ get hasPrev() {
2396
+ return this.index > 0;
2397
+ }
2398
+ /**
2399
+ * True if navigator has items after the current item.
2400
+ */
2401
+ get hasNext() {
2402
+ return this.index !== this.history.length - 1;
2403
+ }
2404
+ /**
2405
+ * Currently active history item index.
2406
+ */
2407
+ get index() {
2408
+ return this._index;
2409
+ }
2410
+ /**
2411
+ * Adds a new history item removing all after the current one.
2412
+ * @param item - item to add.
2413
+ */
2414
+ push(t) {
2415
+ this.hasNext && this.history.splice(this.index + 1), this.replaceAndMove(this.index + 1, J(t, this.current.pathname));
2416
+ }
2417
+ /**
2418
+ * Replaces the current history item.
2419
+ * @param item - item to replace the current item with.
2420
+ */
2421
+ replace(t) {
2422
+ this.replaceAndMove(this.index, J(t, this.current.pathname));
2423
+ }
2424
+ /**
2425
+ * Sets history item by the specified index.
2426
+ * @param index - history item index to replace.
2427
+ * @param historyItem - history item to set.
2428
+ */
2429
+ replaceAndMove(t, s) {
2430
+ const n = t - this.index;
2431
+ if (!n && this.current === s)
2432
+ return;
2433
+ const r = this.current;
2434
+ if (this.index !== t) {
2435
+ const i = this._index;
2436
+ this._index = t, this.attached && i > 0 != t > 0 && this.sync();
2437
+ }
2438
+ this.history[t] = s, this.ee.emit("change", {
2439
+ navigator: this,
2440
+ from: r,
2441
+ to: this.current,
2442
+ delta: n
2443
+ });
2444
+ }
2445
+ /**
2446
+ * Actualizes the `BackButton` visibility state.
2447
+ */
2448
+ sync() {
2449
+ this.postEvent("web_app_setup_back_button", { is_visible: !!this.index });
2450
+ }
2451
+ }
2452
+ function Q({
2453
+ params: e,
2454
+ ...t
2455
+ }) {
2456
+ return { ...e || { hash: "", search: "" }, ...t };
2457
+ }
2458
+ function N(e, t) {
2459
+ return e.startsWith(t) ? e : `${t}${e}`;
2460
+ }
2461
+ function $(e) {
2462
+ return new URL(
2463
+ typeof e == "string" ? e : `${e.pathname || ""}${N(e.search || "", "?")}${N(e.hash || "", "#")}`,
2464
+ "http://a"
2465
+ );
2466
+ }
2467
+ function L(e) {
2468
+ const t = typeof e == "string" ? e.startsWith("/") : !!(e.pathname && e.pathname.startsWith("/")), s = $(e);
2469
+ return `${t ? s.pathname : s.pathname.slice(1)}${s.search}${s.hash}`;
2470
+ }
2471
+ function F(e, t, s) {
2472
+ let n, r;
2473
+ typeof e == "string" ? n = e : (n = L(e), s = e.state, r = e.id);
2474
+ const { pathname: i, search: o, hash: a } = new URL(n, `http://a${N(t, "/")}`);
2475
+ return { id: r, pathname: i, params: { hash: a, search: o, state: s } };
2476
+ }
2477
+ async function O(e) {
2478
+ return e === 0 ? !0 : Promise.race([
2479
+ new Promise((t) => {
2480
+ const s = tt("popstate", () => {
2481
+ s(), t(!0);
2482
+ });
2483
+ window.history.go(e);
2484
+ }),
2485
+ // Usually, it takes about 1ms to emit this event, but we use some buffer.
2486
+ new Promise((t) => {
2487
+ setTimeout(t, 50, !1);
2488
+ })
2489
+ ]);
2490
+ }
2491
+ async function Is() {
2492
+ if (window.history.length <= 1 || (window.history.pushState(null, ""), await O(1 - window.history.length)))
2493
+ return;
2494
+ let e = await O(-1);
2495
+ for (; e; )
2496
+ e = await O(-1);
2497
+ }
2498
+ function Yt(e) {
2499
+ return $(e).pathname;
2500
+ }
2501
+ const bt = 0, Y = 1, Z = 2;
2502
+ class Zt {
2503
+ constructor(t, s, { postEvent: n, hashMode: r, base: i } = {}) {
2504
+ c(this, "navigator"), c(this, "ee", new U()), c(this, "hashMode"), c(this, "base"), c(this, "attached", !1), c(this, "onPopState", ({ state: o }) => {
2505
+ if (o === null)
2506
+ return this.push(this.parsePath(window.location.href));
2507
+ o === bt ? window.history.forward() : o === Y && this.back(), o === Z && this.forward();
2508
+ }), c(this, "onNavigatorChange", async ({
2509
+ to: o,
2510
+ from: a,
2511
+ delta: p
2512
+ }) => {
2513
+ this.attached && await this.syncHistory(), this.ee.emit("change", {
2514
+ delta: p,
2515
+ from: Q(a),
2516
+ to: Q(o),
2517
+ navigator: this
2518
+ });
2519
+ }), c(this, "on", this.ee.on.bind(this.ee)), c(this, "off", this.ee.off.bind(this.ee)), this.navigator = new ks(
2520
+ t.map((o) => F(o, "/")),
2521
+ s,
2522
+ n
2523
+ ), this.navigator.on("change", this.onNavigatorChange), this.hashMode = r, this.base = Yt(i || "");
2524
+ }
2525
+ /**
2526
+ * Attaches current navigator to the browser history allowing navigator to manipulate it.
2527
+ */
2528
+ async attach() {
2529
+ this.attached || (this.attached = !0, this.navigator.attach(), window.addEventListener("popstate", this.onPopState), await this.syncHistory());
2530
+ }
2531
+ /**
2532
+ * Goes back in history by 1.
2533
+ */
2534
+ back() {
2535
+ this.navigator.back();
2536
+ }
2537
+ /**
2538
+ * Detaches current navigator from the browser history.
2539
+ */
2540
+ detach() {
2541
+ this.attached = !1, this.navigator.detach(), window.removeEventListener("popstate", this.onPopState);
2542
+ }
2543
+ /**
2544
+ * Goes forward in history.
2545
+ */
2546
+ forward() {
2547
+ return this.navigator.forward();
2548
+ }
2549
+ /**
2550
+ * Current history cursor.
2551
+ */
2552
+ get index() {
2553
+ return this.navigator.index;
2554
+ }
2555
+ /**
2556
+ * Current history item identifier.
2557
+ */
2558
+ get id() {
2559
+ return this.navigator.current.id;
2560
+ }
2561
+ /**
2562
+ * Changes currently active history item index by the specified delta. This method doesn't
2563
+ * change index in case, the updated index points to the non-existing history item. This behavior
2564
+ * is preserved until the `fit` argument is specified.
2565
+ * @param delta - index delta.
2566
+ * @param fit - cuts the delta argument to fit the bounds `[0, history.length - 1]`.
2567
+ */
2568
+ go(t, s) {
2569
+ return this.navigator.go(t, s);
2570
+ }
2571
+ /**
2572
+ * Goes to the specified index. Method does nothing in case, passed index is out of bounds.
2573
+ *
2574
+ * If "fit" option was specified and index is out of bounds, it will be cut to the nearest
2575
+ * bound.
2576
+ * @param index - target index.
2577
+ * @param fit - cuts the index argument to fit the bounds `[0, history.length - 1]`.
2578
+ */
2579
+ goTo(t, s) {
2580
+ this.navigator.goTo(t, s);
2581
+ }
2582
+ /**
2583
+ * Current history item hash.
2584
+ * @see URL.hash
2585
+ * @example
2586
+ * "", "#my-hash"
2587
+ */
2588
+ get hash() {
2589
+ return (this.navigator.current.params || {}).hash || "";
2590
+ }
2591
+ /**
2592
+ * True if navigator has items before the current item.
2593
+ */
2594
+ get hasPrev() {
2595
+ return this.navigator.hasPrev;
2596
+ }
2597
+ /**
2598
+ * True if navigator has items after the current item.
2599
+ */
2600
+ get hasNext() {
2601
+ return this.navigator.hasNext;
2602
+ }
2603
+ /**
2604
+ * Navigation history.
2605
+ */
2606
+ get history() {
2607
+ return this.navigator.history.map(Q);
2608
+ }
2609
+ /**
2610
+ * Path, including pathname, search and hash.
2611
+ * @example Pathname only.
2612
+ * "/pathname"
2613
+ * @example Pathname + search.
2614
+ * "/pathname?search"
2615
+ * @example Pathname + hash.
2616
+ * "/pathname#hash"
2617
+ * @example Pathname + search + hash.
2618
+ * "/pathname?search#hash"
2619
+ */
2620
+ get path() {
2621
+ return L(this);
2622
+ }
2623
+ /**
2624
+ * Current pathname. Always starts with the slash.
2625
+ * @see URL.pathname
2626
+ * @example
2627
+ * "/", "/abc"
2628
+ */
2629
+ get pathname() {
2630
+ return this.navigator.current.pathname;
2631
+ }
2632
+ /**
2633
+ * Depending on the current navigation type, parses incoming path and returns it presented as
2634
+ * an object. In other words, this method parses the passed path and returns object, describing
2635
+ * how the navigator "sees" it.
2636
+ *
2637
+ * @example Hash mode is omitted.
2638
+ * parsePath('/abc?a=1#hash');
2639
+ * // { pathname: '/abc', search: '?a=1', hash: '#hash' }
2640
+ * parsePath('http://example.com/abc?a=1#hash');
2641
+ * // { pathname: '/abc', search: '?a=1', hash: '#hash' }
2642
+ *
2643
+ * @example Hash mode is enabled.
2644
+ * parsePath('/abc?a=1#tma?is=cool#yeah');
2645
+ * // { pathname: '/tma', search: '?is=cool', hash: '#yeah' }
2646
+ * parsePath('http://example.com/abc?a=1#tma?is=cool#yeah');
2647
+ * // { pathname: '/tma', search: '?is=cool', hash: '#yeah' }
2648
+ */
2649
+ parsePath(t) {
2650
+ let s = $(t);
2651
+ return this.hashMode && (s = $(s.hash.slice(1))), {
2652
+ pathname: s.pathname,
2653
+ search: s.search,
2654
+ hash: s.hash
2655
+ };
2656
+ }
2657
+ push(t, s) {
2658
+ const n = F(t, this.path), { state: r = s } = n.params;
2659
+ this.navigator.push({ ...n, params: { ...n.params, state: r } });
2660
+ }
2661
+ replace(t, s) {
2662
+ const n = F(t, this.path), { state: r = s } = n.params;
2663
+ this.navigator.replace({ ...n, params: { ...n.params, state: r } });
2664
+ }
2665
+ /**
2666
+ * Combines the navigator `base` property with the passed path data applying the navigator
2667
+ * navigation mode.
2668
+ * @param value - path presented as string or URLLike.
2669
+ */
2670
+ renderPath(t) {
2671
+ const s = (this.base.length === 1 ? "" : this.base) + N(L(t), "/");
2672
+ return this.hashMode ? N(s.slice(1), this.hashMode === "default" ? "#" : "#/") : s;
2673
+ }
2674
+ /**
2675
+ * Synchronizes current navigator state with browser history.
2676
+ */
2677
+ async syncHistory() {
2678
+ window.removeEventListener("popstate", this.onPopState);
2679
+ const { state: t } = this, s = this.renderPath(this);
2680
+ await Is(), this.hasPrev && this.hasNext ? (window.history.replaceState(Y, ""), window.history.pushState(t, "", s), window.history.pushState(Z, ""), await O(-1)) : this.hasPrev ? (window.history.replaceState(Y, ""), window.history.pushState(t, "", s)) : this.hasNext ? (window.history.replaceState(t, s), window.history.pushState(Z, ""), await O(-1)) : (window.history.replaceState(bt, ""), window.history.pushState(t, "", s)), window.addEventListener("popstate", this.onPopState);
2681
+ }
2682
+ /**
2683
+ * Current query parameters.
2684
+ * @see URL.search
2685
+ * @example
2686
+ * "", "?", "?a=1"
2687
+ */
2688
+ get search() {
2689
+ return (this.navigator.current.params || {}).search || "";
2690
+ }
2691
+ /**
2692
+ * Current history item state.
2693
+ */
2694
+ get state() {
2695
+ return (this.navigator.current.params || {}).state;
2696
+ }
2697
+ }
2698
+ function Os(e) {
2699
+ e || (e = {});
2700
+ const { href: t, hash: s } = window.location;
2701
+ let n = L(
2702
+ e.hashMode ? s.includes("?") ? s.slice(1) : `?${s.slice(1)}` : t
2703
+ );
2704
+ const r = e.base ? Yt(e.base) : void 0;
2705
+ if (r) {
2706
+ if (!n.startsWith(r))
2707
+ throw l(
2708
+ me,
2709
+ `Path "${n}" expected to be starting with "${r}"`
2710
+ );
2711
+ n = n.slice(r.length);
2712
+ }
2713
+ return new Zt([n], 0, e);
2714
+ }
2715
+ function Rn(e) {
2716
+ const t = e.match(/#(.+)/);
2717
+ return t ? t[1] : null;
2718
+ }
2719
+ function qs(e, t) {
2720
+ if (Gt()) {
2721
+ const s = sessionStorage.getItem(e);
2722
+ if (s)
2723
+ try {
2724
+ const { index: n, history: r } = JSON.parse(s);
2725
+ return new Zt(r, n, t);
2726
+ } catch (n) {
2727
+ console.error("Unable to restore hash navigator state.", n);
2728
+ }
2729
+ }
2730
+ return Os(t);
2731
+ }
2732
+ function xn(e, t) {
2733
+ const s = qs(e, t), n = () => sessionStorage.setItem(e, JSON.stringify({
2734
+ index: s.index,
2735
+ history: s.history
2736
+ }));
2737
+ return s.on("change", n), n(), s;
2738
+ }
2739
+ function g(e, t) {
2740
+ function s(n) {
2741
+ return (r, i, o) => (a) => {
2742
+ const p = a[i] || [], u = { ...a, [r]: n(...p) };
2743
+ return /* @__PURE__ */ vt(o, { ...u });
2744
+ };
2745
+ }
2746
+ return [s(e), s(t)];
2747
+ }
2748
+ const Xt = te(void 0);
2749
+ function Ns() {
2750
+ const e = ee(Xt);
2751
+ if (!e)
2752
+ throw new Error("useSDK was used outside the SDKProvider.");
2753
+ return e;
2754
+ }
2755
+ function w(e) {
2756
+ const t = (...n) => {
2757
+ const r = Ns();
2758
+ return st(() => r.use(e, ...n), [r]);
2759
+ };
2760
+ return [t, (...n) => {
2761
+ const r = t(...n);
2762
+ if ("error" in r)
2763
+ throw r.error;
2764
+ return r.result;
2765
+ }];
2766
+ }
2767
+ const [Ds, Vs] = w(ze), [Sn, Cn] = g(
2768
+ Ds,
2769
+ Vs
2770
+ ), [Bs, Ms] = w(Je), [Tn, An] = g(
2771
+ Bs,
2772
+ Ms
2773
+ ), [$s, Ls] = w(Fe), [kn, In] = g(
2774
+ $s,
2775
+ Ls
2776
+ ), [Hs, Us] = w(es), [On, qn] = g(
2777
+ Hs,
2778
+ Us
2779
+ ), [Ws, js] = w(ns), [Nn, Dn] = g(
2780
+ Ws,
2781
+ js
2782
+ ), [Gs, zs] = w(is), [Vn, Bn] = g(Gs, zs), [Ks, Js] = w(as), [Mn, $n] = g(Ks, Js), [Qs, Fs] = w(hs), [Ln, Hn] = g(Qs, Fs), [Ys, Zs] = w(ls), [Un, Wn] = g(Ys, Zs), [Xs, tn] = w(ws), [jn, Gn] = g(Xs, tn), [en, sn] = w(ms), [zn, Kn] = g(en, sn), [nn, rn] = w(vs), [Jn, Qn] = g(
2783
+ nn,
2784
+ rn
2785
+ ), [on, an] = w(Es), [Fn, Yn] = g(on, an);
2786
+ function Zn() {
2787
+ return st(jt, []);
2788
+ }
2789
+ const [cn, hn] = w(Rs), [Xn, tr] = g(cn, hn), [pn, un] = w(Cs), [er, sr] = g(pn, un);
2790
+ function nr({ children: e, acceptCustomStyles: t, debug: s }) {
2791
+ const n = lt(!0), [r, i] = se(
2792
+ () => /* @__PURE__ */ new Map()
2793
+ ), o = _t((d) => {
2794
+ n.current && i((B) => (d && d(B), new Map(B)));
2795
+ }, []), a = _t(() => o(), [o]), p = lt([]), u = st(() => ({
2796
+ use(d, ...B) {
2797
+ const ut = r.get(d);
2798
+ if (ut)
2799
+ return ut;
2800
+ let b;
2801
+ try {
2802
+ b = { result: d(...B) };
2803
+ } catch (v) {
2804
+ b = { error: v };
2805
+ }
2806
+ if ("error" in b || !b.result)
2807
+ return r.set(d, b), b;
2808
+ const dt = (v) => ("on" in v && (v.on("change", a), p.current.push(v)), { result: v });
2809
+ return b.result instanceof Promise ? (b.result.then(
2810
+ (v) => o((K) => K.set(d, dt(v))),
2811
+ (v) => o((K) => K.set(d, { error: v }))
2812
+ ), r.set(d, {}), {}) : (r.set(d, b = dt(b.result)), b);
2813
+ }
2814
+ }), [r]);
2815
+ return M(() => {
2816
+ ae(s || !1);
2817
+ }, [s]), M(() => () => {
2818
+ n.current = !1;
2819
+ }, []), M(() => {
2820
+ if (Tt())
2821
+ return Ts(t);
2822
+ }, [t]), M(() => () => p.current.forEach((d) => d.off("change", a)), [a]), /* @__PURE__ */ vt(Xt.Provider, { value: u, children: e });
2823
+ }
2824
+ export {
2825
+ Ne as BackButton,
2826
+ ks as BasicNavigator,
2827
+ ft as BiometryManager,
2828
+ Zt as BrowserNavigator,
2829
+ Qe as ClosingBehavior,
2830
+ ts as CloudStorage,
2831
+ me as ERR_INVALID_PATH_BASE,
2832
+ de as ERR_INVOKE_CUSTOM_METHOD_RESPONSE,
2833
+ pe as ERR_METHOD_PARAMETER_UNSUPPORTED,
2834
+ he as ERR_METHOD_UNSUPPORTED,
2835
+ ge as ERR_NAVIGATION_HISTORY_EMPTY,
2836
+ we as ERR_NAVIGATION_INDEX_INVALID,
2837
+ _n as ERR_NAVIGATION_ITEM_INVALID,
2838
+ Pt as ERR_PARSE,
2839
+ nt as ERR_SSR_INIT,
2840
+ fe as ERR_SSR_POST_EVENT,
2841
+ le as ERR_TIMED_OUT,
2842
+ _e as ERR_UNEXPECTED_TYPE,
2843
+ ue as ERR_UNKNOWN_ENV,
2844
+ U as EventEmitter,
2845
+ ss as HapticFeedback,
2846
+ rs as InitData,
2847
+ os as Invoice,
2848
+ cs as MainButton,
2849
+ ds as MiniApp,
2850
+ gs as Popup,
2851
+ fs as QRScanner,
2852
+ W as SDKError,
2853
+ nr as SDKProvider,
2854
+ bs as SettingsButton,
2855
+ ys as ThemeParams,
2856
+ Ps as Utils,
2857
+ Ft as Viewport,
2858
+ Xe as array,
2859
+ bn as bindMiniAppCSSVars,
2860
+ vn as bindThemeParamsCSSVars,
2861
+ yn as bindViewportCSSVars,
2862
+ P as boolean,
2863
+ kt as captureSameReq,
2864
+ et as classNames,
2865
+ Ae as compareVersions,
2866
+ Os as createBrowserNavigatorFromLocation,
2867
+ Oe as createPostEvent,
2868
+ $ as createSafeURL,
2869
+ Dt as date,
2870
+ Rn as getHash,
2871
+ Yt as getPathname,
2872
+ ze as initBackButton,
2873
+ Je as initBiometryManager,
2874
+ Fe as initClosingBehavior,
2875
+ es as initCloudStorage,
2876
+ ns as initHapticFeedback,
2877
+ is as initInitData,
2878
+ as as initInvoice,
2879
+ hs as initMainButton,
2880
+ ls as initMiniApp,
2881
+ xn as initNavigator,
2882
+ ws as initPopup,
2883
+ ms as initQRScanner,
2884
+ vs as initSettingsButton,
2885
+ Es as initThemeParams,
2886
+ Rs as initUtils,
2887
+ Cs as initViewport,
2888
+ Ts as initWeb,
2889
+ I as invokeCustomMethod,
2890
+ qt as isColorDark,
2891
+ Tt as isIframe,
2892
+ Gt as isPageReload,
2893
+ it as isRGB,
2894
+ be as isRGBShort,
2895
+ As as isSDKError,
2896
+ Pn as isSDKErrorOfType,
2897
+ C as isSSR,
2898
+ En as isTMA,
2899
+ f as json,
2900
+ wn as mergeClassNames,
2901
+ x as number,
2902
+ z as off,
2903
+ E as on,
2904
+ fn as parseInitData,
2905
+ Mt as parseLaunchParams,
2906
+ Jt as parseThemeParams,
2907
+ q as postEvent,
2908
+ m as request,
2909
+ Ke as requestBiometryInfo,
2910
+ mn as requestThemeParams,
2911
+ Qt as requestViewport,
2912
+ jt as retrieveLaunchParams,
2913
+ St as rgb,
2914
+ ct as searchParams,
2915
+ Ue as serializeLaunchParams,
2916
+ He as serializeThemeParams,
2917
+ R as setCSSVar,
2918
+ ae as setDebug,
2919
+ gn as setTargetOrigin,
2920
+ h as string,
2921
+ ie as subscribe,
2922
+ S as supports,
2923
+ Ie as targetOrigin,
2924
+ xt as toRGB,
2925
+ Et as unsubscribe,
2926
+ L as urlToPath,
2927
+ Vs as useBackButton,
2928
+ Ds as useBackButtonRaw,
2929
+ Ms as useBiometryManager,
2930
+ Bs as useBiometryManagerRaw,
2931
+ Ls as useClosingBehavior,
2932
+ $s as useClosingBehaviorRaw,
2933
+ Us as useCloudStorage,
2934
+ Hs as useCloudStorageRaw,
2935
+ js as useHapticFeedback,
2936
+ Ws as useHapticFeedbackRaw,
2937
+ zs as useInitData,
2938
+ Gs as useInitDataRaw,
2939
+ Js as useInvoice,
2940
+ Ks as useInvoiceRaw,
2941
+ Zn as useLaunchParams,
2942
+ Fs as useMainButton,
2943
+ Qs as useMainButtonRaw,
2944
+ Zs as useMiniApp,
2945
+ Ys as useMiniAppRaw,
2946
+ tn as usePopup,
2947
+ Xs as usePopupRaw,
2948
+ sn as useQRScanner,
2949
+ en as useQRScannerRaw,
2950
+ Ns as useSDK,
2951
+ rn as useSettingsButton,
2952
+ nn as useSettingsButtonRaw,
2953
+ an as useThemeParams,
2954
+ on as useThemeParamsRaw,
2955
+ hn as useUtils,
2956
+ cn as useUtilsRaw,
2957
+ un as useViewport,
2958
+ pn as useViewportRaw,
2959
+ Cn as withBackButton,
2960
+ Sn as withBackButtonRaw,
2961
+ An as withBiometryManager,
2962
+ Tn as withBiometryManagerRaw,
2963
+ In as withClosingBehavior,
2964
+ kn as withClosingBehaviorRaw,
2965
+ qn as withCloudStorage,
2966
+ On as withCloudStorageRaw,
2967
+ Dn as withHapticFeedback,
2968
+ Nn as withHapticFeedbackRaw,
2969
+ Bn as withInitData,
2970
+ Vn as withInitDataRaw,
2971
+ $n as withInvoice,
2972
+ Mn as withInvoiceRaw,
2973
+ Hn as withMainButton,
2974
+ Ln as withMainButtonRaw,
2975
+ Wn as withMiniApp,
2976
+ Un as withMiniAppRaw,
2977
+ Gn as withPopup,
2978
+ jn as withPopupRaw,
2979
+ Kn as withQRScanner,
2980
+ zn as withQRScannerRaw,
2981
+ Qn as withSettingsButton,
2982
+ Jn as withSettingsButtonRaw,
2983
+ Yn as withThemeParams,
2984
+ Fn as withThemeParamsRaw,
2985
+ Ot as withTimeout,
2986
+ tr as withUtils,
2987
+ Xn as withUtilsRaw,
2988
+ sr as withViewport,
2989
+ er as withViewportRaw
2990
+ };
2991
+ //# sourceMappingURL=index.js.map