@core-ease/telegram-kit 3.0.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 (86) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +299 -0
  3. package/dist/animation/index.d.mts +4 -0
  4. package/dist/animation/index.d.ts +4 -0
  5. package/dist/animation/index.js +2413 -0
  6. package/dist/animation/index.mjs +5 -0
  7. package/dist/animation/lottie/index.d.mts +10 -0
  8. package/dist/animation/lottie/index.d.ts +10 -0
  9. package/dist/animation/lottie/index.js +2313 -0
  10. package/dist/animation/lottie/index.mjs +4 -0
  11. package/dist/animation/tgs/index.d.mts +18 -0
  12. package/dist/animation/tgs/index.d.ts +18 -0
  13. package/dist/animation/tgs/index.js +2402 -0
  14. package/dist/animation/tgs/index.mjs +4 -0
  15. package/dist/bot/index.d.mts +477 -0
  16. package/dist/bot/index.d.ts +477 -0
  17. package/dist/bot/index.js +870 -0
  18. package/dist/bot/index.mjs +847 -0
  19. package/dist/bot-D8BnLWIi.d.mts +2041 -0
  20. package/dist/bot-D8BnLWIi.d.ts +2041 -0
  21. package/dist/browser.global.js +23 -0
  22. package/dist/chunk-7AARTHNW.mjs +40 -0
  23. package/dist/chunk-7CVYPKAL.mjs +15 -0
  24. package/dist/chunk-B3PWALX5.mjs +4418 -0
  25. package/dist/chunk-BQEUEAVK.mjs +2262 -0
  26. package/dist/chunk-FPWYSKK2.mjs +3089 -0
  27. package/dist/chunk-JXK5HCDV.mjs +254 -0
  28. package/dist/chunk-OMH2JGOH.mjs +88 -0
  29. package/dist/chunk-PXO36YTU.mjs +38 -0
  30. package/dist/core/index.d.mts +151 -0
  31. package/dist/core/index.d.ts +151 -0
  32. package/dist/core/index.js +3837 -0
  33. package/dist/core/index.mjs +495 -0
  34. package/dist/dev/index.d.mts +77 -0
  35. package/dist/dev/index.d.ts +77 -0
  36. package/dist/dev/index.js +3214 -0
  37. package/dist/dev/index.mjs +151 -0
  38. package/dist/engine-BDm1_hzn.d.mts +382 -0
  39. package/dist/engine-BDm1_hzn.d.ts +382 -0
  40. package/dist/format/index.d.mts +61 -0
  41. package/dist/format/index.d.ts +61 -0
  42. package/dist/format/index.js +121 -0
  43. package/dist/format/index.mjs +112 -0
  44. package/dist/hooks/index.d.mts +1 -0
  45. package/dist/hooks/index.d.ts +1 -0
  46. package/dist/hooks/index.js +4234 -0
  47. package/dist/hooks/index.mjs +3 -0
  48. package/dist/hooks-C5Per70R.d.mts +1066 -0
  49. package/dist/hooks-C5Per70R.d.ts +1066 -0
  50. package/dist/index.d.mts +849 -0
  51. package/dist/index.d.ts +849 -0
  52. package/dist/index.js +5026 -0
  53. package/dist/index.mjs +478 -0
  54. package/dist/keyboards/index.d.mts +50 -0
  55. package/dist/keyboards/index.d.ts +50 -0
  56. package/dist/keyboards/index.js +127 -0
  57. package/dist/keyboards/index.mjs +124 -0
  58. package/dist/links/index.d.mts +53 -0
  59. package/dist/links/index.d.ts +53 -0
  60. package/dist/links/index.js +139 -0
  61. package/dist/links/index.mjs +133 -0
  62. package/dist/lottie/index.d.mts +3 -0
  63. package/dist/lottie/index.d.ts +3 -0
  64. package/dist/lottie/index.js +2313 -0
  65. package/dist/lottie/index.mjs +4 -0
  66. package/dist/qr/index.d.mts +75 -0
  67. package/dist/qr/index.d.ts +75 -0
  68. package/dist/qr/index.js +983 -0
  69. package/dist/qr/index.mjs +946 -0
  70. package/dist/sdk/index.d.mts +322 -0
  71. package/dist/sdk/index.d.ts +322 -0
  72. package/dist/sdk/index.js +3138 -0
  73. package/dist/sdk/index.mjs +2 -0
  74. package/dist/server/index.d.mts +28 -0
  75. package/dist/server/index.d.ts +28 -0
  76. package/dist/server/index.js +254 -0
  77. package/dist/server/index.mjs +246 -0
  78. package/dist/tgs/index.d.mts +3 -0
  79. package/dist/tgs/index.d.ts +3 -0
  80. package/dist/tgs/index.js +2402 -0
  81. package/dist/tgs/index.mjs +4 -0
  82. package/dist/webapp-B-3_74nK.d.mts +842 -0
  83. package/dist/webapp-B-3_74nK.d.ts +842 -0
  84. package/dist/webapp-BDi9q3-a.d.mts +42 -0
  85. package/dist/webapp-YvmwFYUQ.d.ts +42 -0
  86. package/package.json +165 -0
@@ -0,0 +1,3837 @@
1
+ 'use strict';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+
20
+ // src/sdk/_internal/core/utils.ts
21
+ function urlSafeDecode(urlencoded) {
22
+ try {
23
+ urlencoded = urlencoded.replace(/\+/g, "%20");
24
+ return decodeURIComponent(urlencoded);
25
+ } catch (e) {
26
+ return urlencoded;
27
+ }
28
+ }
29
+ function urlParseQueryString(queryString) {
30
+ const params = {};
31
+ if (!queryString.length) {
32
+ return params;
33
+ }
34
+ const queryStringParams = queryString.split("&");
35
+ for (let i = 0; i < queryStringParams.length; i++) {
36
+ const param = queryStringParams[i].split("=");
37
+ const paramName = urlSafeDecode(param[0]);
38
+ const paramValue = param[1] == null ? null : urlSafeDecode(param[1]);
39
+ params[paramName] = paramValue;
40
+ }
41
+ return params;
42
+ }
43
+ function urlParseHashParams(locationHash) {
44
+ locationHash = locationHash.replace(/^#/, "");
45
+ const params = {};
46
+ if (!locationHash.length) {
47
+ return params;
48
+ }
49
+ if (locationHash.indexOf("=") < 0 && locationHash.indexOf("?") < 0) {
50
+ params._path = urlSafeDecode(locationHash);
51
+ return params;
52
+ }
53
+ const qIndex = locationHash.indexOf("?");
54
+ if (qIndex >= 0) {
55
+ const pathParam = locationHash.substr(0, qIndex);
56
+ params._path = urlSafeDecode(pathParam);
57
+ locationHash = locationHash.substr(qIndex + 1);
58
+ }
59
+ const queryParams = urlParseQueryString(locationHash);
60
+ for (const k in queryParams) {
61
+ params[k] = queryParams[k];
62
+ }
63
+ return params;
64
+ }
65
+ function urlAppendHashParams(url, addHash) {
66
+ const ind = url.indexOf("#");
67
+ if (ind < 0) {
68
+ return url + "#" + addHash;
69
+ }
70
+ const curHash = url.substr(ind + 1);
71
+ if (curHash.indexOf("=") >= 0 || curHash.indexOf("?") >= 0) {
72
+ return url + "&" + addHash;
73
+ }
74
+ if (curHash.length > 0) {
75
+ return url + "?" + addHash;
76
+ }
77
+ return url + addHash;
78
+ }
79
+ var SESSION_STORAGE_PREFIX = "__telegram__";
80
+ function sessionStorageSet(key, value) {
81
+ try {
82
+ window.sessionStorage.setItem(SESSION_STORAGE_PREFIX + key, JSON.stringify(value));
83
+ return true;
84
+ } catch (e) {
85
+ }
86
+ return false;
87
+ }
88
+ function sessionStorageGet(key) {
89
+ try {
90
+ const raw = window.sessionStorage.getItem(SESSION_STORAGE_PREFIX + key);
91
+ return JSON.parse(raw);
92
+ } catch (e) {
93
+ }
94
+ return null;
95
+ }
96
+ function strTrim(str) {
97
+ return String(str).replace(/^\s+|\s+$/g, "");
98
+ }
99
+ function byteLength(str) {
100
+ if (typeof window !== "undefined" && window.Blob) {
101
+ try {
102
+ return new Blob([str]).size;
103
+ } catch (e) {
104
+ }
105
+ }
106
+ let s = str.length;
107
+ for (let i = str.length - 1; i >= 0; i--) {
108
+ const code = str.charCodeAt(i);
109
+ if (code > 127 && code <= 2047) s++;
110
+ else if (code > 2047 && code <= 65535) s += 2;
111
+ if (code >= 56320 && code <= 57343) i--;
112
+ }
113
+ return s;
114
+ }
115
+ function versionCompare(v1, v2) {
116
+ const a1 = (typeof v1 === "string" ? v1 : "").replace(/^\s+|\s+$/g, "").split(".");
117
+ const a2 = (typeof v2 === "string" ? v2 : "").replace(/^\s+|\s+$/g, "").split(".");
118
+ const len = Math.max(a1.length, a2.length);
119
+ for (let i = 0; i < len; i++) {
120
+ const p1 = parseInt(a1[i]) || 0;
121
+ const p2 = parseInt(a2[i]) || 0;
122
+ if (p1 == p2) continue;
123
+ if (p1 > p2) return 1;
124
+ return -1;
125
+ }
126
+ return 0;
127
+ }
128
+ function parseColorToHex(color) {
129
+ const str = String(color);
130
+ let match;
131
+ if (match = /^\s*#([0-9a-f]{6})\s*$/i.exec(str)) {
132
+ return "#" + match[1].toLowerCase();
133
+ } else if (match = /^\s*#([0-9a-f])([0-9a-f])([0-9a-f])\s*$/i.exec(str)) {
134
+ return ("#" + match[1] + match[1] + match[2] + match[2] + match[3] + match[3]).toLowerCase();
135
+ } else if (match = /^\s*rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+\.{0,1}\d*))?\)\s*$/.exec(str)) {
136
+ let r = parseInt(match[1]);
137
+ let g = parseInt(match[2]);
138
+ let b = parseInt(match[3]);
139
+ const rHex = (r < 16 ? "0" : "") + r.toString(16);
140
+ const gHex = (g < 16 ? "0" : "") + g.toString(16);
141
+ const bHex = (b < 16 ? "0" : "") + b.toString(16);
142
+ return "#" + rHex + gHex + bHex;
143
+ }
144
+ return false;
145
+ }
146
+ function isColorDark(rgb) {
147
+ let hex = rgb.replace(/[\s#]/g, "");
148
+ if (hex.length == 3) {
149
+ hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
150
+ }
151
+ const r = parseInt(hex.substr(0, 2), 16);
152
+ const g = parseInt(hex.substr(2, 2), 16);
153
+ const b = parseInt(hex.substr(4, 2), 16);
154
+ const hsp = Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b));
155
+ return hsp < 120;
156
+ }
157
+ function generateRandomId(len, taken) {
158
+ let tries = 100;
159
+ const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
160
+ const charsLen = chars.length;
161
+ while (--tries) {
162
+ let id = "";
163
+ for (let i = 0; i < len; i++) {
164
+ id += chars[Math.floor(Math.random() * charsLen)];
165
+ }
166
+ if (!taken(id)) {
167
+ return id;
168
+ }
169
+ }
170
+ throw new Error("WebAppCallbackIdGenerateFailed");
171
+ }
172
+
173
+ // src/sdk/_internal/core/webview.ts
174
+ var TelegramWebView = class {
175
+ constructor() {
176
+ this.eventHandlers = {};
177
+ this.handleParentMessage = (event) => {
178
+ if (event.source !== window.parent) return;
179
+ let dataParsed;
180
+ try {
181
+ dataParsed = JSON.parse(event.data);
182
+ } catch (e) {
183
+ return;
184
+ }
185
+ if (!dataParsed || !dataParsed.eventType) {
186
+ return;
187
+ }
188
+ if (dataParsed.eventType == "set_custom_style") {
189
+ if (event.origin === "https://web.telegram.org" && this.iFrameStyleEl) {
190
+ this.iFrameStyleEl.innerHTML = dataParsed.eventData;
191
+ }
192
+ } else if (dataParsed.eventType == "reload_iframe") {
193
+ try {
194
+ window.parent.postMessage(JSON.stringify({ eventType: "iframe_will_reload" }), "*");
195
+ } catch (e) {
196
+ }
197
+ location.reload();
198
+ } else {
199
+ this.receiveEvent(dataParsed.eventType, dataParsed.eventData);
200
+ }
201
+ };
202
+ /** Dispatches an incoming event to every subscriber of `eventType`. */
203
+ this.receiveEvent = (eventType, eventData) => {
204
+ console.log("[@core-ease/telegram-kit:webview] < receiveEvent", eventType, eventData);
205
+ this.callEventCallbacks(eventType, (callback) => callback(eventType, eventData));
206
+ };
207
+ let locationHash = "";
208
+ try {
209
+ locationHash = location.hash.toString();
210
+ } catch (e) {
211
+ }
212
+ const parsedParams = urlParseHashParams(locationHash);
213
+ const storedParams = sessionStorageGet("initParams");
214
+ if (storedParams) {
215
+ for (const key in storedParams) {
216
+ if (typeof parsedParams[key] === "undefined") {
217
+ parsedParams[key] = storedParams[key];
218
+ }
219
+ }
220
+ }
221
+ sessionStorageSet("initParams", parsedParams);
222
+ this.initParams = parsedParams;
223
+ let isIframe = false;
224
+ try {
225
+ isIframe = window.parent != null && window !== window.parent;
226
+ if (isIframe) {
227
+ window.addEventListener("message", this.handleParentMessage);
228
+ this.iFrameStyleEl = document.createElement("style");
229
+ document.head.appendChild(this.iFrameStyleEl);
230
+ try {
231
+ window.parent.postMessage(
232
+ JSON.stringify({ eventType: "iframe_ready", eventData: { reload_supported: true } }),
233
+ "*"
234
+ );
235
+ } catch (e) {
236
+ }
237
+ }
238
+ } catch (e) {
239
+ }
240
+ this.isIframe = isIframe;
241
+ window.TelegramGameProxy_receiveEvent = this.receiveEvent;
242
+ window.TelegramGameProxy = { receiveEvent: this.receiveEvent };
243
+ }
244
+ /** Sends a named event + payload to the native Telegram client. */
245
+ postEvent(eventType, callback, eventData = "") {
246
+ const cb = callback || (() => {
247
+ });
248
+ console.log("[@core-ease/telegram-kit:webview] > postEvent", eventType, eventData);
249
+ if (window.TelegramWebviewProxy !== void 0) {
250
+ window.TelegramWebviewProxy.postEvent(eventType, JSON.stringify(eventData));
251
+ cb();
252
+ } else if (window.external && "notify" in window.external) {
253
+ window.external.notify(JSON.stringify({ eventType, eventData }));
254
+ cb();
255
+ } else if (this.isIframe) {
256
+ try {
257
+ const trustedTarget = "*";
258
+ window.parent.postMessage(JSON.stringify({ eventType, eventData }), trustedTarget);
259
+ cb();
260
+ } catch (e) {
261
+ cb(e);
262
+ }
263
+ } else {
264
+ cb({ notAvailable: true });
265
+ }
266
+ }
267
+ callEventCallbacks(eventType, func) {
268
+ const handlers = this.eventHandlers[eventType];
269
+ if (!handlers || !handlers.length) {
270
+ return;
271
+ }
272
+ for (let i = 0; i < handlers.length; i++) {
273
+ try {
274
+ func(handlers[i]);
275
+ } catch (e) {
276
+ }
277
+ }
278
+ }
279
+ onEvent(eventType, callback) {
280
+ if (this.eventHandlers[eventType] === void 0) {
281
+ this.eventHandlers[eventType] = [];
282
+ }
283
+ if (this.eventHandlers[eventType].indexOf(callback) === -1) {
284
+ this.eventHandlers[eventType].push(callback);
285
+ }
286
+ }
287
+ offEvent(eventType, callback) {
288
+ const handlers = this.eventHandlers[eventType];
289
+ if (handlers === void 0) {
290
+ return;
291
+ }
292
+ const index = handlers.indexOf(callback);
293
+ if (index === -1) {
294
+ return;
295
+ }
296
+ handlers.splice(index, 1);
297
+ }
298
+ };
299
+ var Utils = {
300
+ urlSafeDecode,
301
+ urlParseQueryString,
302
+ urlParseHashParams,
303
+ urlAppendHashParams,
304
+ sessionStorageSet,
305
+ sessionStorageGet
306
+ };
307
+
308
+ // src/sdk/_internal/core/errors.ts
309
+ var WebAppError = class _WebAppError extends Error {
310
+ constructor(name) {
311
+ super(name);
312
+ this.name = name;
313
+ this.message = name;
314
+ Object.setPrototypeOf(this, _WebAppError.prototype);
315
+ }
316
+ };
317
+ function throwWebAppError(name) {
318
+ throw new WebAppError(name);
319
+ }
320
+
321
+ // src/sdk/_internal/core/kernel.ts
322
+ var WebAppKernel = class {
323
+ constructor(webView) {
324
+ /** Mutable current protocol version reported by the client, e.g. '8.0'. */
325
+ this._version = "6.0";
326
+ this.callbacks = {};
327
+ /** Height (px) reserved by the in-browser debug bottom bar, if active. */
328
+ this.bottomBarHeightPx = 0;
329
+ this.onCustomMethodInvoked = (_eventType, eventData) => {
330
+ var _a;
331
+ if (eventData.req_id && this.hasCallback(eventData.req_id)) {
332
+ const entry = this.takeCallback(eventData.req_id);
333
+ let res = null;
334
+ let err = null;
335
+ if (typeof eventData.result !== "undefined") {
336
+ res = eventData.result;
337
+ }
338
+ if (typeof eventData.error !== "undefined") {
339
+ err = eventData.error;
340
+ }
341
+ (_a = entry == null ? void 0 : entry.callback) == null ? void 0 : _a.call(entry, err, res);
342
+ }
343
+ };
344
+ this.webView = webView;
345
+ this.initParams = webView.initParams;
346
+ if (this.initParams.tgWebAppVersion) {
347
+ this._version = this.initParams.tgWebAppVersion;
348
+ }
349
+ }
350
+ get version() {
351
+ return this._version;
352
+ }
353
+ set version(v) {
354
+ this._version = v;
355
+ }
356
+ versionAtLeast(ver) {
357
+ return versionCompare(this._version, ver) >= 0;
358
+ }
359
+ /** Logs + throws `WebAppMethodUnsupported` for a method gated by version. */
360
+ requireVersion(ver, methodName) {
361
+ if (!this.versionAtLeast(ver)) {
362
+ console.error(`[@core-ease/telegram-kit] Method ${methodName} is not supported in version ${this._version}`);
363
+ throwWebAppError("WebAppMethodUnsupported" /* MethodUnsupported */);
364
+ }
365
+ }
366
+ /** Same as {@link requireVersion} but warns instead of throwing (soft-gated features). */
367
+ warnIfUnsupported(ver, featureName) {
368
+ if (!this.versionAtLeast(ver)) {
369
+ console.warn(`[@core-ease/telegram-kit] ${featureName} is not supported in version ${this._version}`);
370
+ return false;
371
+ }
372
+ return true;
373
+ }
374
+ setCssProperty(name, value) {
375
+ const root = document.documentElement;
376
+ if (root && root.style && root.style.setProperty) {
377
+ root.style.setProperty("--tg-" + name, value);
378
+ }
379
+ }
380
+ strTrim(str) {
381
+ return strTrim(str);
382
+ }
383
+ byteLength(str) {
384
+ return byteLength(str);
385
+ }
386
+ /** Dispatches an internal `webview:<eventType>` event to WebApp-level subscribers. */
387
+ receiveWebViewEvent(eventType, ...args) {
388
+ this.webView.callEventCallbacks("webview:" + eventType, (callback) => {
389
+ callback.apply(null, args);
390
+ });
391
+ }
392
+ onWebViewEvent(eventType, callback) {
393
+ this.webView.onEvent("webview:" + eventType, callback);
394
+ }
395
+ offWebViewEvent(eventType, callback) {
396
+ this.webView.offEvent("webview:" + eventType, callback);
397
+ }
398
+ /** Allocates a fresh request id and registers its pending callback. */
399
+ registerCallback(callback, len = 16) {
400
+ const id = generateRandomId(len, (candidate) => !!this.callbacks[candidate]);
401
+ this.callbacks[id] = { callback };
402
+ return id;
403
+ }
404
+ takeCallback(reqId) {
405
+ const entry = this.callbacks[reqId];
406
+ if (entry) {
407
+ delete this.callbacks[reqId];
408
+ }
409
+ return entry;
410
+ }
411
+ hasCallback(reqId) {
412
+ return !!this.callbacks[reqId];
413
+ }
414
+ /** Generic `web_app_invoke_custom_method` used by CloudStorage, contact lookup, etc. */
415
+ invokeCustomMethod(method, params, callback) {
416
+ this.requireVersion("6.9", "invokeCustomMethod");
417
+ const reqId = this.registerCallback(callback);
418
+ this.webView.postEvent("web_app_invoke_custom_method", void 0, {
419
+ req_id: reqId,
420
+ method,
421
+ params: params || {}
422
+ });
423
+ }
424
+ };
425
+
426
+ // src/sdk/_internal/theme/theme-manager.ts
427
+ var ThemeManager = class {
428
+ constructor(kernel) {
429
+ this.kernel = kernel;
430
+ this.themeParams = {};
431
+ this._colorScheme = "light";
432
+ this.backgroundColorValue = "bg_color";
433
+ this.appBackgroundColor = null;
434
+ this.headerColorKey = "bg_color";
435
+ this.headerColorValue = null;
436
+ this.appHeaderColorKey = null;
437
+ this.appHeaderColorValue = null;
438
+ this.bottomBarColorValue = "bottom_bar_bg_color";
439
+ this.appBottomBarColor = null;
440
+ /** Called after every bottom-bar color update, e.g. to refresh the debug bar. */
441
+ this.onBottomBarColorApplied = null;
442
+ const storedTheme = sessionStorageGet("themeParams");
443
+ const rawTheme = kernel.initParams.tgWebAppThemeParams;
444
+ if (rawTheme && rawTheme.length) {
445
+ try {
446
+ const parsed = JSON.parse(rawTheme);
447
+ if (parsed) this.setThemeParams(parsed);
448
+ } catch (e) {
449
+ }
450
+ }
451
+ if (storedTheme) {
452
+ this.setThemeParams(storedTheme);
453
+ }
454
+ const storedColors = sessionStorageGet("defaultColors");
455
+ const rawColors = kernel.initParams.tgWebAppDefaultColors;
456
+ if (rawColors && rawColors.length) {
457
+ try {
458
+ const parsed = JSON.parse(rawColors);
459
+ if (parsed) this.setDefaultColors(parsed);
460
+ } catch (e) {
461
+ }
462
+ }
463
+ if (storedColors) {
464
+ this.setDefaultColors(storedColors);
465
+ }
466
+ }
467
+ get colorScheme() {
468
+ return this._colorScheme;
469
+ }
470
+ getThemeParams() {
471
+ return this.themeParams;
472
+ }
473
+ setThemeParams(theme) {
474
+ if (theme.bg_color == "#1c1c1d" && theme.bg_color == theme.secondary_bg_color) {
475
+ theme.secondary_bg_color = "#2c2c2e";
476
+ }
477
+ for (const key in theme) {
478
+ const color = parseColorToHex(theme[key]);
479
+ if (color) {
480
+ this.themeParams[key] = color;
481
+ if (key == "bg_color") {
482
+ this._colorScheme = isColorDark(color) ? "dark" : "light";
483
+ this.kernel.setCssProperty("color-scheme", this._colorScheme);
484
+ }
485
+ const cssKey = "theme-" + key.split("_").join("-");
486
+ this.kernel.setCssProperty(cssKey, color);
487
+ }
488
+ }
489
+ sessionStorageSet("themeParams", this.themeParams);
490
+ }
491
+ setDefaultColors(defColors) {
492
+ if (this._colorScheme == "dark") {
493
+ if (defColors.bg_dark_color) {
494
+ this.backgroundColorValue = defColors.bg_dark_color;
495
+ }
496
+ if (defColors.header_dark_color) {
497
+ this.headerColorKey = null;
498
+ this.headerColorValue = defColors.header_dark_color;
499
+ }
500
+ } else {
501
+ if (defColors.bg_color) {
502
+ this.backgroundColorValue = defColors.bg_color;
503
+ }
504
+ if (defColors.header_color) {
505
+ this.headerColorKey = null;
506
+ this.headerColorValue = defColors.header_color;
507
+ }
508
+ }
509
+ sessionStorageSet("defaultColors", defColors);
510
+ }
511
+ // ---------------------------------------------------------------------
512
+ // Header color
513
+ // ---------------------------------------------------------------------
514
+ getHeaderColor() {
515
+ if (this.headerColorKey == "secondary_bg_color") {
516
+ return this.themeParams.secondary_bg_color;
517
+ } else if (this.headerColorKey == "bg_color") {
518
+ return this.themeParams.bg_color;
519
+ }
520
+ return this.headerColorValue;
521
+ }
522
+ setHeaderColor(color) {
523
+ if (!this.kernel.warnIfUnsupported("6.1", "Header color")) {
524
+ return;
525
+ }
526
+ if (!this.kernel.versionAtLeast("6.9")) {
527
+ if (this.themeParams.bg_color && this.themeParams.bg_color == color) {
528
+ color = "bg_color";
529
+ } else if (this.themeParams.secondary_bg_color && this.themeParams.secondary_bg_color == color) {
530
+ color = "secondary_bg_color";
531
+ }
532
+ }
533
+ let headColor = null;
534
+ let colorKey = null;
535
+ if (color == "bg_color" || color == "secondary_bg_color") {
536
+ colorKey = color;
537
+ } else if (this.kernel.versionAtLeast("6.9")) {
538
+ headColor = parseColorToHex(color);
539
+ if (!headColor) {
540
+ console.error("[@core-ease/telegram-kit] Header color format is invalid", color);
541
+ throwWebAppError("WebAppHeaderColorInvalid" /* HeaderColorInvalid */);
542
+ }
543
+ }
544
+ if (!this.kernel.versionAtLeast("6.9") && colorKey != "bg_color" && colorKey != "secondary_bg_color") {
545
+ console.error(
546
+ "[@core-ease/telegram-kit] Header color key should be one of Telegram.WebApp.themeParams.bg_color, Telegram.WebApp.themeParams.secondary_bg_color, 'bg_color', 'secondary_bg_color'",
547
+ color
548
+ );
549
+ throwWebAppError("WebAppHeaderColorKeyInvalid" /* HeaderColorKeyInvalid */);
550
+ }
551
+ this.headerColorKey = colorKey;
552
+ this.headerColorValue = headColor || null;
553
+ this.updateHeaderColor();
554
+ }
555
+ updateHeaderColor() {
556
+ if (this.appHeaderColorKey != this.headerColorKey || this.appHeaderColorValue != this.headerColorValue) {
557
+ this.appHeaderColorKey = this.headerColorKey;
558
+ this.appHeaderColorValue = this.headerColorValue;
559
+ if (this.appHeaderColorValue) {
560
+ this.kernel.webView.postEvent("web_app_set_header_color", void 0, { color: this.appHeaderColorValue });
561
+ } else {
562
+ this.kernel.webView.postEvent("web_app_set_header_color", void 0, { color_key: this.appHeaderColorKey });
563
+ }
564
+ }
565
+ }
566
+ // ---------------------------------------------------------------------
567
+ // Background color
568
+ // ---------------------------------------------------------------------
569
+ getBackgroundColor() {
570
+ if (this.backgroundColorValue == "secondary_bg_color") {
571
+ return this.themeParams.secondary_bg_color;
572
+ } else if (this.backgroundColorValue == "bg_color") {
573
+ return this.themeParams.bg_color;
574
+ }
575
+ return this.backgroundColorValue;
576
+ }
577
+ setBackgroundColor(color) {
578
+ if (!this.kernel.warnIfUnsupported("6.1", "Background color")) {
579
+ return;
580
+ }
581
+ let bgColor;
582
+ if (color == "bg_color" || color == "secondary_bg_color") {
583
+ bgColor = color;
584
+ } else {
585
+ const parsed = parseColorToHex(color);
586
+ if (!parsed) {
587
+ console.error("[@core-ease/telegram-kit] Background color format is invalid", color);
588
+ throwWebAppError("WebAppBackgroundColorInvalid" /* BackgroundColorInvalid */);
589
+ }
590
+ bgColor = parsed;
591
+ }
592
+ this.backgroundColorValue = bgColor;
593
+ this.updateBackgroundColor();
594
+ }
595
+ updateBackgroundColor() {
596
+ const color = this.getBackgroundColor();
597
+ if (this.appBackgroundColor != color) {
598
+ this.appBackgroundColor = color != null ? color : null;
599
+ this.kernel.webView.postEvent("web_app_set_background_color", void 0, { color });
600
+ }
601
+ }
602
+ // ---------------------------------------------------------------------
603
+ // Bottom bar color
604
+ // ---------------------------------------------------------------------
605
+ getBottomBarColor() {
606
+ if (this.bottomBarColorValue == "bottom_bar_bg_color") {
607
+ return this.themeParams.bottom_bar_bg_color || this.themeParams.secondary_bg_color || "#ffffff";
608
+ } else if (this.bottomBarColorValue == "secondary_bg_color") {
609
+ return this.themeParams.secondary_bg_color;
610
+ } else if (this.bottomBarColorValue == "bg_color") {
611
+ return this.themeParams.bg_color;
612
+ }
613
+ return this.bottomBarColorValue;
614
+ }
615
+ setBottomBarColor(color) {
616
+ if (!this.kernel.warnIfUnsupported("7.10", "Bottom bar color")) {
617
+ return;
618
+ }
619
+ let bgColor;
620
+ if (color == "bg_color" || color == "secondary_bg_color" || color == "bottom_bar_bg_color") {
621
+ bgColor = color;
622
+ } else {
623
+ const parsed = parseColorToHex(color);
624
+ if (!parsed) {
625
+ console.error("[@core-ease/telegram-kit] Bottom bar color format is invalid", color);
626
+ throwWebAppError("WebAppBottomBarColorInvalid" /* BottomBarColorInvalid */);
627
+ }
628
+ bgColor = parsed;
629
+ }
630
+ this.bottomBarColorValue = bgColor;
631
+ this.updateBottomBarColor();
632
+ }
633
+ updateBottomBarColor() {
634
+ var _a;
635
+ const color = this.getBottomBarColor();
636
+ if (this.appBottomBarColor != color) {
637
+ this.appBottomBarColor = color;
638
+ this.kernel.webView.postEvent("web_app_set_bottom_bar_color", void 0, { color });
639
+ }
640
+ (_a = this.onBottomBarColorApplied) == null ? void 0 : _a.call(this);
641
+ }
642
+ };
643
+
644
+ // src/sdk/_internal/theme/viewport-manager.ts
645
+ var ViewportManager = class {
646
+ constructor(kernel) {
647
+ this.kernel = kernel;
648
+ this.viewportHeightPx = false;
649
+ this.viewportStableHeightPx = false;
650
+ this._isExpanded = true;
651
+ this._safeAreaInset = { top: 0, bottom: 0, left: 0, right: 0 };
652
+ this._contentSafeAreaInset = { top: 0, bottom: 0, left: 0, right: 0 };
653
+ this._isFullscreen = false;
654
+ this._isOrientationLocked = false;
655
+ this._isClosingConfirmationEnabled = false;
656
+ this._isVerticalSwipesEnabled = true;
657
+ this.lastWindowHeight = typeof window !== "undefined" ? window.innerHeight : 0;
658
+ this.handleViewportChanged = (_eventType, eventData) => {
659
+ if (eventData.height) {
660
+ window.removeEventListener("resize", this.onWindowResize);
661
+ this.setViewportHeight(eventData);
662
+ }
663
+ };
664
+ this.handleSafeAreaChanged = (_eventType, eventData) => {
665
+ if (eventData) this.setSafeAreaInset(eventData);
666
+ };
667
+ this.handleContentSafeAreaChanged = (_eventType, eventData) => {
668
+ if (eventData) this.setContentSafeAreaInset(eventData);
669
+ };
670
+ this.handleFullscreenChanged = (_eventType, eventData) => {
671
+ this.setFullscreen(eventData.is_fullscreen);
672
+ this.kernel.receiveWebViewEvent("fullscreenChanged");
673
+ };
674
+ this.handleFullscreenFailed = (_eventType, eventData) => {
675
+ if (eventData.error == "ALREADY_FULLSCREEN" && !this._isFullscreen) {
676
+ this.setFullscreen(true);
677
+ }
678
+ this.kernel.receiveWebViewEvent("fullscreenFailed", { error: eventData.error });
679
+ };
680
+ if (kernel.initParams.tgWebAppFullscreen) {
681
+ this.setFullscreen(true);
682
+ }
683
+ const storedFullscreen = sessionStorageGet("isFullscreen");
684
+ if (storedFullscreen) {
685
+ this.setFullscreen(storedFullscreen == "yes");
686
+ }
687
+ const storedOrientationLock = sessionStorageGet("isOrientationLocked");
688
+ if (storedOrientationLock) {
689
+ this.setOrientationLock(storedOrientationLock == "yes");
690
+ }
691
+ this.onWindowResize = this.onWindowResize.bind(this);
692
+ }
693
+ // ---------------------------------------------------------------------
694
+ // Getters mirroring the public WebApp properties
695
+ // ---------------------------------------------------------------------
696
+ get isExpanded() {
697
+ return this._isExpanded;
698
+ }
699
+ get viewportHeight() {
700
+ const raw = this.viewportHeightPx === false ? window.innerHeight : this.viewportHeightPx;
701
+ return raw - this.kernel.bottomBarHeightPx;
702
+ }
703
+ get viewportStableHeight() {
704
+ const raw = this.viewportStableHeightPx === false ? window.innerHeight : this.viewportStableHeightPx;
705
+ return raw - this.kernel.bottomBarHeightPx;
706
+ }
707
+ get safeAreaInset() {
708
+ return this._safeAreaInset;
709
+ }
710
+ get contentSafeAreaInset() {
711
+ return this._contentSafeAreaInset;
712
+ }
713
+ get isFullscreen() {
714
+ return this._isFullscreen;
715
+ }
716
+ get isOrientationLocked() {
717
+ return this._isOrientationLocked;
718
+ }
719
+ get isClosingConfirmationEnabled() {
720
+ return this._isClosingConfirmationEnabled;
721
+ }
722
+ get isVerticalSwipesEnabled() {
723
+ return this._isVerticalSwipesEnabled;
724
+ }
725
+ // ---------------------------------------------------------------------
726
+ // Viewport height
727
+ // ---------------------------------------------------------------------
728
+ /** Re-applies the current viewport CSS vars; call after bottom-bar height changes too. */
729
+ setViewportHeight(data) {
730
+ let emitEvent = false;
731
+ if (typeof data !== "undefined") {
732
+ this._isExpanded = !!data.is_expanded;
733
+ this.viewportHeightPx = data.height;
734
+ if (data.is_state_stable) {
735
+ this.viewportStableHeightPx = data.height;
736
+ }
737
+ emitEvent = true;
738
+ }
739
+ const bottomBarHeight = this.kernel.bottomBarHeightPx;
740
+ const height = this.viewportHeightPx !== false ? this.viewportHeightPx - bottomBarHeight + "px" : bottomBarHeight ? `calc(100vh - ${bottomBarHeight}px)` : "100vh";
741
+ const stableHeight = this.viewportStableHeightPx !== false ? this.viewportStableHeightPx - bottomBarHeight + "px" : bottomBarHeight ? `calc(100vh - ${bottomBarHeight}px)` : "100vh";
742
+ this.kernel.setCssProperty("viewport-height", height);
743
+ this.kernel.setCssProperty("viewport-stable-height", stableHeight);
744
+ if (emitEvent) {
745
+ this.kernel.receiveWebViewEvent("viewportChanged", { isStateStable: !!data.is_state_stable });
746
+ }
747
+ }
748
+ onWindowResize() {
749
+ if (this.lastWindowHeight != window.innerHeight) {
750
+ this.lastWindowHeight = window.innerHeight;
751
+ this.kernel.receiveWebViewEvent("viewportChanged", { isStateStable: true });
752
+ }
753
+ }
754
+ // ---------------------------------------------------------------------
755
+ // Safe area insets
756
+ // ---------------------------------------------------------------------
757
+ setSafeAreaInset(data) {
758
+ if (typeof data !== "undefined") {
759
+ if (typeof data.top !== "undefined") this._safeAreaInset.top = data.top;
760
+ if (typeof data.bottom !== "undefined") this._safeAreaInset.bottom = data.bottom;
761
+ if (typeof data.left !== "undefined") this._safeAreaInset.left = data.left;
762
+ if (typeof data.right !== "undefined") this._safeAreaInset.right = data.right;
763
+ this.kernel.receiveWebViewEvent("safeAreaChanged");
764
+ }
765
+ this.kernel.setCssProperty("safe-area-inset-top", this._safeAreaInset.top + "px");
766
+ this.kernel.setCssProperty("safe-area-inset-bottom", this._safeAreaInset.bottom + "px");
767
+ this.kernel.setCssProperty("safe-area-inset-left", this._safeAreaInset.left + "px");
768
+ this.kernel.setCssProperty("safe-area-inset-right", this._safeAreaInset.right + "px");
769
+ }
770
+ setContentSafeAreaInset(data) {
771
+ if (typeof data !== "undefined") {
772
+ if (typeof data.top !== "undefined") this._contentSafeAreaInset.top = data.top;
773
+ if (typeof data.bottom !== "undefined") this._contentSafeAreaInset.bottom = data.bottom;
774
+ if (typeof data.left !== "undefined") this._contentSafeAreaInset.left = data.left;
775
+ if (typeof data.right !== "undefined") this._contentSafeAreaInset.right = data.right;
776
+ this.kernel.receiveWebViewEvent("contentSafeAreaChanged");
777
+ }
778
+ this.kernel.setCssProperty("content-safe-area-inset-top", this._contentSafeAreaInset.top + "px");
779
+ this.kernel.setCssProperty("content-safe-area-inset-bottom", this._contentSafeAreaInset.bottom + "px");
780
+ this.kernel.setCssProperty("content-safe-area-inset-left", this._contentSafeAreaInset.left + "px");
781
+ this.kernel.setCssProperty("content-safe-area-inset-right", this._contentSafeAreaInset.right + "px");
782
+ }
783
+ // ---------------------------------------------------------------------
784
+ // Closing confirmation / vertical swipes
785
+ // ---------------------------------------------------------------------
786
+ setClosingConfirmation(needConfirmation) {
787
+ if (!this.kernel.warnIfUnsupported("6.2", "Closing confirmation")) {
788
+ return;
789
+ }
790
+ this._isClosingConfirmationEnabled = !!needConfirmation;
791
+ this.kernel.webView.postEvent("web_app_setup_closing_behavior", void 0, {
792
+ need_confirmation: this._isClosingConfirmationEnabled
793
+ });
794
+ }
795
+ toggleVerticalSwipes(enableSwipes) {
796
+ if (!this.kernel.warnIfUnsupported("7.7", "Changing swipes behavior")) {
797
+ return;
798
+ }
799
+ this._isVerticalSwipesEnabled = !!enableSwipes;
800
+ this.kernel.webView.postEvent("web_app_setup_swipe_behavior", void 0, {
801
+ allow_vertical_swipe: this._isVerticalSwipesEnabled
802
+ });
803
+ }
804
+ // ---------------------------------------------------------------------
805
+ // Fullscreen
806
+ // ---------------------------------------------------------------------
807
+ setFullscreen(isFullscreen) {
808
+ this._isFullscreen = !!isFullscreen;
809
+ sessionStorageSet("isFullscreen", this._isFullscreen ? "yes" : "no");
810
+ }
811
+ requestFullscreen() {
812
+ this.kernel.requireVersion("8.0", "requestFullscreen");
813
+ this.kernel.webView.postEvent("web_app_request_fullscreen");
814
+ }
815
+ exitFullscreen() {
816
+ this.kernel.requireVersion("8.0", "exitFullscreen");
817
+ this.kernel.webView.postEvent("web_app_exit_fullscreen");
818
+ }
819
+ // ---------------------------------------------------------------------
820
+ // Orientation lock
821
+ // ---------------------------------------------------------------------
822
+ setOrientationLock(isLocked) {
823
+ this._isOrientationLocked = !!isLocked;
824
+ sessionStorageSet("isOrientationLocked", this._isOrientationLocked ? "yes" : "no");
825
+ }
826
+ toggleOrientationLock(locked) {
827
+ if (!this.kernel.warnIfUnsupported("8.0", "Orientation locking")) {
828
+ return;
829
+ }
830
+ this.setOrientationLock(locked);
831
+ this.kernel.webView.postEvent("web_app_toggle_orientation_lock", void 0, {
832
+ locked: this._isOrientationLocked
833
+ });
834
+ }
835
+ };
836
+
837
+ // src/sdk/_internal/ui/back-button.ts
838
+ var BackButton = class {
839
+ constructor(kernel) {
840
+ this.kernel = kernel;
841
+ this._isVisible = false;
842
+ this.curButtonState = null;
843
+ this.handleBackButtonPressed = () => {
844
+ this.kernel.receiveWebViewEvent("backButtonClicked");
845
+ };
846
+ kernel.webView.onEvent("back_button_pressed", this.handleBackButtonPressed);
847
+ }
848
+ get isVisible() {
849
+ return this._isVisible;
850
+ }
851
+ set isVisible(val) {
852
+ this.setParams({ is_visible: val });
853
+ }
854
+ checkVersion() {
855
+ return this.kernel.warnIfUnsupported("6.1", "BackButton");
856
+ }
857
+ buttonParams() {
858
+ return { is_visible: this._isVisible };
859
+ }
860
+ updateButton() {
861
+ const params = this.buttonParams();
862
+ const state = JSON.stringify(params);
863
+ if (this.curButtonState === state) {
864
+ return;
865
+ }
866
+ this.curButtonState = state;
867
+ this.kernel.webView.postEvent("web_app_setup_back_button", void 0, params);
868
+ }
869
+ setParams(params) {
870
+ if (!this.checkVersion()) {
871
+ return this;
872
+ }
873
+ if (typeof params.is_visible !== "undefined") {
874
+ this._isVisible = !!params.is_visible;
875
+ }
876
+ this.updateButton();
877
+ return this;
878
+ }
879
+ onClick(callback) {
880
+ if (this.checkVersion()) {
881
+ this.kernel.onWebViewEvent("backButtonClicked", callback);
882
+ }
883
+ return this;
884
+ }
885
+ offClick(callback) {
886
+ if (this.checkVersion()) {
887
+ this.kernel.offWebViewEvent("backButtonClicked", callback);
888
+ }
889
+ return this;
890
+ }
891
+ show() {
892
+ return this.setParams({ is_visible: true });
893
+ }
894
+ hide() {
895
+ return this.setParams({ is_visible: false });
896
+ }
897
+ };
898
+
899
+ // src/sdk/_internal/ui/bottom-button.ts
900
+ var BottomButton = class {
901
+ constructor(type, kernel, theme, debugBar) {
902
+ this.kernel = kernel;
903
+ this.theme = theme;
904
+ this.debugBar = debugBar;
905
+ this.isVisibleValue = false;
906
+ this.isActiveValue = true;
907
+ this.hasShineEffectValue = false;
908
+ this.isProgressVisibleValue = false;
909
+ this.iconCustomEmojiIdValue = false;
910
+ this.colorValue = false;
911
+ this.textColorValue = false;
912
+ this.positionValue = "left";
913
+ this.curButtonState = null;
914
+ this.handlePressed = () => {
915
+ if (this.isActiveValue) {
916
+ this.kernel.receiveWebViewEvent(this.webViewEventName);
917
+ }
918
+ };
919
+ this.type = type;
920
+ this.isMain = type === "main";
921
+ if (this.isMain) {
922
+ this.setupEventName = "web_app_setup_main_button";
923
+ this.nativePressEventName = "main_button_pressed";
924
+ this.webViewEventName = "mainButtonClicked";
925
+ this.defaultText = "Continue";
926
+ this.defaultColor = () => theme.getThemeParams().button_color || "#2481cc";
927
+ this.defaultTextColor = () => theme.getThemeParams().button_text_color || "#ffffff";
928
+ } else {
929
+ this.setupEventName = "web_app_setup_secondary_button";
930
+ this.nativePressEventName = "secondary_button_pressed";
931
+ this.webViewEventName = "secondaryButtonClicked";
932
+ this.defaultText = "Cancel";
933
+ this.defaultColor = () => theme.getBottomBarColor();
934
+ this.defaultTextColor = () => theme.getThemeParams().button_color || "#2481cc";
935
+ }
936
+ this.textValue = this.defaultText;
937
+ kernel.webView.onEvent(this.nativePressEventName, this.handlePressed);
938
+ debugBar.registerButton(type, this.handlePressed);
939
+ }
940
+ // ---------------------------------------------------------------------
941
+ // Public property accessors (mirrors Object.defineProperty in original)
942
+ // ---------------------------------------------------------------------
943
+ get iconCustomEmojiId() {
944
+ return this.iconCustomEmojiIdValue;
945
+ }
946
+ set iconCustomEmojiId(val) {
947
+ this.setParams({ icon_custom_emoji_id: val });
948
+ }
949
+ get text() {
950
+ return this.textValue;
951
+ }
952
+ set text(val) {
953
+ this.setParams({ text: val });
954
+ }
955
+ get color() {
956
+ return this.colorValue || this.defaultColor();
957
+ }
958
+ set color(val) {
959
+ this.setParams({ color: val });
960
+ }
961
+ get textColor() {
962
+ return this.textColorValue || this.defaultTextColor();
963
+ }
964
+ set textColor(val) {
965
+ this.setParams({ text_color: val });
966
+ }
967
+ get isVisible() {
968
+ return this.isVisibleValue;
969
+ }
970
+ set isVisible(val) {
971
+ this.setParams({ is_visible: val });
972
+ }
973
+ get isProgressVisible() {
974
+ return this.isProgressVisibleValue;
975
+ }
976
+ get isActive() {
977
+ return this.isActiveValue;
978
+ }
979
+ set isActive(val) {
980
+ this.setParams({ is_active: val });
981
+ }
982
+ get hasShineEffect() {
983
+ return this.hasShineEffectValue;
984
+ }
985
+ set hasShineEffect(val) {
986
+ this.setParams({ has_shine_effect: val });
987
+ }
988
+ get position() {
989
+ return this.positionValue;
990
+ }
991
+ set position(val) {
992
+ if (!this.isMain) this.setParams({ position: val });
993
+ }
994
+ // ---------------------------------------------------------------------
995
+ // Wire protocol
996
+ // ---------------------------------------------------------------------
997
+ buttonParams() {
998
+ if (!this.isVisibleValue) {
999
+ return { is_visible: false };
1000
+ }
1001
+ const params = {
1002
+ is_visible: true,
1003
+ is_active: this.isActiveValue,
1004
+ is_progress_visible: this.isProgressVisibleValue,
1005
+ icon_custom_emoji_id: this.iconCustomEmojiIdValue || void 0,
1006
+ text: this.textValue,
1007
+ color: this.color,
1008
+ text_color: this.textColor,
1009
+ has_shine_effect: this.hasShineEffectValue && this.isActiveValue && !this.isProgressVisibleValue
1010
+ };
1011
+ if (!this.isMain) {
1012
+ params.position = this.positionValue;
1013
+ }
1014
+ return params;
1015
+ }
1016
+ updateButton() {
1017
+ const params = this.buttonParams();
1018
+ const state = JSON.stringify(params);
1019
+ if (this.curButtonState === state) {
1020
+ return;
1021
+ }
1022
+ this.curButtonState = state;
1023
+ this.kernel.webView.postEvent(this.setupEventName, void 0, params);
1024
+ if (this.debugBar.enabled) {
1025
+ this.debugBar.updateButtonVisual(this.type, params);
1026
+ }
1027
+ }
1028
+ setParams(params) {
1029
+ if (typeof params.icon_custom_emoji_id !== "undefined") {
1030
+ let emojiId = params.icon_custom_emoji_id;
1031
+ if (emojiId === false || emojiId === null) {
1032
+ emojiId = "";
1033
+ }
1034
+ if (emojiId !== "" && !/^[0-9]{10,20}$/.test(emojiId)) {
1035
+ console.error("[@core-ease/telegram-kit] Bottom button icon custom emoji is invalid", params.icon_custom_emoji_id);
1036
+ throwWebAppError("WebAppBottomButtonParamInvalid" /* BottomButtonParamInvalid */);
1037
+ }
1038
+ this.iconCustomEmojiIdValue = emojiId || false;
1039
+ }
1040
+ if (typeof params.text !== "undefined") {
1041
+ const text = strTrim(params.text);
1042
+ if (!text.length && !this.iconCustomEmojiIdValue) {
1043
+ console.error("[@core-ease/telegram-kit] Bottom button text is required", params.text);
1044
+ throwWebAppError("WebAppBottomButtonParamInvalid" /* BottomButtonParamInvalid */);
1045
+ }
1046
+ if (text.length > 64) {
1047
+ console.error("[@core-ease/telegram-kit] Bottom button text is too long", text);
1048
+ throwWebAppError("WebAppBottomButtonParamInvalid" /* BottomButtonParamInvalid */);
1049
+ }
1050
+ this.textValue = text;
1051
+ }
1052
+ if (typeof params.color !== "undefined") {
1053
+ if (params.color === false || params.color === null) {
1054
+ this.colorValue = false;
1055
+ } else {
1056
+ const color = parseColorToHex(params.color);
1057
+ if (!color) {
1058
+ console.error("[@core-ease/telegram-kit] Bottom button color format is invalid", params.color);
1059
+ throwWebAppError("WebAppBottomButtonParamInvalid" /* BottomButtonParamInvalid */);
1060
+ }
1061
+ this.colorValue = color;
1062
+ }
1063
+ }
1064
+ if (typeof params.text_color !== "undefined") {
1065
+ if (params.text_color === false || params.text_color === null) {
1066
+ this.textColorValue = false;
1067
+ } else {
1068
+ const textColor = parseColorToHex(params.text_color);
1069
+ if (!textColor) {
1070
+ console.error("[@core-ease/telegram-kit] Bottom button text color format is invalid", params.text_color);
1071
+ throwWebAppError("WebAppBottomButtonParamInvalid" /* BottomButtonParamInvalid */);
1072
+ }
1073
+ this.textColorValue = textColor;
1074
+ }
1075
+ }
1076
+ if (typeof params.is_visible !== "undefined") {
1077
+ if (params.is_visible && !this.textValue.length) {
1078
+ console.error("[@core-ease/telegram-kit] Bottom button text is required");
1079
+ throwWebAppError("WebAppBottomButtonParamInvalid" /* BottomButtonParamInvalid */);
1080
+ }
1081
+ this.isVisibleValue = !!params.is_visible;
1082
+ }
1083
+ if (typeof params.has_shine_effect !== "undefined") {
1084
+ this.hasShineEffectValue = !!params.has_shine_effect;
1085
+ }
1086
+ if (!this.isMain && typeof params.position !== "undefined") {
1087
+ if (params.position != "left" && params.position != "right" && params.position != "top" && params.position != "bottom") {
1088
+ console.error("[@core-ease/telegram-kit] Bottom button posiition is invalid", params.position);
1089
+ throwWebAppError("WebAppBottomButtonParamInvalid" /* BottomButtonParamInvalid */);
1090
+ }
1091
+ this.positionValue = params.position;
1092
+ }
1093
+ if (typeof params.is_active !== "undefined") {
1094
+ this.isActiveValue = !!params.is_active;
1095
+ }
1096
+ this.updateButton();
1097
+ return this;
1098
+ }
1099
+ setText(text) {
1100
+ return this.setParams({ text });
1101
+ }
1102
+ onClick(callback) {
1103
+ this.kernel.onWebViewEvent(this.webViewEventName, callback);
1104
+ return this;
1105
+ }
1106
+ offClick(callback) {
1107
+ this.kernel.offWebViewEvent(this.webViewEventName, callback);
1108
+ return this;
1109
+ }
1110
+ show() {
1111
+ return this.setParams({ is_visible: true });
1112
+ }
1113
+ hide() {
1114
+ return this.setParams({ is_visible: false });
1115
+ }
1116
+ enable() {
1117
+ return this.setParams({ is_active: true });
1118
+ }
1119
+ disable() {
1120
+ return this.setParams({ is_active: false });
1121
+ }
1122
+ showProgress(leaveActive) {
1123
+ this.isActiveValue = !!leaveActive;
1124
+ this.isProgressVisibleValue = true;
1125
+ this.updateButton();
1126
+ return this;
1127
+ }
1128
+ hideProgress() {
1129
+ if (!this.isActiveValue) {
1130
+ this.isActiveValue = true;
1131
+ }
1132
+ this.isProgressVisibleValue = false;
1133
+ this.updateButton();
1134
+ return this;
1135
+ }
1136
+ };
1137
+
1138
+ // src/sdk/_internal/ui/settings-button.ts
1139
+ var SettingsButton = class {
1140
+ constructor(kernel) {
1141
+ this.kernel = kernel;
1142
+ this._isVisible = false;
1143
+ this.curButtonState = null;
1144
+ this.handleSettingsButtonPressed = () => {
1145
+ this.kernel.receiveWebViewEvent("settingsButtonClicked");
1146
+ };
1147
+ kernel.webView.onEvent("settings_button_pressed", this.handleSettingsButtonPressed);
1148
+ }
1149
+ get isVisible() {
1150
+ return this._isVisible;
1151
+ }
1152
+ set isVisible(val) {
1153
+ this.setParams({ is_visible: val });
1154
+ }
1155
+ checkVersion() {
1156
+ return this.kernel.warnIfUnsupported("6.10", "SettingsButton");
1157
+ }
1158
+ buttonParams() {
1159
+ return { is_visible: this._isVisible };
1160
+ }
1161
+ updateButton() {
1162
+ const params = this.buttonParams();
1163
+ const state = JSON.stringify(params);
1164
+ if (this.curButtonState === state) {
1165
+ return;
1166
+ }
1167
+ this.curButtonState = state;
1168
+ this.kernel.webView.postEvent("web_app_setup_settings_button", void 0, params);
1169
+ }
1170
+ setParams(params) {
1171
+ if (!this.checkVersion()) {
1172
+ return this;
1173
+ }
1174
+ if (typeof params.is_visible !== "undefined") {
1175
+ this._isVisible = !!params.is_visible;
1176
+ }
1177
+ this.updateButton();
1178
+ return this;
1179
+ }
1180
+ onClick(callback) {
1181
+ if (this.checkVersion()) {
1182
+ this.kernel.onWebViewEvent("settingsButtonClicked", callback);
1183
+ }
1184
+ return this;
1185
+ }
1186
+ offClick(callback) {
1187
+ if (this.checkVersion()) {
1188
+ this.kernel.offWebViewEvent("settingsButtonClicked", callback);
1189
+ }
1190
+ return this;
1191
+ }
1192
+ show() {
1193
+ return this.setParams({ is_visible: true });
1194
+ }
1195
+ hide() {
1196
+ return this.setParams({ is_visible: false });
1197
+ }
1198
+ };
1199
+
1200
+ // src/sdk/_internal/ui/debug-bottom-bar.ts
1201
+ var SPINNER_SVG = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewport="0 0 48 48" width="48px" height="48px"><circle cx="50%" cy="50%" stroke="{COLOR}" stroke-width="2.25" stroke-linecap="round" fill="none" stroke-dashoffset="106" r="9" stroke-dasharray="56.52" rotate="-90"><animate attributeName="stroke-dashoffset" attributeType="XML" dur="360s" from="0" to="12500" repeatCount="indefinite"></animate><animateTransform attributeName="transform" attributeType="XML" type="rotate" dur="1s" from="-90 24 24" to="630 24 24" repeatCount="indefinite"></animateTransform></circle></svg>';
1202
+ var DebugBottomBar = class {
1203
+ constructor(kernel, getBottomBarColor) {
1204
+ this.kernel = kernel;
1205
+ this.getBottomBarColor = getBottomBarColor;
1206
+ this.container = null;
1207
+ this.buttons = {};
1208
+ /** Invoked whenever the reserved bottom-bar height changes. */
1209
+ this.onHeightChanged = null;
1210
+ this.enabled = !!kernel.initParams.tgWebAppDebug;
1211
+ if (!this.enabled) return;
1212
+ this.container = document.createElement("tg-bottom-bar");
1213
+ const style = {
1214
+ display: "flex",
1215
+ gap: "7px",
1216
+ font: "600 14px/18px sans-serif",
1217
+ width: "100%",
1218
+ background: getBottomBarColor(),
1219
+ position: "fixed",
1220
+ left: "0",
1221
+ right: "0",
1222
+ bottom: "0",
1223
+ margin: "0",
1224
+ padding: "7px",
1225
+ textAlign: "center",
1226
+ boxSizing: "border-box",
1227
+ zIndex: "10000"
1228
+ };
1229
+ Object.assign(this.container.style, style);
1230
+ document.addEventListener("DOMContentLoaded", function onDomLoaded() {
1231
+ document.removeEventListener("DOMContentLoaded", onDomLoaded);
1232
+ document.body.appendChild(this_container());
1233
+ });
1234
+ const this_container = () => this.container;
1235
+ const animStyle = document.createElement("style");
1236
+ animStyle.innerHTML = 'tg-bottom-button.shine { position: relative; overflow: hidden; } tg-bottom-button.shine:before { content:""; position: absolute; top: 0; width: 100%; height: 100%; background: linear-gradient(120deg, transparent, rgba(255, 255, 255, .2), transparent); animation: tg-bottom-button-shine 5s ease-in-out infinite; } @-webkit-keyframes tg-bottom-button-shine { 0% {left: -100%;} 12%,100% {left: 100%}} @keyframes tg-bottom-button-shine { 0% {left: -100%;} 12%,100% {left: 100%}}';
1237
+ this.container.appendChild(animStyle);
1238
+ }
1239
+ /** Creates & registers a debug clone of a Main/Secondary button; returns its element. */
1240
+ registerButton(type, onPressed) {
1241
+ if (!this.enabled || !this.container) return null;
1242
+ const el = document.createElement("tg-bottom-button");
1243
+ const style = {
1244
+ display: "none",
1245
+ width: "100%",
1246
+ height: "44px",
1247
+ borderRadius: "0",
1248
+ background: "no-repeat right center",
1249
+ padding: "13px 15px",
1250
+ textAlign: "center",
1251
+ boxSizing: "border-box"
1252
+ };
1253
+ Object.assign(el.style, style);
1254
+ this.container.appendChild(el);
1255
+ el.addEventListener("click", onPressed, false);
1256
+ this.buttons[type] = { el, isVisible: false, position: "left" };
1257
+ return el;
1258
+ }
1259
+ /** Applies visual state coming from `BottomButton.buttonParams()`. */
1260
+ updateButtonVisual(type, params) {
1261
+ const entry = this.buttons[type];
1262
+ if (!entry) return;
1263
+ const el = entry.el;
1264
+ entry.isVisible = !!params.is_visible;
1265
+ entry.position = params.position || "left";
1266
+ if (params.is_visible) {
1267
+ el.style.display = "block";
1268
+ el.style.opacity = params.is_active ? "1" : "0.8";
1269
+ el.style.cursor = params.is_active ? "pointer" : "auto";
1270
+ el.disabled = !params.is_active;
1271
+ el.innerText = params.text || "";
1272
+ el.className = params.has_shine_effect ? "shine" : "";
1273
+ el.style.backgroundImage = params.is_progress_visible ? `url('data:image/svg+xml,${encodeURIComponent(
1274
+ SPINNER_SVG.replace("{COLOR}", params.text_color || "#ffffff")
1275
+ )}')` : "none";
1276
+ el.style.backgroundColor = params.color || "";
1277
+ el.style.color = params.text_color || "";
1278
+ } else {
1279
+ el.style.display = "none";
1280
+ }
1281
+ this.updateBar();
1282
+ }
1283
+ updateBar() {
1284
+ var _a;
1285
+ if (!this.enabled || !this.container) return;
1286
+ const main = this.buttons.main;
1287
+ const secondary = this.buttons.secondary;
1288
+ let height = 0;
1289
+ if (main && main.isVisible || secondary && secondary.isVisible) {
1290
+ this.container.style.display = "flex";
1291
+ height = 58;
1292
+ if ((main == null ? void 0 : main.isVisible) && (secondary == null ? void 0 : secondary.isVisible)) {
1293
+ if (secondary.position == "top") {
1294
+ this.container.style.flexDirection = "column-reverse";
1295
+ height += 51;
1296
+ } else if (secondary.position == "bottom") {
1297
+ this.container.style.flexDirection = "column";
1298
+ height += 51;
1299
+ } else if (secondary.position == "left") {
1300
+ this.container.style.flexDirection = "row-reverse";
1301
+ } else if (secondary.position == "right") {
1302
+ this.container.style.flexDirection = "row";
1303
+ }
1304
+ }
1305
+ } else {
1306
+ this.container.style.display = "none";
1307
+ height = 0;
1308
+ }
1309
+ this.kernel.bottomBarHeightPx = height;
1310
+ this.container.style.background = this.getBottomBarColor();
1311
+ if (document.documentElement) {
1312
+ document.documentElement.style.boxSizing = "border-box";
1313
+ document.documentElement.style.paddingBottom = height + "px";
1314
+ }
1315
+ (_a = this.onHeightChanged) == null ? void 0 : _a.call(this);
1316
+ }
1317
+ /** Called after the bottom-bar color changes so the debug bar repaints too. */
1318
+ refreshColor() {
1319
+ if (!this.enabled || !this.container) return;
1320
+ this.updateBar();
1321
+ }
1322
+ };
1323
+
1324
+ // src/sdk/_internal/ui/popup.ts
1325
+ var PopupManager = class {
1326
+ constructor(kernel) {
1327
+ this.kernel = kernel;
1328
+ this.pending = false;
1329
+ this.handlePopupClosed = (_eventType, eventData) => {
1330
+ var _a;
1331
+ if (this.pending) {
1332
+ const popupData = this.pending;
1333
+ this.pending = false;
1334
+ const buttonId = typeof eventData.button_id !== "undefined" ? eventData.button_id : null;
1335
+ (_a = popupData.callback) == null ? void 0 : _a.call(popupData, buttonId);
1336
+ this.kernel.receiveWebViewEvent("popupClosed", { button_id: buttonId });
1337
+ }
1338
+ };
1339
+ kernel.webView.onEvent("popup_closed", this.handlePopupClosed);
1340
+ }
1341
+ showPopup(params, callback) {
1342
+ this.kernel.requireVersion("6.2", "showPopup");
1343
+ if (this.pending) {
1344
+ console.error("[@core-ease/telegram-kit] Popup is already opened");
1345
+ throwWebAppError("WebAppPopupOpened" /* PopupOpened */);
1346
+ }
1347
+ const popupParams = { message: "" };
1348
+ if (typeof params.title !== "undefined") {
1349
+ const title = strTrim(params.title);
1350
+ if (title.length > 64) {
1351
+ console.error("[@core-ease/telegram-kit] Popup title is too long", title);
1352
+ throwWebAppError("WebAppPopupParamInvalid" /* PopupParamInvalid */);
1353
+ }
1354
+ if (title.length > 0) {
1355
+ popupParams.title = title;
1356
+ }
1357
+ }
1358
+ let message = "";
1359
+ if (typeof params.message !== "undefined") {
1360
+ message = strTrim(params.message);
1361
+ }
1362
+ if (!message.length) {
1363
+ console.error("[@core-ease/telegram-kit] Popup message is required", params.message);
1364
+ throwWebAppError("WebAppPopupParamInvalid" /* PopupParamInvalid */);
1365
+ }
1366
+ if (message.length > 256) {
1367
+ console.error("[@core-ease/telegram-kit] Popup message is too long", message);
1368
+ throwWebAppError("WebAppPopupParamInvalid" /* PopupParamInvalid */);
1369
+ }
1370
+ popupParams.message = message;
1371
+ const buttons = [];
1372
+ if (typeof params.buttons !== "undefined") {
1373
+ if (!Array.isArray(params.buttons)) {
1374
+ console.error("[@core-ease/telegram-kit] Popup buttons should be an array", params.buttons);
1375
+ throwWebAppError("WebAppPopupParamInvalid" /* PopupParamInvalid */);
1376
+ }
1377
+ for (const button of params.buttons) {
1378
+ const btn = {};
1379
+ let id = "";
1380
+ if (typeof button.id !== "undefined") {
1381
+ id = String(button.id);
1382
+ if (id.length > 64) {
1383
+ console.error("[@core-ease/telegram-kit] Popup button id is too long", id);
1384
+ throwWebAppError("WebAppPopupParamInvalid" /* PopupParamInvalid */);
1385
+ }
1386
+ }
1387
+ btn.id = id;
1388
+ const buttonType = button.type || "default";
1389
+ btn.type = buttonType;
1390
+ if (buttonType == "ok" || buttonType == "close" || buttonType == "cancel") ; else if (buttonType == "default" || buttonType == "destructive") {
1391
+ let text = "";
1392
+ if (typeof button.text !== "undefined") {
1393
+ text = strTrim(button.text);
1394
+ }
1395
+ if (!text.length) {
1396
+ console.error(`[@core-ease/telegram-kit] Popup button text is required for type ${buttonType}`, button.text);
1397
+ throwWebAppError("WebAppPopupParamInvalid" /* PopupParamInvalid */);
1398
+ }
1399
+ if (text.length > 64) {
1400
+ console.error("[@core-ease/telegram-kit] Popup button text is too long", text);
1401
+ throwWebAppError("WebAppPopupParamInvalid" /* PopupParamInvalid */);
1402
+ }
1403
+ btn.text = text;
1404
+ } else {
1405
+ console.error("[@core-ease/telegram-kit] Popup button type is invalid", buttonType);
1406
+ throwWebAppError("WebAppPopupParamInvalid" /* PopupParamInvalid */);
1407
+ }
1408
+ buttons.push(btn);
1409
+ }
1410
+ } else {
1411
+ buttons.push({ id: "", type: "close" });
1412
+ }
1413
+ if (buttons.length < 1) {
1414
+ console.error("[@core-ease/telegram-kit] Popup should have at least one button");
1415
+ throwWebAppError("WebAppPopupParamInvalid" /* PopupParamInvalid */);
1416
+ }
1417
+ if (buttons.length > 3) {
1418
+ console.error("[@core-ease/telegram-kit] Popup should not have more than 3 buttons");
1419
+ throwWebAppError("WebAppPopupParamInvalid" /* PopupParamInvalid */);
1420
+ }
1421
+ popupParams.buttons = buttons;
1422
+ this.pending = { callback };
1423
+ this.kernel.webView.postEvent("web_app_open_popup", void 0, popupParams);
1424
+ }
1425
+ showAlert(message, callback) {
1426
+ this.showPopup({ message }, callback ? () => callback() : void 0);
1427
+ }
1428
+ showConfirm(message, callback) {
1429
+ this.showPopup(
1430
+ {
1431
+ message,
1432
+ buttons: [
1433
+ { type: "ok", id: "ok" },
1434
+ { type: "cancel" }
1435
+ ]
1436
+ },
1437
+ callback ? (buttonId) => callback(buttonId == "ok") : void 0
1438
+ );
1439
+ }
1440
+ };
1441
+
1442
+ // src/sdk/_internal/ui/scan-qr.ts
1443
+ var ScanQrManager = class {
1444
+ constructor(kernel) {
1445
+ this.kernel = kernel;
1446
+ this.pending = false;
1447
+ this.handleQrTextReceived = (_eventType, eventData) => {
1448
+ if (this.pending) {
1449
+ const popupData = this.pending;
1450
+ const data = typeof eventData.data !== "undefined" ? eventData.data : null;
1451
+ if (popupData.callback) {
1452
+ if (popupData.callback(data)) {
1453
+ this.pending = false;
1454
+ this.kernel.webView.postEvent("web_app_close_scan_qr_popup", void 0);
1455
+ }
1456
+ }
1457
+ this.kernel.receiveWebViewEvent("qrTextReceived", { data });
1458
+ }
1459
+ };
1460
+ this.handleScanQrPopupClosed = () => {
1461
+ this.pending = false;
1462
+ this.kernel.receiveWebViewEvent("scanQrPopupClosed");
1463
+ };
1464
+ kernel.webView.onEvent("qr_text_received", this.handleQrTextReceived);
1465
+ kernel.webView.onEvent("scan_qr_popup_closed", this.handleScanQrPopupClosed);
1466
+ }
1467
+ showScanQrPopup(params, callback) {
1468
+ this.kernel.requireVersion("6.4", "showScanQrPopup");
1469
+ if (this.pending) {
1470
+ console.error("[@core-ease/telegram-kit] Popup is already opened");
1471
+ throwWebAppError("WebAppScanQrPopupOpened" /* ScanQrPopupOpened */);
1472
+ }
1473
+ const popupParams = {};
1474
+ if (typeof params.text !== "undefined") {
1475
+ const text = strTrim(params.text);
1476
+ if (text.length > 64) {
1477
+ console.error("[@core-ease/telegram-kit] Scan QR popup text is too long", text);
1478
+ throwWebAppError("WebAppScanQrPopupParamInvalid" /* ScanQrPopupParamInvalid */);
1479
+ }
1480
+ if (text.length > 0) {
1481
+ popupParams.text = text;
1482
+ }
1483
+ }
1484
+ this.pending = { callback };
1485
+ this.kernel.webView.postEvent("web_app_open_scan_qr_popup", void 0, popupParams);
1486
+ }
1487
+ closeScanQrPopup() {
1488
+ this.kernel.requireVersion("6.4", "closeScanQrPopup");
1489
+ this.pending = false;
1490
+ this.kernel.webView.postEvent("web_app_close_scan_qr_popup", void 0);
1491
+ }
1492
+ };
1493
+
1494
+ // src/sdk/_internal/features/haptic-feedback.ts
1495
+ var HapticFeedback = class {
1496
+ constructor(kernel) {
1497
+ this.kernel = kernel;
1498
+ }
1499
+ trigger(params) {
1500
+ if (!this.kernel.warnIfUnsupported("6.1", "HapticFeedback")) {
1501
+ return this;
1502
+ }
1503
+ if (params.type == "impact") {
1504
+ if (params.impact_style != "light" && params.impact_style != "medium" && params.impact_style != "heavy" && params.impact_style != "rigid" && params.impact_style != "soft") {
1505
+ console.error("[@core-ease/telegram-kit] Haptic impact style is invalid", params.impact_style);
1506
+ throwWebAppError("WebAppHapticImpactStyleInvalid" /* HapticImpactStyleInvalid */);
1507
+ }
1508
+ } else if (params.type == "notification") {
1509
+ if (params.notification_type != "error" && params.notification_type != "success" && params.notification_type != "warning") {
1510
+ console.error("[@core-ease/telegram-kit] Haptic notification type is invalid", params.notification_type);
1511
+ throwWebAppError("WebAppHapticNotificationTypeInvalid" /* HapticNotificationTypeInvalid */);
1512
+ }
1513
+ } else if (params.type == "selection_change") ; else {
1514
+ console.error("[@core-ease/telegram-kit] Haptic feedback type is invalid", params.type);
1515
+ throwWebAppError("WebAppHapticFeedbackTypeInvalid" /* HapticFeedbackTypeInvalid */);
1516
+ }
1517
+ this.kernel.webView.postEvent("web_app_trigger_haptic_feedback", void 0, params);
1518
+ return this;
1519
+ }
1520
+ impactOccurred(style) {
1521
+ return this.trigger({ type: "impact", impact_style: style });
1522
+ }
1523
+ notificationOccurred(type) {
1524
+ return this.trigger({ type: "notification", notification_type: type });
1525
+ }
1526
+ selectionChanged() {
1527
+ return this.trigger({ type: "selection_change" });
1528
+ }
1529
+ };
1530
+
1531
+ // src/sdk/_internal/features/cloud-storage.ts
1532
+ var CloudStorage = class {
1533
+ constructor(kernel) {
1534
+ this.kernel = kernel;
1535
+ }
1536
+ invoke(method, params, callback) {
1537
+ this.kernel.requireVersion("6.9", "CloudStorage");
1538
+ this.kernel.invokeCustomMethod(method, params, callback);
1539
+ return this;
1540
+ }
1541
+ setItem(key, value, callback) {
1542
+ return this.invoke("saveStorageValue", { key, value }, callback);
1543
+ }
1544
+ getItem(key, callback) {
1545
+ return this.getItems(
1546
+ [key],
1547
+ callback ? (err, res) => err ? callback(err) : callback(null, res == null ? void 0 : res[key]) : void 0
1548
+ );
1549
+ }
1550
+ getItems(keys, callback) {
1551
+ return this.invoke("getStorageValues", { keys }, callback);
1552
+ }
1553
+ removeItem(key, callback) {
1554
+ return this.removeItems([key], callback);
1555
+ }
1556
+ removeItems(keys, callback) {
1557
+ return this.invoke("deleteStorageValues", { keys }, callback);
1558
+ }
1559
+ getKeys(callback) {
1560
+ return this.invoke("getStorageKeys", {}, callback);
1561
+ }
1562
+ };
1563
+
1564
+ // src/sdk/_internal/features/device-storage.ts
1565
+ var DeviceStorage = class {
1566
+ constructor(kernel) {
1567
+ this.kernel = kernel;
1568
+ this.handleEvent = (eventType, eventData) => {
1569
+ var _a;
1570
+ if (!eventData.req_id || !this.kernel.hasCallback(eventData.req_id)) return;
1571
+ const entry = this.kernel.takeCallback(eventData.req_id);
1572
+ let res = null;
1573
+ let err = null;
1574
+ if (eventType == "device_storage_failed") {
1575
+ err = eventData.error || "UNKNOWN_ERROR";
1576
+ } else if (eventType == "device_storage_key_received") {
1577
+ res = eventData.value;
1578
+ } else {
1579
+ res = true;
1580
+ }
1581
+ (_a = entry == null ? void 0 : entry.callback) == null ? void 0 : _a.call(entry, err, res);
1582
+ };
1583
+ kernel.webView.onEvent("device_storage_key_saved", this.handleEvent);
1584
+ kernel.webView.onEvent("device_storage_key_received", this.handleEvent);
1585
+ kernel.webView.onEvent("device_storage_cleared", this.handleEvent);
1586
+ kernel.webView.onEvent("device_storage_failed", this.handleEvent);
1587
+ }
1588
+ invoke(method, params, callback) {
1589
+ this.kernel.requireVersion("9.0", "DeviceStorage");
1590
+ const reqId = this.kernel.registerCallback(callback);
1591
+ this.kernel.webView.postEvent(method, void 0, __spreadValues({ req_id: reqId }, params));
1592
+ return this;
1593
+ }
1594
+ setItem(key, value, callback) {
1595
+ return this.invoke("web_app_device_storage_save_key", { key, value }, callback);
1596
+ }
1597
+ getItem(key, callback) {
1598
+ return this.invoke("web_app_device_storage_get_key", { key }, callback);
1599
+ }
1600
+ removeItem(key, callback) {
1601
+ return this.invoke("web_app_device_storage_save_key", { key, value: null }, callback);
1602
+ }
1603
+ clear(callback) {
1604
+ return this.invoke("web_app_device_storage_clear", {}, callback);
1605
+ }
1606
+ };
1607
+
1608
+ // src/sdk/_internal/features/secure-storage.ts
1609
+ var SecureStorage = class {
1610
+ constructor(kernel) {
1611
+ this.kernel = kernel;
1612
+ this.handleEvent = (eventType, eventData) => {
1613
+ var _a;
1614
+ if (!eventData.req_id || !this.kernel.hasCallback(eventData.req_id)) return;
1615
+ const entry = this.kernel.takeCallback(eventData.req_id);
1616
+ let res = null;
1617
+ let err = null;
1618
+ let canRestore = null;
1619
+ if (eventType == "secure_storage_failed") {
1620
+ err = eventData.error || "UNKNOWN_ERROR";
1621
+ } else if (eventType == "secure_storage_key_received") {
1622
+ res = eventData.value;
1623
+ if (eventData.can_restore) {
1624
+ canRestore = true;
1625
+ }
1626
+ } else if (eventType == "secure_storage_key_restored") {
1627
+ res = eventData.value;
1628
+ } else {
1629
+ res = true;
1630
+ }
1631
+ (_a = entry == null ? void 0 : entry.callback) == null ? void 0 : _a.call(entry, err, res, canRestore);
1632
+ };
1633
+ kernel.webView.onEvent("secure_storage_key_saved", this.handleEvent);
1634
+ kernel.webView.onEvent("secure_storage_key_received", this.handleEvent);
1635
+ kernel.webView.onEvent("secure_storage_key_restored", this.handleEvent);
1636
+ kernel.webView.onEvent("secure_storage_cleared", this.handleEvent);
1637
+ kernel.webView.onEvent("secure_storage_failed", this.handleEvent);
1638
+ }
1639
+ invoke(method, params, callback) {
1640
+ this.kernel.requireVersion("9.0", "SecureStorage");
1641
+ const reqId = this.kernel.registerCallback(callback);
1642
+ this.kernel.webView.postEvent(method, void 0, __spreadValues({ req_id: reqId }, params));
1643
+ return this;
1644
+ }
1645
+ setItem(key, value, callback) {
1646
+ return this.invoke("web_app_secure_storage_save_key", { key, value }, callback);
1647
+ }
1648
+ getItem(key, callback) {
1649
+ return this.invoke("web_app_secure_storage_get_key", { key }, callback);
1650
+ }
1651
+ restoreItem(key, callback) {
1652
+ return this.invoke("web_app_secure_storage_restore_key", { key }, callback);
1653
+ }
1654
+ removeItem(key, callback) {
1655
+ return this.invoke("web_app_secure_storage_save_key", { key, value: null }, callback);
1656
+ }
1657
+ clear(callback) {
1658
+ return this.invoke("web_app_secure_storage_clear", {}, callback);
1659
+ }
1660
+ };
1661
+
1662
+ // src/sdk/_internal/features/biometric-manager.ts
1663
+ var BiometricManager = class {
1664
+ constructor(kernel) {
1665
+ this.kernel = kernel;
1666
+ this._isInited = false;
1667
+ this._isBiometricAvailable = false;
1668
+ this._biometricType = "unknown";
1669
+ this._isAccessRequested = false;
1670
+ this._isAccessGranted = false;
1671
+ this._isBiometricTokenSaved = false;
1672
+ this._deviceId = "";
1673
+ this.initCallbacks = [];
1674
+ this.accessRequestState = false;
1675
+ this.authRequestState = false;
1676
+ this.tokenRequestState = false;
1677
+ this.handleInfoReceived = (_eventType, eventData) => {
1678
+ var _a;
1679
+ this._isInited = true;
1680
+ if (eventData.available) {
1681
+ this._isBiometricAvailable = true;
1682
+ this._biometricType = eventData.type || "unknown";
1683
+ if (eventData.access_requested) {
1684
+ this._isAccessRequested = true;
1685
+ this._isAccessGranted = !!eventData.access_granted;
1686
+ this._isBiometricTokenSaved = !!eventData.token_saved;
1687
+ } else {
1688
+ this._isAccessRequested = false;
1689
+ this._isAccessGranted = false;
1690
+ this._isBiometricTokenSaved = false;
1691
+ }
1692
+ } else {
1693
+ this._isBiometricAvailable = false;
1694
+ this._biometricType = "unknown";
1695
+ this._isAccessRequested = false;
1696
+ this._isAccessGranted = false;
1697
+ this._isBiometricTokenSaved = false;
1698
+ }
1699
+ this._deviceId = eventData.device_id || "";
1700
+ if (this.initCallbacks.length > 0) {
1701
+ this.initCallbacks.forEach((cb) => cb());
1702
+ this.initCallbacks = [];
1703
+ }
1704
+ if (this.accessRequestState) {
1705
+ const state = this.accessRequestState;
1706
+ this.accessRequestState = false;
1707
+ (_a = state.callback) == null ? void 0 : _a.call(state, this._isAccessGranted);
1708
+ }
1709
+ this.kernel.receiveWebViewEvent("biometricManagerUpdated");
1710
+ };
1711
+ this.handleAuthRequested = (_eventType, eventData) => {
1712
+ var _a;
1713
+ const isAuthenticated = eventData.status == "authorized";
1714
+ const biometricToken = eventData.token || "";
1715
+ if (this.authRequestState) {
1716
+ const state = this.authRequestState;
1717
+ this.authRequestState = false;
1718
+ (_a = state.callback) == null ? void 0 : _a.call(state, isAuthenticated, isAuthenticated ? biometricToken : null);
1719
+ }
1720
+ this.kernel.receiveWebViewEvent(
1721
+ "biometricAuthRequested",
1722
+ isAuthenticated ? { isAuthenticated: true, biometricToken } : { isAuthenticated: false }
1723
+ );
1724
+ };
1725
+ this.handleTokenUpdated = (_eventType, eventData) => {
1726
+ var _a;
1727
+ let applied = false;
1728
+ if (this._isBiometricAvailable && this._isAccessRequested) {
1729
+ if (eventData.status == "updated") {
1730
+ this._isBiometricTokenSaved = true;
1731
+ applied = true;
1732
+ } else if (eventData.status == "removed") {
1733
+ this._isBiometricTokenSaved = false;
1734
+ applied = true;
1735
+ }
1736
+ }
1737
+ if (this.tokenRequestState) {
1738
+ const state = this.tokenRequestState;
1739
+ this.tokenRequestState = false;
1740
+ (_a = state.callback) == null ? void 0 : _a.call(state, applied);
1741
+ }
1742
+ this.kernel.receiveWebViewEvent("biometricTokenUpdated", { isUpdated: applied });
1743
+ };
1744
+ kernel.webView.onEvent("biometry_info_received", this.handleInfoReceived);
1745
+ kernel.webView.onEvent("biometry_auth_requested", this.handleAuthRequested);
1746
+ kernel.webView.onEvent("biometry_token_updated", this.handleTokenUpdated);
1747
+ }
1748
+ get isInited() {
1749
+ return this._isInited;
1750
+ }
1751
+ get isBiometricAvailable() {
1752
+ return this._isInited && this._isBiometricAvailable;
1753
+ }
1754
+ get biometricType() {
1755
+ return this._biometricType || "unknown";
1756
+ }
1757
+ get isAccessRequested() {
1758
+ return this._isAccessRequested;
1759
+ }
1760
+ get isAccessGranted() {
1761
+ return this._isAccessRequested && this._isAccessGranted;
1762
+ }
1763
+ get isBiometricTokenSaved() {
1764
+ return this._isBiometricTokenSaved;
1765
+ }
1766
+ get deviceId() {
1767
+ return this._deviceId || "";
1768
+ }
1769
+ checkVersion() {
1770
+ return this.kernel.warnIfUnsupported("7.2", "BiometricManager");
1771
+ }
1772
+ checkInit() {
1773
+ if (!this._isInited) {
1774
+ console.error("[@core-ease/telegram-kit] BiometricManager should be inited before using.");
1775
+ throwWebAppError("WebAppBiometricManagerNotInited" /* BiometricManagerNotInited */);
1776
+ }
1777
+ return true;
1778
+ }
1779
+ init(callback) {
1780
+ if (!this.checkVersion()) return this;
1781
+ if (this._isInited) return this;
1782
+ if (callback) this.initCallbacks.push(callback);
1783
+ this.kernel.webView.postEvent("web_app_biometry_get_info");
1784
+ return this;
1785
+ }
1786
+ requestAccess(params, callback) {
1787
+ if (!this.checkVersion()) return this;
1788
+ this.checkInit();
1789
+ if (!this._isBiometricAvailable) {
1790
+ console.error("[@core-ease/telegram-kit] Biometrics is not available on this device.");
1791
+ throwWebAppError("WebAppBiometricManagerBiometricsNotAvailable" /* BiometricManagerBiometricsNotAvailable */);
1792
+ }
1793
+ if (this.accessRequestState) {
1794
+ console.error("[@core-ease/telegram-kit] Access is already requested");
1795
+ throwWebAppError("WebAppBiometricManagerAccessRequested" /* BiometricManagerAccessRequested */);
1796
+ }
1797
+ const popupParams = {};
1798
+ if (typeof params.reason !== "undefined") {
1799
+ const reason = strTrim(params.reason);
1800
+ if (reason.length > 128) {
1801
+ console.error("[@core-ease/telegram-kit] Biometric reason is too long", reason);
1802
+ throwWebAppError("WebAppBiometricRequestAccessParamInvalid" /* BiometricRequestAccessParamInvalid */);
1803
+ }
1804
+ if (reason.length > 0) popupParams.reason = reason;
1805
+ }
1806
+ this.accessRequestState = { callback };
1807
+ this.kernel.webView.postEvent("web_app_biometry_request_access", void 0, popupParams);
1808
+ return this;
1809
+ }
1810
+ authenticate(params, callback) {
1811
+ if (!this.checkVersion()) return this;
1812
+ this.checkInit();
1813
+ if (!this._isBiometricAvailable) {
1814
+ console.error("[@core-ease/telegram-kit] Biometrics is not available on this device.");
1815
+ throwWebAppError("WebAppBiometricManagerBiometricsNotAvailable" /* BiometricManagerBiometricsNotAvailable */);
1816
+ }
1817
+ if (!this.isAccessGranted) {
1818
+ console.error("[@core-ease/telegram-kit] Biometric access was not granted by the user.");
1819
+ throwWebAppError("WebAppBiometricManagerBiometricAccessNotGranted" /* BiometricManagerBiometricAccessNotGranted */);
1820
+ }
1821
+ if (this.authRequestState) {
1822
+ console.error("[@core-ease/telegram-kit] Authentication request is already in progress.");
1823
+ throwWebAppError("WebAppBiometricManagerAuthenticationRequested" /* BiometricManagerAuthenticationRequested */);
1824
+ }
1825
+ const popupParams = {};
1826
+ if (typeof params.reason !== "undefined") {
1827
+ const reason = strTrim(params.reason);
1828
+ if (reason.length > 128) {
1829
+ console.error("[@core-ease/telegram-kit] Biometric reason is too long", reason);
1830
+ throwWebAppError("WebAppBiometricRequestAccessParamInvalid" /* BiometricRequestAccessParamInvalid */);
1831
+ }
1832
+ if (reason.length > 0) popupParams.reason = reason;
1833
+ }
1834
+ this.authRequestState = { callback };
1835
+ this.kernel.webView.postEvent("web_app_biometry_request_auth", void 0, popupParams);
1836
+ return this;
1837
+ }
1838
+ updateBiometricToken(token, callback) {
1839
+ if (!this.checkVersion()) return this;
1840
+ token = token || "";
1841
+ if (token.length > 1024) {
1842
+ console.error("[@core-ease/telegram-kit] Token is too long", token);
1843
+ throwWebAppError("WebAppBiometricManagerTokenInvalid" /* BiometricManagerTokenInvalid */);
1844
+ }
1845
+ this.checkInit();
1846
+ if (!this._isBiometricAvailable) {
1847
+ console.error("[@core-ease/telegram-kit] Biometrics is not available on this device.");
1848
+ throwWebAppError("WebAppBiometricManagerBiometricsNotAvailable" /* BiometricManagerBiometricsNotAvailable */);
1849
+ }
1850
+ if (!this.isAccessGranted) {
1851
+ console.error("[@core-ease/telegram-kit] Biometric access was not granted by the user.");
1852
+ throwWebAppError("WebAppBiometricManagerBiometricAccessNotGranted" /* BiometricManagerBiometricAccessNotGranted */);
1853
+ }
1854
+ if (this.tokenRequestState) {
1855
+ console.error("[@core-ease/telegram-kit] Token request is already in progress.");
1856
+ throwWebAppError("WebAppBiometricManagerTokenUpdateRequested" /* BiometricManagerTokenUpdateRequested */);
1857
+ }
1858
+ this.tokenRequestState = { callback };
1859
+ this.kernel.webView.postEvent("web_app_biometry_update_token", void 0, { token });
1860
+ return this;
1861
+ }
1862
+ openSettings() {
1863
+ if (!this.checkVersion()) return this;
1864
+ this.checkInit();
1865
+ if (!this._isBiometricAvailable) {
1866
+ console.error("[@core-ease/telegram-kit] Biometrics is not available on this device.");
1867
+ throwWebAppError("WebAppBiometricManagerBiometricsNotAvailable" /* BiometricManagerBiometricsNotAvailable */);
1868
+ }
1869
+ if (!this._isAccessRequested) {
1870
+ console.error("[@core-ease/telegram-kit] Biometric access was not requested yet.");
1871
+ throwWebAppError("WebAppBiometricManagerBiometricsAccessNotRequested" /* BiometricManagerBiometricsAccessNotRequested */);
1872
+ }
1873
+ if (this._isAccessGranted) {
1874
+ console.warn("[@core-ease/telegram-kit] Biometric access was granted by the user, no need to go to settings.");
1875
+ return this;
1876
+ }
1877
+ this.kernel.webView.postEvent("web_app_biometry_open_settings");
1878
+ return this;
1879
+ }
1880
+ };
1881
+
1882
+ // src/sdk/_internal/features/location-manager.ts
1883
+ var LocationManager = class {
1884
+ constructor(kernel) {
1885
+ this.kernel = kernel;
1886
+ this._isInited = false;
1887
+ this._isLocationAvailable = false;
1888
+ this._isAccessRequested = false;
1889
+ this._isAccessGranted = false;
1890
+ this.initCallbacks = [];
1891
+ this.getRequestCallbacks = [];
1892
+ this.handleLocationChecked = (_eventType, eventData) => {
1893
+ this._isInited = true;
1894
+ if (eventData.available) {
1895
+ this._isLocationAvailable = true;
1896
+ if (eventData.access_requested) {
1897
+ this._isAccessRequested = true;
1898
+ this._isAccessGranted = !!eventData.access_granted;
1899
+ } else {
1900
+ this._isAccessRequested = false;
1901
+ this._isAccessGranted = false;
1902
+ }
1903
+ } else {
1904
+ this._isLocationAvailable = false;
1905
+ this._isAccessRequested = false;
1906
+ this._isAccessGranted = false;
1907
+ }
1908
+ if (this.initCallbacks.length > 0) {
1909
+ this.initCallbacks.forEach((cb) => cb());
1910
+ this.initCallbacks = [];
1911
+ }
1912
+ this.kernel.receiveWebViewEvent("locationManagerUpdated");
1913
+ };
1914
+ this.handleLocationRequested = (_eventType, eventData) => {
1915
+ let locationData = null;
1916
+ if (eventData.available) {
1917
+ locationData = {
1918
+ latitude: eventData.latitude,
1919
+ longitude: eventData.longitude,
1920
+ altitude: null,
1921
+ course: null,
1922
+ speed: null,
1923
+ horizontal_accuracy: null,
1924
+ vertical_accuracy: null,
1925
+ course_accuracy: null,
1926
+ speed_accuracy: null
1927
+ };
1928
+ if (typeof eventData.altitude !== "undefined" && eventData.altitude !== null) {
1929
+ locationData.altitude = eventData.altitude;
1930
+ }
1931
+ if (typeof eventData.course !== "undefined" && eventData.course !== null) {
1932
+ locationData.course = eventData.course % 360;
1933
+ }
1934
+ if (typeof eventData.speed !== "undefined" && eventData.speed !== null) {
1935
+ locationData.speed = eventData.speed;
1936
+ }
1937
+ if (typeof eventData.horizontal_accuracy !== "undefined" && eventData.horizontal_accuracy !== null) {
1938
+ locationData.horizontal_accuracy = eventData.horizontal_accuracy;
1939
+ }
1940
+ if (typeof eventData.vertical_accuracy !== "undefined" && eventData.vertical_accuracy !== null) {
1941
+ locationData.vertical_accuracy = eventData.vertical_accuracy;
1942
+ }
1943
+ if (typeof eventData.course_accuracy !== "undefined" && eventData.course_accuracy !== null) {
1944
+ locationData.course_accuracy = eventData.course_accuracy;
1945
+ }
1946
+ if (typeof eventData.speed_accuracy !== "undefined" && eventData.speed_accuracy !== null) {
1947
+ locationData.speed_accuracy = eventData.speed_accuracy;
1948
+ }
1949
+ }
1950
+ if (!eventData.available || !this._isLocationAvailable || !this._isAccessRequested || !this._isAccessGranted) {
1951
+ this.initCallbacks.push(() => this.locationResponse(locationData));
1952
+ this.kernel.webView.postEvent("web_app_check_location");
1953
+ } else {
1954
+ this.locationResponse(locationData);
1955
+ }
1956
+ };
1957
+ kernel.webView.onEvent("location_checked", this.handleLocationChecked);
1958
+ kernel.webView.onEvent("location_requested", this.handleLocationRequested);
1959
+ }
1960
+ get isInited() {
1961
+ return this._isInited;
1962
+ }
1963
+ get isLocationAvailable() {
1964
+ return this._isInited && this._isLocationAvailable;
1965
+ }
1966
+ get isAccessRequested() {
1967
+ return this._isAccessRequested;
1968
+ }
1969
+ get isAccessGranted() {
1970
+ return this._isAccessRequested && this._isAccessGranted;
1971
+ }
1972
+ locationResponse(response) {
1973
+ if (this.getRequestCallbacks.length > 0) {
1974
+ this.getRequestCallbacks.forEach((cb) => cb(response));
1975
+ this.getRequestCallbacks = [];
1976
+ }
1977
+ if (response !== null) {
1978
+ this.kernel.receiveWebViewEvent("locationRequested", { locationData: response });
1979
+ }
1980
+ }
1981
+ checkVersion() {
1982
+ return this.kernel.warnIfUnsupported("8.0", "LocationManager");
1983
+ }
1984
+ checkInit() {
1985
+ if (!this._isInited) {
1986
+ console.error("[@core-ease/telegram-kit] LocationManager should be inited before using.");
1987
+ throwWebAppError("WebAppLocationManagerNotInited" /* LocationManagerNotInited */);
1988
+ }
1989
+ return true;
1990
+ }
1991
+ init(callback) {
1992
+ if (!this.checkVersion()) return this;
1993
+ if (this._isInited) return this;
1994
+ if (callback) this.initCallbacks.push(callback);
1995
+ this.kernel.webView.postEvent("web_app_check_location");
1996
+ return this;
1997
+ }
1998
+ getLocation(callback) {
1999
+ if (!this.checkVersion()) return this;
2000
+ this.checkInit();
2001
+ if (!this._isLocationAvailable) {
2002
+ console.error("[@core-ease/telegram-kit] Location is not available on this device.");
2003
+ throwWebAppError("WebAppLocationManagerLocationNotAvailable" /* LocationManagerLocationNotAvailable */);
2004
+ }
2005
+ this.getRequestCallbacks.push(callback);
2006
+ this.kernel.webView.postEvent("web_app_request_location");
2007
+ return this;
2008
+ }
2009
+ openSettings() {
2010
+ if (!this.checkVersion()) return this;
2011
+ this.checkInit();
2012
+ if (!this._isLocationAvailable) {
2013
+ console.error("[@core-ease/telegram-kit] Location is not available on this device.");
2014
+ throwWebAppError("WebAppLocationManagerLocationNotAvailable" /* LocationManagerLocationNotAvailable */);
2015
+ }
2016
+ if (!this._isAccessRequested) {
2017
+ console.error("[@core-ease/telegram-kit] Location access was not requested yet.");
2018
+ throwWebAppError("WebAppLocationManagerLocationAccessNotRequested" /* LocationManagerLocationAccessNotRequested */);
2019
+ }
2020
+ if (this._isAccessGranted) {
2021
+ console.warn("[@core-ease/telegram-kit] Location access was granted by the user, no need to go to settings.");
2022
+ return this;
2023
+ }
2024
+ this.kernel.webView.postEvent("web_app_open_location_settings");
2025
+ return this;
2026
+ }
2027
+ };
2028
+
2029
+ // src/sdk/_internal/features/invoice.ts
2030
+ var InvoiceManager = class {
2031
+ constructor(kernel) {
2032
+ this.kernel = kernel;
2033
+ this.openInvoices = {};
2034
+ this.handleInvoiceClosed = (_eventType, eventData) => {
2035
+ var _a;
2036
+ if (eventData.slug && this.openInvoices[eventData.slug]) {
2037
+ const invoiceData = this.openInvoices[eventData.slug];
2038
+ delete this.openInvoices[eventData.slug];
2039
+ (_a = invoiceData.callback) == null ? void 0 : _a.call(invoiceData, eventData.status);
2040
+ this.kernel.receiveWebViewEvent("invoiceClosed", { url: invoiceData.url, status: eventData.status });
2041
+ }
2042
+ };
2043
+ kernel.webView.onEvent("invoice_closed", this.handleInvoiceClosed);
2044
+ }
2045
+ openInvoice(url, callback) {
2046
+ const a = document.createElement("A");
2047
+ a.href = url;
2048
+ const match = a.pathname.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);
2049
+ const slug = match == null ? void 0 : match[2];
2050
+ if (a.protocol != "http:" && a.protocol != "https:" || a.hostname != "t.me" || !match || !slug) {
2051
+ console.error("[@core-ease/telegram-kit] Invoice url is invalid", url);
2052
+ throwWebAppError("WebAppInvoiceUrlInvalid" /* InvoiceUrlInvalid */);
2053
+ }
2054
+ this.kernel.requireVersion("6.1", "openInvoice");
2055
+ if (this.openInvoices[slug]) {
2056
+ console.error("[@core-ease/telegram-kit] Invoice is already opened");
2057
+ throwWebAppError("WebAppInvoiceOpened" /* InvoiceOpened */);
2058
+ }
2059
+ this.openInvoices[slug] = { url, callback };
2060
+ this.kernel.webView.postEvent("web_app_open_invoice", void 0, { slug });
2061
+ }
2062
+ };
2063
+
2064
+ // src/sdk/_internal/features/clipboard.ts
2065
+ var ClipboardManager = class {
2066
+ constructor(kernel) {
2067
+ this.kernel = kernel;
2068
+ this.handleClipboardTextReceived = (_eventType, eventData) => {
2069
+ var _a;
2070
+ if (!eventData.req_id || !this.kernel.hasCallback(eventData.req_id)) return;
2071
+ const entry = this.kernel.takeCallback(eventData.req_id);
2072
+ const data = typeof eventData.data !== "undefined" ? eventData.data : null;
2073
+ (_a = entry == null ? void 0 : entry.callback) == null ? void 0 : _a.call(entry, data);
2074
+ this.kernel.receiveWebViewEvent("clipboardTextReceived", { data });
2075
+ };
2076
+ kernel.webView.onEvent("clipboard_text_received", this.handleClipboardTextReceived);
2077
+ }
2078
+ readTextFromClipboard(callback) {
2079
+ this.kernel.requireVersion("6.4", "readTextFromClipboard");
2080
+ const reqId = this.kernel.registerCallback(callback);
2081
+ this.kernel.webView.postEvent("web_app_read_text_from_clipboard", void 0, { req_id: reqId });
2082
+ }
2083
+ };
2084
+
2085
+ // src/sdk/_internal/features/custom-method-helpers.ts
2086
+ function invokeGetRequestedContact(kernel, callback, timeout) {
2087
+ let reqTo;
2088
+ let fallbackTo;
2089
+ let reqDelay = 0;
2090
+ const reqInvoke = () => {
2091
+ kernel.invokeCustomMethod("getRequestedContact", {}, (_err, res) => {
2092
+ if (typeof res === "string" && res.substr(0, 1) == '"' && res.substr(-1) == '"') {
2093
+ res = JSON.parse(res);
2094
+ }
2095
+ if (res && res.length) {
2096
+ clearTimeout(fallbackTo);
2097
+ callback(res);
2098
+ } else {
2099
+ reqDelay += 50;
2100
+ reqTo = setTimeout(reqInvoke, reqDelay);
2101
+ }
2102
+ });
2103
+ };
2104
+ const fallbackInvoke = () => {
2105
+ clearTimeout(reqTo);
2106
+ callback("");
2107
+ };
2108
+ fallbackTo = setTimeout(fallbackInvoke, timeout);
2109
+ reqInvoke();
2110
+ }
2111
+
2112
+ // src/sdk/_internal/features/contact.ts
2113
+ var ContactManager = class {
2114
+ constructor(kernel) {
2115
+ this.kernel = kernel;
2116
+ this.writeAccessRequested = false;
2117
+ this.contactRequested = false;
2118
+ this.handleWriteAccessRequested = (_eventType, eventData) => {
2119
+ var _a;
2120
+ if (this.writeAccessRequested) {
2121
+ const requestData = this.writeAccessRequested;
2122
+ this.writeAccessRequested = false;
2123
+ (_a = requestData.callback) == null ? void 0 : _a.call(requestData, eventData.status == "allowed");
2124
+ this.kernel.receiveWebViewEvent("writeAccessRequested", { status: eventData.status });
2125
+ }
2126
+ };
2127
+ this.handlePhoneRequested = (_eventType, eventData) => {
2128
+ var _a;
2129
+ if (!this.contactRequested) return;
2130
+ const requestData = this.contactRequested;
2131
+ this.contactRequested = false;
2132
+ const requestSent = eventData.status == "sent";
2133
+ const webViewEvent = { status: eventData.status };
2134
+ if (requestSent) {
2135
+ invokeGetRequestedContact(this.kernel, (res) => {
2136
+ var _a2;
2137
+ if (res && res.length) {
2138
+ webViewEvent.response = res;
2139
+ webViewEvent.responseUnsafe = urlParseQueryString(res);
2140
+ for (const key in webViewEvent.responseUnsafe) {
2141
+ const val = webViewEvent.responseUnsafe[key];
2142
+ try {
2143
+ if ((val == null ? void 0 : val.substr(0, 1)) == "{" && (val == null ? void 0 : val.substr(-1)) == "}" || (val == null ? void 0 : val.substr(0, 1)) == "[" && (val == null ? void 0 : val.substr(-1)) == "]") {
2144
+ webViewEvent.responseUnsafe[key] = JSON.parse(val);
2145
+ }
2146
+ } catch (e) {
2147
+ }
2148
+ }
2149
+ }
2150
+ (_a2 = requestData.callback) == null ? void 0 : _a2.call(requestData, requestSent, webViewEvent);
2151
+ this.kernel.receiveWebViewEvent("contactRequested", webViewEvent);
2152
+ }, 3e3);
2153
+ } else {
2154
+ (_a = requestData.callback) == null ? void 0 : _a.call(requestData, requestSent, webViewEvent);
2155
+ this.kernel.receiveWebViewEvent("contactRequested", webViewEvent);
2156
+ }
2157
+ };
2158
+ kernel.webView.onEvent("write_access_requested", this.handleWriteAccessRequested);
2159
+ kernel.webView.onEvent("phone_requested", this.handlePhoneRequested);
2160
+ }
2161
+ requestWriteAccess(callback) {
2162
+ this.kernel.requireVersion("6.9", "requestWriteAccess");
2163
+ if (this.writeAccessRequested) {
2164
+ console.error("[@core-ease/telegram-kit] Write access is already requested");
2165
+ throwWebAppError("WebAppWriteAccessRequested" /* WriteAccessRequested */);
2166
+ }
2167
+ this.writeAccessRequested = { callback };
2168
+ this.kernel.webView.postEvent("web_app_request_write_access");
2169
+ }
2170
+ requestContact(callback) {
2171
+ this.kernel.requireVersion("6.9", "requestContact");
2172
+ if (this.contactRequested) {
2173
+ console.error("[@core-ease/telegram-kit] Contact is already requested");
2174
+ throwWebAppError("WebAppContactRequested" /* ContactRequested */);
2175
+ }
2176
+ this.contactRequested = { callback };
2177
+ this.kernel.webView.postEvent("web_app_request_phone");
2178
+ }
2179
+ };
2180
+
2181
+ // src/sdk/_internal/features/home-screen.ts
2182
+ var HomeScreenManager = class {
2183
+ constructor(kernel) {
2184
+ this.kernel = kernel;
2185
+ this.statusCallbacks = [];
2186
+ this.handleAdded = () => {
2187
+ this.kernel.receiveWebViewEvent("homeScreenAdded");
2188
+ };
2189
+ this.handleChecked = (_eventType, eventData) => {
2190
+ const status = eventData.status || "unknown";
2191
+ if (this.statusCallbacks.length > 0) {
2192
+ this.statusCallbacks.forEach((cb) => cb(status));
2193
+ this.statusCallbacks = [];
2194
+ }
2195
+ this.kernel.receiveWebViewEvent("homeScreenChecked", { status });
2196
+ };
2197
+ kernel.webView.onEvent("home_screen_added", this.handleAdded);
2198
+ kernel.webView.onEvent("home_screen_checked", this.handleChecked);
2199
+ }
2200
+ addToHomeScreen() {
2201
+ this.kernel.requireVersion("8.0", "addToHomeScreen");
2202
+ this.kernel.webView.postEvent("web_app_add_to_home_screen");
2203
+ }
2204
+ checkHomeScreenStatus(callback) {
2205
+ this.kernel.requireVersion("8.0", "checkHomeScreenStatus");
2206
+ if (callback) this.statusCallbacks.push(callback);
2207
+ this.kernel.webView.postEvent("web_app_check_home_screen");
2208
+ }
2209
+ };
2210
+
2211
+ // src/sdk/_internal/features/download-file.ts
2212
+ var DownloadFileManager = class {
2213
+ constructor(kernel) {
2214
+ this.kernel = kernel;
2215
+ this.requested = false;
2216
+ this.handleFileDownloadRequested = (_eventType, eventData) => {
2217
+ var _a;
2218
+ if (!this.requested) return;
2219
+ const requestData = this.requested;
2220
+ this.requested = false;
2221
+ const isDownloading = eventData.status == "downloading";
2222
+ (_a = requestData.callback) == null ? void 0 : _a.call(requestData, isDownloading);
2223
+ this.kernel.receiveWebViewEvent("fileDownloadRequested", { status: isDownloading ? "downloading" : "cancelled" });
2224
+ };
2225
+ kernel.webView.onEvent("file_download_requested", this.handleFileDownloadRequested);
2226
+ }
2227
+ downloadFile(params, callback) {
2228
+ this.kernel.requireVersion("8.0", "downloadFile");
2229
+ if (this.requested) {
2230
+ console.error("[@core-ease/telegram-kit] Popup is already opened");
2231
+ throwWebAppError("WebAppDownloadFilePopupOpened" /* DownloadFilePopupOpened */);
2232
+ }
2233
+ const a = document.createElement("A");
2234
+ const dlParams = {};
2235
+ if (!params || !params.url || !params.url.length) {
2236
+ console.error("[@core-ease/telegram-kit] Url is required");
2237
+ throwWebAppError("WebAppDownloadFileParamInvalid" /* DownloadFileParamInvalid */);
2238
+ }
2239
+ a.href = params.url;
2240
+ if (a.protocol != "https:") {
2241
+ console.error("[@core-ease/telegram-kit] Url protocol is not supported", params.url);
2242
+ throwWebAppError("WebAppDownloadFileParamInvalid" /* DownloadFileParamInvalid */);
2243
+ }
2244
+ dlParams.url = a.href;
2245
+ if (!params || !params.file_name || !params.file_name.length) {
2246
+ console.error("[@core-ease/telegram-kit] File name is required");
2247
+ throwWebAppError("WebAppDownloadFileParamInvalid" /* DownloadFileParamInvalid */);
2248
+ }
2249
+ dlParams.file_name = params.file_name;
2250
+ this.requested = { callback };
2251
+ this.kernel.webView.postEvent("web_app_request_file_download", void 0, dlParams);
2252
+ }
2253
+ };
2254
+
2255
+ // src/sdk/_internal/features/sharing.ts
2256
+ var SharingManager = class {
2257
+ constructor(kernel) {
2258
+ this.kernel = kernel;
2259
+ this.shareMessageOpened = false;
2260
+ this.requestChatOpened = false;
2261
+ this.handlePreparedMessageSent = () => {
2262
+ var _a;
2263
+ if (!this.shareMessageOpened) return;
2264
+ const requestData = this.shareMessageOpened;
2265
+ this.shareMessageOpened = false;
2266
+ (_a = requestData.callback) == null ? void 0 : _a.call(requestData, true);
2267
+ this.kernel.receiveWebViewEvent("shareMessageSent");
2268
+ };
2269
+ this.handlePreparedMessageFailed = (_eventType, eventData) => {
2270
+ var _a;
2271
+ if (!this.shareMessageOpened) return;
2272
+ const requestData = this.shareMessageOpened;
2273
+ this.shareMessageOpened = false;
2274
+ (_a = requestData.callback) == null ? void 0 : _a.call(requestData, false);
2275
+ this.kernel.receiveWebViewEvent("shareMessageFailed", { error: eventData.error });
2276
+ };
2277
+ this.handleRequestedChatSent = () => {
2278
+ var _a;
2279
+ if (!this.requestChatOpened) return;
2280
+ const requestData = this.requestChatOpened;
2281
+ this.requestChatOpened = false;
2282
+ (_a = requestData.callback) == null ? void 0 : _a.call(requestData, true);
2283
+ this.kernel.receiveWebViewEvent("requestedChatSent");
2284
+ };
2285
+ this.handleRequestedChatFailed = (_eventType, eventData) => {
2286
+ var _a;
2287
+ if (!this.requestChatOpened) return;
2288
+ const requestData = this.requestChatOpened;
2289
+ this.requestChatOpened = false;
2290
+ (_a = requestData.callback) == null ? void 0 : _a.call(requestData, false);
2291
+ this.kernel.receiveWebViewEvent("requestedChatFailed", { error: eventData.error });
2292
+ };
2293
+ kernel.webView.onEvent("prepared_message_sent", this.handlePreparedMessageSent);
2294
+ kernel.webView.onEvent("prepared_message_failed", this.handlePreparedMessageFailed);
2295
+ kernel.webView.onEvent("requested_chat_sent", this.handleRequestedChatSent);
2296
+ kernel.webView.onEvent("requested_chat_failed", this.handleRequestedChatFailed);
2297
+ }
2298
+ shareToStory(mediaUrl, params = {}) {
2299
+ this.kernel.requireVersion("7.8", "shareToStory");
2300
+ const a = document.createElement("A");
2301
+ a.href = mediaUrl;
2302
+ if (a.protocol != "http:" && a.protocol != "https:") {
2303
+ console.error("[@core-ease/telegram-kit] Media url protocol is not supported", mediaUrl);
2304
+ throwWebAppError("WebAppMediaUrlInvalid" /* MediaUrlInvalid */);
2305
+ }
2306
+ const shareParams = { media_url: a.href };
2307
+ if (typeof params.text !== "undefined") {
2308
+ const text = strTrim(params.text);
2309
+ if (text.length > 2048) {
2310
+ console.error("[@core-ease/telegram-kit] Text is too long", text);
2311
+ throwWebAppError("WebAppShareToStoryParamInvalid" /* ShareToStoryParamInvalid */);
2312
+ }
2313
+ if (text.length > 0) shareParams.text = text;
2314
+ }
2315
+ if (typeof params.widget_link !== "undefined") {
2316
+ const widgetLinkParam = params.widget_link || {};
2317
+ a.href = widgetLinkParam.url;
2318
+ if (a.protocol != "http:" && a.protocol != "https:") {
2319
+ console.error("[@core-ease/telegram-kit] Link protocol is not supported", widgetLinkParam.url);
2320
+ throwWebAppError("WebAppShareToStoryParamInvalid" /* ShareToStoryParamInvalid */);
2321
+ }
2322
+ const widgetLink = { url: a.href };
2323
+ if (typeof widgetLinkParam.name !== "undefined") {
2324
+ const linkName = strTrim(widgetLinkParam.name);
2325
+ if (linkName.length > 48) {
2326
+ console.error("[@core-ease/telegram-kit] Link name is too long", linkName);
2327
+ throwWebAppError("WebAppShareToStoryParamInvalid" /* ShareToStoryParamInvalid */);
2328
+ }
2329
+ if (linkName.length > 0) widgetLink.name = linkName;
2330
+ }
2331
+ shareParams.widget_link = widgetLink;
2332
+ }
2333
+ this.kernel.webView.postEvent("web_app_share_to_story", void 0, shareParams);
2334
+ }
2335
+ shareMessage(msgId, callback) {
2336
+ this.kernel.requireVersion("8.0", "shareMessage");
2337
+ if (this.shareMessageOpened) {
2338
+ console.error("[@core-ease/telegram-kit] Share message is already opened");
2339
+ throwWebAppError("WebAppShareMessageOpened" /* ShareMessageOpened */);
2340
+ }
2341
+ this.shareMessageOpened = { callback };
2342
+ this.kernel.webView.postEvent("web_app_send_prepared_message", void 0, { id: msgId });
2343
+ }
2344
+ requestChat(reqId, callback) {
2345
+ this.kernel.requireVersion("9.6", "requestChat");
2346
+ if (this.requestChatOpened) {
2347
+ console.error("[@core-ease/telegram-kit] Request chat is already opened");
2348
+ throwWebAppError("WebAppRequestChatOpened" /* RequestChatOpened */);
2349
+ }
2350
+ this.requestChatOpened = { callback };
2351
+ this.kernel.webView.postEvent("web_app_request_chat", void 0, { req_id: reqId });
2352
+ }
2353
+ switchInlineQuery(query, chooseChatTypes, initParams) {
2354
+ this.kernel.requireVersion("6.6", "switchInlineQuery");
2355
+ if (!initParams.tgWebAppBotInline) {
2356
+ console.error(
2357
+ "[@core-ease/telegram-kit] Inline mode is disabled for this bot. Read more about inline mode: https://core.telegram.org/bots/inline"
2358
+ );
2359
+ throwWebAppError("WebAppInlineModeDisabled" /* InlineModeDisabled */);
2360
+ }
2361
+ const q = query || "";
2362
+ if (q.length > 256) {
2363
+ console.error("[@core-ease/telegram-kit] Inline query is too long", q);
2364
+ throwWebAppError("WebAppInlineQueryInvalid" /* InlineQueryInvalid */);
2365
+ }
2366
+ const chatTypes = [];
2367
+ if (chooseChatTypes) {
2368
+ if (!Array.isArray(chooseChatTypes)) {
2369
+ console.error("[@core-ease/telegram-kit] Choose chat types should be an array", chooseChatTypes);
2370
+ throwWebAppError("WebAppInlineChooseChatTypesInvalid" /* InlineChooseChatTypesInvalid */);
2371
+ }
2372
+ const goodTypes = { users: 1, bots: 1, groups: 1, channels: 1 };
2373
+ for (const chatType of chooseChatTypes) {
2374
+ if (!goodTypes[chatType]) {
2375
+ console.error("[@core-ease/telegram-kit] Choose chat type is invalid", chatType);
2376
+ throwWebAppError("WebAppInlineChooseChatTypeInvalid" /* InlineChooseChatTypeInvalid */);
2377
+ }
2378
+ if (goodTypes[chatType] != 2) {
2379
+ goodTypes[chatType] = 2;
2380
+ chatTypes.push(chatType);
2381
+ }
2382
+ }
2383
+ }
2384
+ this.kernel.webView.postEvent("web_app_switch_inline_query", void 0, { query: q, chat_types: chatTypes });
2385
+ }
2386
+ };
2387
+
2388
+ // src/sdk/_internal/features/emoji-status.ts
2389
+ var EmojiStatusManager = class {
2390
+ constructor(kernel) {
2391
+ this.kernel = kernel;
2392
+ this.setRequested = false;
2393
+ this.accessRequested = false;
2394
+ this.handleSet = () => {
2395
+ var _a;
2396
+ if (!this.setRequested) return;
2397
+ const requestData = this.setRequested;
2398
+ this.setRequested = false;
2399
+ (_a = requestData.callback) == null ? void 0 : _a.call(requestData, true);
2400
+ this.kernel.receiveWebViewEvent("emojiStatusSet");
2401
+ };
2402
+ this.handleFailed = (_eventType, eventData) => {
2403
+ var _a;
2404
+ if (!this.setRequested) return;
2405
+ const requestData = this.setRequested;
2406
+ this.setRequested = false;
2407
+ (_a = requestData.callback) == null ? void 0 : _a.call(requestData, false);
2408
+ this.kernel.receiveWebViewEvent("emojiStatusFailed", { error: eventData.error });
2409
+ };
2410
+ this.handleAccessRequested = (_eventType, eventData) => {
2411
+ var _a;
2412
+ if (!this.accessRequested) return;
2413
+ const requestData = this.accessRequested;
2414
+ this.accessRequested = false;
2415
+ (_a = requestData.callback) == null ? void 0 : _a.call(requestData, eventData.status == "allowed");
2416
+ this.kernel.receiveWebViewEvent("emojiStatusAccessRequested", { status: eventData.status });
2417
+ };
2418
+ kernel.webView.onEvent("emoji_status_set", this.handleSet);
2419
+ kernel.webView.onEvent("emoji_status_failed", this.handleFailed);
2420
+ kernel.webView.onEvent("emoji_status_access_requested", this.handleAccessRequested);
2421
+ }
2422
+ setEmojiStatus(customEmojiId, params = {}, callback) {
2423
+ this.kernel.requireVersion("8.0", "setEmojiStatus");
2424
+ const statusParams = { custom_emoji_id: customEmojiId };
2425
+ if (typeof params.duration !== "undefined") {
2426
+ statusParams.duration = params.duration;
2427
+ }
2428
+ if (this.setRequested) {
2429
+ console.error("[@core-ease/telegram-kit] Emoji status is already requested");
2430
+ throwWebAppError("WebAppEmojiStatusRequested" /* EmojiStatusRequested */);
2431
+ }
2432
+ this.setRequested = { callback };
2433
+ this.kernel.webView.postEvent("web_app_set_emoji_status", void 0, statusParams);
2434
+ }
2435
+ requestEmojiStatusAccess(callback) {
2436
+ this.kernel.requireVersion("8.0", "requestEmojiStatusAccess");
2437
+ if (this.accessRequested) {
2438
+ console.error("[@core-ease/telegram-kit] Emoji status permission is already requested");
2439
+ throwWebAppError("WebAppEmojiStatusAccessRequested" /* EmojiStatusAccessRequested */);
2440
+ }
2441
+ this.accessRequested = { callback };
2442
+ this.kernel.webView.postEvent("web_app_request_emoji_status_access");
2443
+ }
2444
+ };
2445
+
2446
+ // src/sdk/_internal/features/links.ts
2447
+ var LinkManager = class {
2448
+ constructor(kernel) {
2449
+ this.kernel = kernel;
2450
+ /**
2451
+ * Intercepts clicks on in-page `t.me` links while running inside an
2452
+ * iframe (web.telegram.org) and routes them through `openTelegramLink`
2453
+ * instead of letting the browser navigate directly.
2454
+ */
2455
+ this.handleDocumentClick = (e) => {
2456
+ if (e.metaKey || e.ctrlKey) return;
2457
+ let el = e.target;
2458
+ while (el && el.tagName != "A" && el.parentNode) {
2459
+ el = el.parentNode;
2460
+ }
2461
+ if (el && el.tagName == "A" && el.target != "_blank" && (el.protocol == "http:" || el.protocol == "https:") && el.hostname == "t.me") {
2462
+ this.openTelegramLink(el.href);
2463
+ e.preventDefault();
2464
+ }
2465
+ };
2466
+ }
2467
+ openLink(url, options = {}) {
2468
+ const a = document.createElement("A");
2469
+ a.href = url;
2470
+ if (a.protocol != "http:" && a.protocol != "https:") {
2471
+ console.error("[@core-ease/telegram-kit] Url protocol is not supported", url);
2472
+ throwWebAppError("WebAppTgUrlInvalid" /* TgUrlInvalid */);
2473
+ }
2474
+ const resolvedUrl = a.href;
2475
+ if (this.kernel.versionAtLeast("6.1")) {
2476
+ const reqParams = { url: resolvedUrl };
2477
+ if (this.kernel.versionAtLeast("6.4") && options.try_instant_view) {
2478
+ reqParams.try_instant_view = true;
2479
+ }
2480
+ if (this.kernel.versionAtLeast("7.6") && options.try_browser) {
2481
+ reqParams.try_browser = options.try_browser;
2482
+ }
2483
+ this.kernel.webView.postEvent("web_app_open_link", void 0, reqParams);
2484
+ } else {
2485
+ window.open(resolvedUrl, "_blank");
2486
+ }
2487
+ }
2488
+ openTelegramLink(url, options = {}) {
2489
+ const a = document.createElement("A");
2490
+ a.href = url;
2491
+ if (a.protocol != "http:" && a.protocol != "https:") {
2492
+ console.error("[@core-ease/telegram-kit] Url protocol is not supported", url);
2493
+ throwWebAppError("WebAppTgUrlInvalid" /* TgUrlInvalid */);
2494
+ }
2495
+ if (a.hostname != "t.me") {
2496
+ console.error("[@core-ease/telegram-kit] Url host is not supported", url);
2497
+ throwWebAppError("WebAppTgUrlInvalid" /* TgUrlInvalid */);
2498
+ }
2499
+ const pathFull = a.pathname + a.search;
2500
+ if (this.kernel.webView.isIframe || this.kernel.versionAtLeast("6.1")) {
2501
+ const reqParams = { path_full: pathFull };
2502
+ if (options.force_request) {
2503
+ reqParams.force_request = true;
2504
+ }
2505
+ this.kernel.webView.postEvent("web_app_open_tg_link", void 0, reqParams);
2506
+ } else {
2507
+ location.href = "https://t.me" + pathFull;
2508
+ }
2509
+ }
2510
+ };
2511
+
2512
+ // src/sdk/_internal/sensors/motion-sensor-base.ts
2513
+ var MotionSensorBase = class {
2514
+ constructor(kernel, names, initialValues) {
2515
+ this.kernel = kernel;
2516
+ this.names = names;
2517
+ this._isStarted = false;
2518
+ this.startCallbacks = [];
2519
+ this.stopCallbacks = [];
2520
+ this.handleStarted = () => {
2521
+ this._isStarted = true;
2522
+ if (this.startCallbacks.length > 0) {
2523
+ this.startCallbacks.forEach((cb) => cb(true));
2524
+ this.startCallbacks = [];
2525
+ }
2526
+ this.kernel.receiveWebViewEvent(this.names.webViewStarted);
2527
+ };
2528
+ this.handleStopped = () => {
2529
+ this._isStarted = false;
2530
+ if (this.stopCallbacks.length > 0) {
2531
+ this.stopCallbacks.forEach((cb) => cb(true));
2532
+ this.stopCallbacks = [];
2533
+ }
2534
+ this.kernel.receiveWebViewEvent(this.names.webViewStopped);
2535
+ };
2536
+ this.handleChanged = (_eventType, eventData) => {
2537
+ this.values = this.mapChangedPayload(eventData);
2538
+ this.kernel.receiveWebViewEvent(this.names.webViewChanged);
2539
+ };
2540
+ this.handleFailed = (_eventType, eventData) => {
2541
+ if (this.startCallbacks.length > 0) {
2542
+ this.startCallbacks.forEach((cb) => cb(false));
2543
+ this.startCallbacks = [];
2544
+ }
2545
+ this.kernel.receiveWebViewEvent(this.names.webViewFailed, { error: eventData.error });
2546
+ };
2547
+ this.values = initialValues;
2548
+ kernel.webView.onEvent(names.started, this.handleStarted);
2549
+ kernel.webView.onEvent(names.stopped, this.handleStopped);
2550
+ kernel.webView.onEvent(names.changed, this.handleChanged);
2551
+ kernel.webView.onEvent(names.failed, this.handleFailed);
2552
+ }
2553
+ get isStarted() {
2554
+ return this._isStarted;
2555
+ }
2556
+ checkVersion() {
2557
+ return this.kernel.warnIfUnsupported(this.names.minVersion, this.names.displayName);
2558
+ }
2559
+ buildStartParams(refreshRate) {
2560
+ const params = {};
2561
+ const rate = parseInt(String(refreshRate != null ? refreshRate : 1e3));
2562
+ if (isNaN(rate) || rate < 20 || rate > 1e3) {
2563
+ console.warn(`[@core-ease/telegram-kit] ${this.names.displayName} refresh_rate is invalid`, rate);
2564
+ } else {
2565
+ params.refresh_rate = rate;
2566
+ }
2567
+ return params;
2568
+ }
2569
+ doStart(reqParams, callback) {
2570
+ if (callback) this.startCallbacks.push(callback);
2571
+ this.kernel.webView.postEvent(this.names.startCommand, void 0, reqParams);
2572
+ }
2573
+ stop(callback) {
2574
+ if (!this.checkVersion()) return this;
2575
+ if (callback) this.stopCallbacks.push(callback);
2576
+ this.kernel.webView.postEvent(this.names.stopCommand);
2577
+ return this;
2578
+ }
2579
+ };
2580
+
2581
+ // src/sdk/_internal/sensors/accelerometer.ts
2582
+ var Accelerometer = class extends MotionSensorBase {
2583
+ constructor(kernel) {
2584
+ super(
2585
+ kernel,
2586
+ {
2587
+ started: "accelerometer_started",
2588
+ stopped: "accelerometer_stopped",
2589
+ changed: "accelerometer_changed",
2590
+ failed: "accelerometer_failed",
2591
+ webViewStarted: "accelerometerStarted",
2592
+ webViewStopped: "accelerometerStopped",
2593
+ webViewChanged: "accelerometerChanged",
2594
+ webViewFailed: "accelerometerFailed",
2595
+ startCommand: "web_app_start_accelerometer",
2596
+ stopCommand: "web_app_stop_accelerometer",
2597
+ minVersion: "8.0",
2598
+ displayName: "Accelerometer"
2599
+ },
2600
+ { x: null, y: null, z: null }
2601
+ );
2602
+ }
2603
+ mapChangedPayload(eventData) {
2604
+ return { x: eventData.x, y: eventData.y, z: eventData.z };
2605
+ }
2606
+ get x() {
2607
+ return this.values.x;
2608
+ }
2609
+ get y() {
2610
+ return this.values.y;
2611
+ }
2612
+ get z() {
2613
+ return this.values.z;
2614
+ }
2615
+ start(params = {}, callback) {
2616
+ if (!this.checkVersion()) return this;
2617
+ const reqParams = this.buildStartParams(params.refresh_rate);
2618
+ this.doStart(reqParams, callback);
2619
+ return this;
2620
+ }
2621
+ };
2622
+
2623
+ // src/sdk/_internal/sensors/gyroscope.ts
2624
+ var Gyroscope = class extends MotionSensorBase {
2625
+ constructor(kernel) {
2626
+ super(
2627
+ kernel,
2628
+ {
2629
+ started: "gyroscope_started",
2630
+ stopped: "gyroscope_stopped",
2631
+ changed: "gyroscope_changed",
2632
+ failed: "gyroscope_failed",
2633
+ webViewStarted: "gyroscopeStarted",
2634
+ webViewStopped: "gyroscopeStopped",
2635
+ webViewChanged: "gyroscopeChanged",
2636
+ webViewFailed: "gyroscopeFailed",
2637
+ startCommand: "web_app_start_gyroscope",
2638
+ stopCommand: "web_app_stop_gyroscope",
2639
+ minVersion: "8.0",
2640
+ displayName: "Gyroscope"
2641
+ },
2642
+ { x: null, y: null, z: null }
2643
+ );
2644
+ }
2645
+ mapChangedPayload(eventData) {
2646
+ return { x: eventData.x, y: eventData.y, z: eventData.z };
2647
+ }
2648
+ get x() {
2649
+ return this.values.x;
2650
+ }
2651
+ get y() {
2652
+ return this.values.y;
2653
+ }
2654
+ get z() {
2655
+ return this.values.z;
2656
+ }
2657
+ start(params = {}, callback) {
2658
+ if (!this.checkVersion()) return this;
2659
+ const reqParams = this.buildStartParams(params.refresh_rate);
2660
+ this.doStart(reqParams, callback);
2661
+ return this;
2662
+ }
2663
+ };
2664
+
2665
+ // src/sdk/_internal/sensors/device-orientation.ts
2666
+ var DeviceOrientation = class extends MotionSensorBase {
2667
+ constructor(kernel) {
2668
+ super(
2669
+ kernel,
2670
+ {
2671
+ started: "device_orientation_started",
2672
+ stopped: "device_orientation_stopped",
2673
+ changed: "device_orientation_changed",
2674
+ failed: "device_orientation_failed",
2675
+ webViewStarted: "deviceOrientationStarted",
2676
+ webViewStopped: "deviceOrientationStopped",
2677
+ webViewChanged: "deviceOrientationChanged",
2678
+ webViewFailed: "deviceOrientationFailed",
2679
+ startCommand: "web_app_start_device_orientation",
2680
+ stopCommand: "web_app_stop_device_orientation",
2681
+ minVersion: "8.0",
2682
+ displayName: "DeviceOrientation"
2683
+ },
2684
+ { absolute: false, alpha: null, beta: null, gamma: null }
2685
+ );
2686
+ }
2687
+ mapChangedPayload(eventData) {
2688
+ return {
2689
+ absolute: !!eventData.absolute,
2690
+ alpha: eventData.alpha,
2691
+ beta: eventData.beta,
2692
+ gamma: eventData.gamma
2693
+ };
2694
+ }
2695
+ get absolute() {
2696
+ return this.values.absolute;
2697
+ }
2698
+ get alpha() {
2699
+ return this.values.alpha;
2700
+ }
2701
+ get beta() {
2702
+ return this.values.beta;
2703
+ }
2704
+ get gamma() {
2705
+ return this.values.gamma;
2706
+ }
2707
+ start(params = {}, callback) {
2708
+ if (!this.checkVersion()) return this;
2709
+ const reqParams = this.buildStartParams(params.refresh_rate);
2710
+ reqParams.need_absolute = !!params.need_absolute;
2711
+ this.doStart(reqParams, callback);
2712
+ return this;
2713
+ }
2714
+ };
2715
+
2716
+ // src/sdk/_internal/webapp.ts
2717
+ var WebApp = class {
2718
+ constructor(webView) {
2719
+ this.webView = webView;
2720
+ this.webAppInitData = "";
2721
+ this.webAppInitDataUnsafe = {};
2722
+ this.webAppPlatform = "unknown";
2723
+ this.webAppIsActive = true;
2724
+ this.handleThemeChanged = (_eventType, eventData) => {
2725
+ if (eventData.theme_params) {
2726
+ this.theme.setThemeParams(eventData.theme_params);
2727
+ this.MainButton.setParams({});
2728
+ this.SecondaryButton.setParams({});
2729
+ this.theme.updateHeaderColor();
2730
+ this.theme.updateBackgroundColor();
2731
+ this.theme.updateBottomBarColor();
2732
+ this.kernel.receiveWebViewEvent("themeChanged");
2733
+ }
2734
+ };
2735
+ this.handleVisibilityChanged = (_eventType, eventData) => {
2736
+ if (eventData.is_visible) {
2737
+ this.webAppIsActive = true;
2738
+ this.kernel.receiveWebViewEvent("activated");
2739
+ } else {
2740
+ this.webAppIsActive = false;
2741
+ this.kernel.receiveWebViewEvent("deactivated");
2742
+ }
2743
+ };
2744
+ const kernel = new WebAppKernel(webView);
2745
+ this.kernel = kernel;
2746
+ const initParams = webView.initParams;
2747
+ if (initParams.tgWebAppData && initParams.tgWebAppData.length) {
2748
+ this.webAppInitData = initParams.tgWebAppData;
2749
+ const parsed = urlParseQueryString(this.webAppInitData);
2750
+ for (const key in parsed) {
2751
+ const val = parsed[key];
2752
+ try {
2753
+ if ((val == null ? void 0 : val.substr(0, 1)) == "{" && (val == null ? void 0 : val.substr(-1)) == "}" || (val == null ? void 0 : val.substr(0, 1)) == "[" && (val == null ? void 0 : val.substr(-1)) == "]") {
2754
+ parsed[key] = JSON.parse(val);
2755
+ }
2756
+ } catch (e) {
2757
+ }
2758
+ }
2759
+ this.webAppInitDataUnsafe = parsed;
2760
+ }
2761
+ if (initParams.tgWebAppPlatform) {
2762
+ this.webAppPlatform = initParams.tgWebAppPlatform;
2763
+ }
2764
+ this.theme = new ThemeManager(kernel);
2765
+ this.viewport = new ViewportManager(kernel);
2766
+ this.debugBar = new DebugBottomBar(kernel, () => this.theme.getBottomBarColor());
2767
+ this.BackButton = new BackButton(kernel);
2768
+ this.MainButton = new BottomButton("main", kernel, this.theme, this.debugBar);
2769
+ this.SecondaryButton = new BottomButton("secondary", kernel, this.theme, this.debugBar);
2770
+ this.SettingsButton = new SettingsButton(kernel);
2771
+ this.popups = new PopupManager(kernel);
2772
+ this.scanQr = new ScanQrManager(kernel);
2773
+ this.HapticFeedback = new HapticFeedback(kernel);
2774
+ this.CloudStorage = new CloudStorage(kernel);
2775
+ this.DeviceStorage = new DeviceStorage(kernel);
2776
+ this.SecureStorage = new SecureStorage(kernel);
2777
+ this.BiometricManager = new BiometricManager(kernel);
2778
+ this.LocationManager = new LocationManager(kernel);
2779
+ this.invoices = new InvoiceManager(kernel);
2780
+ this.clipboard = new ClipboardManager(kernel);
2781
+ this.contact = new ContactManager(kernel);
2782
+ this.homeScreen = new HomeScreenManager(kernel);
2783
+ this.downloadFileManager = new DownloadFileManager(kernel);
2784
+ this.sharing = new SharingManager(kernel);
2785
+ this.emojiStatus = new EmojiStatusManager(kernel);
2786
+ this.links = new LinkManager(kernel);
2787
+ this.Accelerometer = new Accelerometer(kernel);
2788
+ this.DeviceOrientation = new DeviceOrientation(kernel);
2789
+ this.Gyroscope = new Gyroscope(kernel);
2790
+ this.debugBar.onHeightChanged = () => this.viewport.setViewportHeight();
2791
+ this.theme.onBottomBarColorApplied = () => {
2792
+ this.debugBar.refreshColor();
2793
+ this.SecondaryButton.setParams({});
2794
+ };
2795
+ kernel.webView.onEvent("theme_changed", this.handleThemeChanged);
2796
+ kernel.webView.onEvent("viewport_changed", this.viewport.handleViewportChanged);
2797
+ kernel.webView.onEvent("safe_area_changed", this.viewport.handleSafeAreaChanged);
2798
+ kernel.webView.onEvent("content_safe_area_changed", this.viewport.handleContentSafeAreaChanged);
2799
+ kernel.webView.onEvent("visibility_changed", this.handleVisibilityChanged);
2800
+ kernel.webView.onEvent("fullscreen_changed", this.viewport.handleFullscreenChanged);
2801
+ kernel.webView.onEvent("fullscreen_failed", this.viewport.handleFullscreenFailed);
2802
+ kernel.webView.onEvent("custom_method_invoked", kernel.onCustomMethodInvoked);
2803
+ window.addEventListener("resize", this.viewport.onWindowResize);
2804
+ if (webView.isIframe) {
2805
+ document.addEventListener("click", this.links.handleDocumentClick);
2806
+ }
2807
+ this.theme.updateHeaderColor();
2808
+ this.theme.updateBackgroundColor();
2809
+ this.theme.updateBottomBarColor();
2810
+ this.viewport.setViewportHeight();
2811
+ if (initParams.tgWebAppShowSettings) {
2812
+ this.SettingsButton.show();
2813
+ }
2814
+ kernel.webView.postEvent("web_app_request_theme");
2815
+ kernel.webView.postEvent("web_app_request_viewport");
2816
+ kernel.webView.postEvent("web_app_request_safe_area");
2817
+ kernel.webView.postEvent("web_app_request_content_safe_area");
2818
+ }
2819
+ // -----------------------------------------------------------------------
2820
+ // Public read-only properties
2821
+ // -----------------------------------------------------------------------
2822
+ get initData() {
2823
+ return this.webAppInitData;
2824
+ }
2825
+ get initDataUnsafe() {
2826
+ return this.webAppInitDataUnsafe;
2827
+ }
2828
+ get version() {
2829
+ return this.kernel.version;
2830
+ }
2831
+ get platform() {
2832
+ return this.webAppPlatform;
2833
+ }
2834
+ get colorScheme() {
2835
+ return this.theme.colorScheme;
2836
+ }
2837
+ get themeParams() {
2838
+ return this.theme.getThemeParams();
2839
+ }
2840
+ get isExpanded() {
2841
+ return this.viewport.isExpanded;
2842
+ }
2843
+ get viewportHeight() {
2844
+ return this.viewport.viewportHeight;
2845
+ }
2846
+ get viewportStableHeight() {
2847
+ return this.viewport.viewportStableHeight;
2848
+ }
2849
+ get safeAreaInset() {
2850
+ return this.viewport.safeAreaInset;
2851
+ }
2852
+ get contentSafeAreaInset() {
2853
+ return this.viewport.contentSafeAreaInset;
2854
+ }
2855
+ get isFullscreen() {
2856
+ return this.viewport.isFullscreen;
2857
+ }
2858
+ get isActive() {
2859
+ return this.webAppIsActive;
2860
+ }
2861
+ get isClosingConfirmationEnabled() {
2862
+ return this.viewport.isClosingConfirmationEnabled;
2863
+ }
2864
+ set isClosingConfirmationEnabled(val) {
2865
+ this.viewport.setClosingConfirmation(val);
2866
+ }
2867
+ get isVerticalSwipesEnabled() {
2868
+ return this.viewport.isVerticalSwipesEnabled;
2869
+ }
2870
+ set isVerticalSwipesEnabled(val) {
2871
+ this.viewport.toggleVerticalSwipes(val);
2872
+ }
2873
+ get isOrientationLocked() {
2874
+ return this.viewport.isOrientationLocked;
2875
+ }
2876
+ set isOrientationLocked(val) {
2877
+ this.viewport.toggleOrientationLock(val);
2878
+ }
2879
+ get headerColor() {
2880
+ return this.theme.getHeaderColor();
2881
+ }
2882
+ set headerColor(val) {
2883
+ this.theme.setHeaderColor(val);
2884
+ }
2885
+ get backgroundColor() {
2886
+ return this.theme.getBackgroundColor();
2887
+ }
2888
+ set backgroundColor(val) {
2889
+ this.theme.setBackgroundColor(val);
2890
+ }
2891
+ get bottomBarColor() {
2892
+ return this.theme.getBottomBarColor();
2893
+ }
2894
+ set bottomBarColor(val) {
2895
+ this.theme.setBottomBarColor(val);
2896
+ }
2897
+ // -----------------------------------------------------------------------
2898
+ // Methods
2899
+ // -----------------------------------------------------------------------
2900
+ isVersionAtLeast(ver) {
2901
+ return this.kernel.versionAtLeast(ver);
2902
+ }
2903
+ setHeaderColor(colorKey) {
2904
+ this.headerColor = colorKey;
2905
+ }
2906
+ setBackgroundColor(color) {
2907
+ this.backgroundColor = color;
2908
+ }
2909
+ setBottomBarColor(color) {
2910
+ this.bottomBarColor = color;
2911
+ }
2912
+ enableClosingConfirmation() {
2913
+ this.isClosingConfirmationEnabled = true;
2914
+ }
2915
+ disableClosingConfirmation() {
2916
+ this.isClosingConfirmationEnabled = false;
2917
+ }
2918
+ enableVerticalSwipes() {
2919
+ this.isVerticalSwipesEnabled = true;
2920
+ }
2921
+ disableVerticalSwipes() {
2922
+ this.isVerticalSwipesEnabled = false;
2923
+ }
2924
+ lockOrientation() {
2925
+ this.isOrientationLocked = true;
2926
+ }
2927
+ unlockOrientation() {
2928
+ this.isOrientationLocked = false;
2929
+ }
2930
+ requestFullscreen() {
2931
+ this.viewport.requestFullscreen();
2932
+ }
2933
+ exitFullscreen() {
2934
+ this.viewport.exitFullscreen();
2935
+ }
2936
+ addToHomeScreen() {
2937
+ this.homeScreen.addToHomeScreen();
2938
+ }
2939
+ checkHomeScreenStatus(callback) {
2940
+ this.homeScreen.checkHomeScreenStatus(callback);
2941
+ }
2942
+ onEvent(eventType, callback) {
2943
+ this.kernel.onWebViewEvent(eventType, callback);
2944
+ }
2945
+ offEvent(eventType, callback) {
2946
+ this.kernel.offWebViewEvent(eventType, callback);
2947
+ }
2948
+ sendData(data) {
2949
+ if (!data || !data.length) {
2950
+ console.error("[@core-ease/telegram-kit] Data is required", data);
2951
+ throwWebAppError("WebAppDataInvalid" /* DataInvalid */);
2952
+ }
2953
+ if (byteLength(data) > 4096) {
2954
+ console.error("[@core-ease/telegram-kit] Data is too long", data);
2955
+ throwWebAppError("WebAppDataInvalid" /* DataInvalid */);
2956
+ }
2957
+ this.kernel.webView.postEvent("web_app_data_send", void 0, { data });
2958
+ }
2959
+ switchInlineQuery(query, chooseChatTypes) {
2960
+ this.sharing.switchInlineQuery(query, chooseChatTypes, this.kernel.initParams);
2961
+ }
2962
+ openLink(url, options) {
2963
+ this.links.openLink(url, options);
2964
+ }
2965
+ openTelegramLink(url, options) {
2966
+ this.links.openTelegramLink(url, options);
2967
+ }
2968
+ openInvoice(url, callback) {
2969
+ this.invoices.openInvoice(url, callback);
2970
+ }
2971
+ showPopup(params, callback) {
2972
+ this.popups.showPopup(params, callback);
2973
+ }
2974
+ showAlert(message, callback) {
2975
+ this.popups.showAlert(message, callback);
2976
+ }
2977
+ showConfirm(message, callback) {
2978
+ this.popups.showConfirm(message, callback);
2979
+ }
2980
+ showScanQrPopup(params, callback) {
2981
+ this.scanQr.showScanQrPopup(params, callback);
2982
+ }
2983
+ closeScanQrPopup() {
2984
+ this.scanQr.closeScanQrPopup();
2985
+ }
2986
+ readTextFromClipboard(callback) {
2987
+ this.clipboard.readTextFromClipboard(callback);
2988
+ }
2989
+ requestWriteAccess(callback) {
2990
+ this.contact.requestWriteAccess(callback);
2991
+ }
2992
+ requestContact(callback) {
2993
+ this.contact.requestContact(callback);
2994
+ }
2995
+ downloadFile(params, callback) {
2996
+ this.downloadFileManager.downloadFile(params, callback);
2997
+ }
2998
+ shareToStory(mediaUrl, params) {
2999
+ this.sharing.shareToStory(mediaUrl, params);
3000
+ }
3001
+ shareMessage(msgId, callback) {
3002
+ this.sharing.shareMessage(msgId, callback);
3003
+ }
3004
+ requestChat(reqId, callback) {
3005
+ this.sharing.requestChat(reqId, callback);
3006
+ }
3007
+ setEmojiStatus(customEmojiId, params, callback) {
3008
+ this.emojiStatus.setEmojiStatus(customEmojiId, params, callback);
3009
+ }
3010
+ requestEmojiStatusAccess(callback) {
3011
+ this.emojiStatus.requestEmojiStatusAccess(callback);
3012
+ }
3013
+ invokeCustomMethod(method, params, callback) {
3014
+ this.kernel.invokeCustomMethod(method, params, callback);
3015
+ }
3016
+ hideKeyboard() {
3017
+ this.kernel.webView.postEvent("web_app_hide_keyboard");
3018
+ }
3019
+ ready() {
3020
+ this.kernel.webView.postEvent("web_app_ready");
3021
+ }
3022
+ expand() {
3023
+ this.kernel.webView.postEvent("web_app_expand");
3024
+ }
3025
+ close(options = {}) {
3026
+ const reqParams = {};
3027
+ if (this.kernel.versionAtLeast("7.6") && options.return_back) {
3028
+ reqParams.return_back = true;
3029
+ }
3030
+ this.kernel.webView.postEvent("web_app_close", void 0, reqParams);
3031
+ }
3032
+ };
3033
+
3034
+ // src/sdk/index.ts
3035
+ var SDK_NAME = "@core-ease/telegram-kit";
3036
+ var bootstrapped = null;
3037
+ function bootstrapTelegramWebApp() {
3038
+ var _a;
3039
+ if (bootstrapped) {
3040
+ return bootstrapped;
3041
+ }
3042
+ if (typeof window === "undefined" || typeof document === "undefined") {
3043
+ throw new Error(`[${SDK_NAME}] bootstrapTelegramWebApp() requires a browser environment (window/document).`);
3044
+ }
3045
+ const webView = new TelegramWebView();
3046
+ const telegram = (_a = window.Telegram) != null ? _a : window.Telegram = {};
3047
+ telegram.WebView = webView;
3048
+ telegram.Utils = Utils;
3049
+ const webApp = new WebApp(webView);
3050
+ telegram.WebApp = webApp;
3051
+ bootstrapped = { webView, webApp };
3052
+ return bootstrapped;
3053
+ }
3054
+
3055
+ // src/core/fallback.ts
3056
+ var DEV_MODE_STORAGE_KEY = "@core-ease/telegram-kit:dev-mode-active";
3057
+ function isDevModeActive() {
3058
+ try {
3059
+ return typeof window !== "undefined" && window.sessionStorage.getItem(DEV_MODE_STORAGE_KEY) === "1";
3060
+ } catch (e) {
3061
+ return false;
3062
+ }
3063
+ }
3064
+ var STORAGE_PREFIX = "@core-ease/telegram-kit:fallback:";
3065
+ function createLocalStorageFallback(namespace) {
3066
+ const prefix = `${STORAGE_PREFIX}${namespace}:`;
3067
+ const hasLocalStorage = () => typeof window !== "undefined" && !!window.localStorage;
3068
+ return {
3069
+ async setItem(key, value) {
3070
+ if (!hasLocalStorage()) return false;
3071
+ try {
3072
+ window.localStorage.setItem(prefix + key, value);
3073
+ return true;
3074
+ } catch (e) {
3075
+ return false;
3076
+ }
3077
+ },
3078
+ async getItem(key) {
3079
+ if (!hasLocalStorage()) return void 0;
3080
+ try {
3081
+ const value = window.localStorage.getItem(prefix + key);
3082
+ return value === null ? void 0 : value;
3083
+ } catch (e) {
3084
+ return void 0;
3085
+ }
3086
+ },
3087
+ async getItems(keys) {
3088
+ const result = {};
3089
+ if (!hasLocalStorage()) return result;
3090
+ for (const key of keys) {
3091
+ try {
3092
+ const value = window.localStorage.getItem(prefix + key);
3093
+ if (value !== null) result[key] = value;
3094
+ } catch (e) {
3095
+ }
3096
+ }
3097
+ return result;
3098
+ },
3099
+ async removeItem(key) {
3100
+ if (!hasLocalStorage()) return false;
3101
+ try {
3102
+ window.localStorage.removeItem(prefix + key);
3103
+ return true;
3104
+ } catch (e) {
3105
+ return false;
3106
+ }
3107
+ },
3108
+ async removeItems(keys) {
3109
+ if (!hasLocalStorage()) return false;
3110
+ try {
3111
+ keys.forEach((key) => window.localStorage.removeItem(prefix + key));
3112
+ return true;
3113
+ } catch (e) {
3114
+ return false;
3115
+ }
3116
+ },
3117
+ async getKeys() {
3118
+ if (!hasLocalStorage()) return [];
3119
+ try {
3120
+ const keys = [];
3121
+ for (let i = 0; i < window.localStorage.length; i++) {
3122
+ const rawKey = window.localStorage.key(i);
3123
+ if (rawKey && rawKey.startsWith(prefix)) keys.push(rawKey.slice(prefix.length));
3124
+ }
3125
+ return keys;
3126
+ } catch (e) {
3127
+ return [];
3128
+ }
3129
+ },
3130
+ async clear() {
3131
+ if (!hasLocalStorage()) return false;
3132
+ try {
3133
+ const keys = await this.getKeys();
3134
+ keys.forEach((key) => window.localStorage.removeItem(prefix + key));
3135
+ return true;
3136
+ } catch (e) {
3137
+ return false;
3138
+ }
3139
+ }
3140
+ };
3141
+ }
3142
+ var HAPTIC_PATTERNS = {
3143
+ light: 10,
3144
+ medium: 20,
3145
+ heavy: 30,
3146
+ rigid: 15,
3147
+ soft: 10,
3148
+ success: [10, 30, 10],
3149
+ warning: [20, 40, 20],
3150
+ error: [30, 60, 30],
3151
+ selection: 5
3152
+ };
3153
+ function vibrateFallback(kind) {
3154
+ try {
3155
+ if (typeof navigator !== "undefined" && typeof navigator.vibrate === "function") {
3156
+ navigator.vibrate(HAPTIC_PATTERNS[kind]);
3157
+ }
3158
+ } catch (e) {
3159
+ }
3160
+ }
3161
+ function downloadFileFallback(url, fileName) {
3162
+ try {
3163
+ if (typeof document === "undefined") return false;
3164
+ const a = document.createElement("a");
3165
+ a.href = url;
3166
+ a.download = fileName;
3167
+ a.rel = "noopener";
3168
+ a.target = "_blank";
3169
+ document.body.appendChild(a);
3170
+ a.click();
3171
+ document.body.removeChild(a);
3172
+ return true;
3173
+ } catch (e) {
3174
+ return false;
3175
+ }
3176
+ }
3177
+ function getLocationFallback() {
3178
+ return new Promise((resolve) => {
3179
+ if (typeof navigator === "undefined" || !navigator.geolocation) {
3180
+ resolve(null);
3181
+ return;
3182
+ }
3183
+ navigator.geolocation.getCurrentPosition(
3184
+ (position) => {
3185
+ resolve({
3186
+ latitude: position.coords.latitude,
3187
+ longitude: position.coords.longitude,
3188
+ altitude: position.coords.altitude,
3189
+ course: position.coords.heading,
3190
+ speed: position.coords.speed,
3191
+ horizontal_accuracy: position.coords.accuracy,
3192
+ vertical_accuracy: position.coords.altitudeAccuracy,
3193
+ course_accuracy: null,
3194
+ speed_accuracy: null
3195
+ });
3196
+ },
3197
+ () => resolve(null),
3198
+ { enableHighAccuracy: false, timeout: 8e3, maximumAge: 6e4 }
3199
+ );
3200
+ });
3201
+ }
3202
+ async function readClipboardFallback() {
3203
+ var _a;
3204
+ try {
3205
+ if (typeof navigator !== "undefined" && ((_a = navigator.clipboard) == null ? void 0 : _a.readText)) {
3206
+ const text = await navigator.clipboard.readText();
3207
+ return text != null ? text : null;
3208
+ }
3209
+ } catch (e) {
3210
+ }
3211
+ return null;
3212
+ }
3213
+ function scanQrFallback(promptText) {
3214
+ if (typeof window === "undefined" || typeof window.prompt !== "function") return null;
3215
+ const value = window.prompt(promptText || "Enter the QR code value:");
3216
+ return value && value.length ? value : null;
3217
+ }
3218
+ async function shareTextFallback(text, url) {
3219
+ var _a;
3220
+ try {
3221
+ if (typeof navigator !== "undefined" && typeof navigator.share === "function") {
3222
+ await navigator.share({ text, url });
3223
+ return true;
3224
+ }
3225
+ } catch (e) {
3226
+ }
3227
+ try {
3228
+ if (typeof navigator !== "undefined" && ((_a = navigator.clipboard) == null ? void 0 : _a.writeText)) {
3229
+ await navigator.clipboard.writeText(url ? `${text}
3230
+ ${url}` : text);
3231
+ return true;
3232
+ }
3233
+ } catch (e) {
3234
+ }
3235
+ return false;
3236
+ }
3237
+ function callNativeOrFallback(options) {
3238
+ const { ready: ready2, native, fallback, timeoutMs = 4e3 } = options;
3239
+ if (!ready2) {
3240
+ try {
3241
+ return Promise.resolve(fallback());
3242
+ } catch (e) {
3243
+ return Promise.reject(e);
3244
+ }
3245
+ }
3246
+ return new Promise((resolve) => {
3247
+ let settled = false;
3248
+ const finish = async (useFallback, value) => {
3249
+ if (settled) return;
3250
+ settled = true;
3251
+ clearTimeout(timer);
3252
+ resolve(useFallback ? await fallback() : value);
3253
+ };
3254
+ const timer = setTimeout(() => finish(true), timeoutMs);
3255
+ try {
3256
+ native().then(
3257
+ (value) => finish(false, value),
3258
+ () => finish(true)
3259
+ );
3260
+ } catch (e) {
3261
+ finish(true);
3262
+ }
3263
+ });
3264
+ }
3265
+ async function orientationLockFallback(locked) {
3266
+ try {
3267
+ const orientation2 = typeof screen !== "undefined" ? screen.orientation : void 0;
3268
+ if (!orientation2) return false;
3269
+ if (locked) {
3270
+ await orientation2.lock("portrait");
3271
+ } else if (typeof orientation2.unlock === "function") {
3272
+ orientation2.unlock();
3273
+ }
3274
+ return true;
3275
+ } catch (e) {
3276
+ return false;
3277
+ }
3278
+ }
3279
+ async function fullscreenFallback(enter, el) {
3280
+ var _a, _b;
3281
+ try {
3282
+ if (typeof document === "undefined") return false;
3283
+ if (enter) {
3284
+ const target = el != null ? el : document.documentElement;
3285
+ await ((_a = target.requestFullscreen) == null ? void 0 : _a.call(target));
3286
+ } else if (document.fullscreenElement) {
3287
+ await ((_b = document.exitFullscreen) == null ? void 0 : _b.call(document));
3288
+ }
3289
+ return true;
3290
+ } catch (e) {
3291
+ return false;
3292
+ }
3293
+ }
3294
+ function safeInvoke(fn) {
3295
+ try {
3296
+ fn();
3297
+ } catch (e) {
3298
+ }
3299
+ }
3300
+
3301
+ // src/core/index.ts
3302
+ var cachedWebApp = null;
3303
+ function getWebApp() {
3304
+ if (typeof window === "undefined") return null;
3305
+ if (!cachedWebApp) {
3306
+ cachedWebApp = bootstrapTelegramWebApp().webApp;
3307
+ }
3308
+ return cachedWebApp;
3309
+ }
3310
+ function isInTelegram() {
3311
+ const wa = getWebApp();
3312
+ return Boolean(wa && wa.initData && wa.initData.length > 0);
3313
+ }
3314
+ function isVersionAtLeast(version) {
3315
+ var _a, _b;
3316
+ return (_b = (_a = getWebApp()) == null ? void 0 : _a.isVersionAtLeast(version)) != null ? _b : false;
3317
+ }
3318
+ function nativeReady(version) {
3319
+ if (!isInTelegram()) return false;
3320
+ if (isDevModeActive()) return false;
3321
+ if (version && !isVersionAtLeast(version)) return false;
3322
+ return true;
3323
+ }
3324
+ function getRawUserData() {
3325
+ var _a, _b, _c;
3326
+ return (_c = (_b = (_a = getWebApp()) == null ? void 0 : _a.initDataUnsafe) == null ? void 0 : _b.user) != null ? _c : null;
3327
+ }
3328
+ function getUserDisplayName(user) {
3329
+ var _a, _b;
3330
+ if (!user) return "User";
3331
+ const fullName = `${(_a = user.first_name) != null ? _a : ""} ${(_b = user.last_name) != null ? _b : ""}`.trim();
3332
+ if (fullName) return fullName;
3333
+ if (user.username) return `@${user.username}`;
3334
+ return `User_${user.id}`;
3335
+ }
3336
+ function getUserIdentifier(user) {
3337
+ if (user == null ? void 0 : user.username) return user.username;
3338
+ if (user == null ? void 0 : user.id) return String(user.id);
3339
+ return "unknown";
3340
+ }
3341
+ function getUserAvatarUrl(user, fallback = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjNjY2Ii8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGRvbWluYW50LWJhc2VsaW5lPSJtaWRkbGUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZvbnQtc2l6ZT0iNDAiIGZpbGw9IndoaXRlIj4/PC90ZXh0Pjwvc3ZnPg==") {
3342
+ var _a, _b;
3343
+ if (user == null ? void 0 : user.photo_url) return user.photo_url;
3344
+ if (user == null ? void 0 : user.id) {
3345
+ const name = `${(_a = user.first_name) != null ? _a : ""} ${(_b = user.last_name) != null ? _b : ""}`.trim() || user.username || `user_${user.id}`;
3346
+ const initials = name.split(/\s+/).slice(0, 2).map((part) => {
3347
+ var _a2, _b2;
3348
+ return (_b2 = (_a2 = part[0]) == null ? void 0 : _a2.toUpperCase()) != null ? _b2 : "";
3349
+ }).join("");
3350
+ const svg = `
3351
+ <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
3352
+ <rect width="100%" height="100%" rx="50" fill="#4F46E5"/>
3353
+ <text
3354
+ x="50%"
3355
+ y="50%"
3356
+ dominant-baseline="middle"
3357
+ text-anchor="middle"
3358
+ font-family="Arial,sans-serif"
3359
+ font-size="40"
3360
+ font-weight="bold"
3361
+ fill="white"
3362
+ >
3363
+ ${initials}
3364
+ </text>
3365
+ </svg>
3366
+ `;
3367
+ const base64 = typeof Buffer !== "undefined" ? Buffer.from(svg).toString("base64") : btoa(svg);
3368
+ return `data:image/svg+xml;base64,${base64}`;
3369
+ }
3370
+ return fallback;
3371
+ }
3372
+ function getUserInfoWithAvatar() {
3373
+ var _a;
3374
+ const user = (_a = getRawUserData()) != null ? _a : void 0;
3375
+ return {
3376
+ user,
3377
+ avatarUrl: getUserAvatarUrl(user),
3378
+ displayName: getUserDisplayName(user),
3379
+ identifier: getUserIdentifier(user)
3380
+ };
3381
+ }
3382
+ function openExternalLink(url, tryInstantView = false) {
3383
+ const wa = getWebApp();
3384
+ if (!wa) {
3385
+ if (typeof window !== "undefined") window.open(url, "_blank", "noopener");
3386
+ return;
3387
+ }
3388
+ wa.openLink(url, { try_instant_view: tryInstantView });
3389
+ }
3390
+ function openTelegramLink(url) {
3391
+ const wa = getWebApp();
3392
+ if (!wa) {
3393
+ if (typeof window !== "undefined") window.open(url, "_blank", "noopener");
3394
+ return;
3395
+ }
3396
+ wa.openTelegramLink(url);
3397
+ }
3398
+ function openInvoice(url) {
3399
+ return callNativeOrFallback({
3400
+ ready: nativeReady("6.1"),
3401
+ native: () => new Promise((resolve) => getWebApp().openInvoice(url, (status) => resolve(status))),
3402
+ fallback: () => {
3403
+ throw new Error("openInvoice requires the Telegram app (Bot API 6.1+).");
3404
+ }
3405
+ });
3406
+ }
3407
+ function switchInlineQuery(query, chooseChatTypes) {
3408
+ if (!nativeReady("6.6")) return;
3409
+ safeInvoke(() => getWebApp().switchInlineQuery(query, chooseChatTypes));
3410
+ }
3411
+ function hideKeyboard() {
3412
+ safeInvoke(() => {
3413
+ var _a;
3414
+ return (_a = getWebApp()) == null ? void 0 : _a.hideKeyboard();
3415
+ });
3416
+ }
3417
+ function getTheme() {
3418
+ var _a, _b;
3419
+ const wa = getWebApp();
3420
+ return { colorScheme: (_a = wa == null ? void 0 : wa.colorScheme) != null ? _a : "dark", themeParams: (_b = wa == null ? void 0 : wa.themeParams) != null ? _b : {} };
3421
+ }
3422
+ function getViewport() {
3423
+ var _a, _b, _c;
3424
+ const wa = getWebApp();
3425
+ return {
3426
+ height: (_a = wa == null ? void 0 : wa.viewportHeight) != null ? _a : typeof window !== "undefined" ? window.innerHeight : 0,
3427
+ stableHeight: (_b = wa == null ? void 0 : wa.viewportStableHeight) != null ? _b : typeof window !== "undefined" ? window.innerHeight : 0,
3428
+ isExpanded: (_c = wa == null ? void 0 : wa.isExpanded) != null ? _c : true
3429
+ };
3430
+ }
3431
+ function expand() {
3432
+ safeInvoke(() => {
3433
+ var _a;
3434
+ return (_a = getWebApp()) == null ? void 0 : _a.expand();
3435
+ });
3436
+ }
3437
+ function ready() {
3438
+ safeInvoke(() => {
3439
+ var _a;
3440
+ return (_a = getWebApp()) == null ? void 0 : _a.ready();
3441
+ });
3442
+ }
3443
+ function close() {
3444
+ safeInvoke(() => {
3445
+ var _a;
3446
+ return (_a = getWebApp()) == null ? void 0 : _a.close();
3447
+ });
3448
+ }
3449
+ var fullscreen = {
3450
+ enter: () => {
3451
+ if (nativeReady("8.0")) {
3452
+ safeInvoke(() => getWebApp().requestFullscreen());
3453
+ return Promise.resolve(true);
3454
+ }
3455
+ return fullscreenFallback(true);
3456
+ },
3457
+ exit: () => {
3458
+ if (nativeReady("8.0")) {
3459
+ safeInvoke(() => getWebApp().exitFullscreen());
3460
+ return Promise.resolve(true);
3461
+ }
3462
+ return fullscreenFallback(false);
3463
+ }
3464
+ };
3465
+ var orientation = {
3466
+ lock: () => {
3467
+ if (nativeReady("8.0")) {
3468
+ safeInvoke(() => getWebApp().lockOrientation());
3469
+ return Promise.resolve(true);
3470
+ }
3471
+ return orientationLockFallback(true);
3472
+ },
3473
+ unlock: () => {
3474
+ if (nativeReady("8.0")) {
3475
+ safeInvoke(() => getWebApp().unlockOrientation());
3476
+ return Promise.resolve(true);
3477
+ }
3478
+ return orientationLockFallback(false);
3479
+ }
3480
+ };
3481
+ function enableClosingConfirmation() {
3482
+ safeInvoke(() => {
3483
+ var _a;
3484
+ return (_a = getWebApp()) == null ? void 0 : _a.enableClosingConfirmation();
3485
+ });
3486
+ }
3487
+ function disableClosingConfirmation() {
3488
+ safeInvoke(() => {
3489
+ var _a;
3490
+ return (_a = getWebApp()) == null ? void 0 : _a.disableClosingConfirmation();
3491
+ });
3492
+ }
3493
+ function enableVerticalSwipes() {
3494
+ safeInvoke(() => {
3495
+ var _a;
3496
+ return (_a = getWebApp()) == null ? void 0 : _a.enableVerticalSwipes();
3497
+ });
3498
+ }
3499
+ function disableVerticalSwipes() {
3500
+ safeInvoke(() => {
3501
+ var _a;
3502
+ return (_a = getWebApp()) == null ? void 0 : _a.disableVerticalSwipes();
3503
+ });
3504
+ }
3505
+ function setHeaderColor(color) {
3506
+ safeInvoke(() => {
3507
+ var _a;
3508
+ return (_a = getWebApp()) == null ? void 0 : _a.setHeaderColor(color);
3509
+ });
3510
+ }
3511
+ function setBackgroundColor(color) {
3512
+ safeInvoke(() => {
3513
+ var _a;
3514
+ return (_a = getWebApp()) == null ? void 0 : _a.setBackgroundColor(color);
3515
+ });
3516
+ }
3517
+ function setBottomBarColor(color) {
3518
+ safeInvoke(() => {
3519
+ var _a;
3520
+ return (_a = getWebApp()) == null ? void 0 : _a.setBottomBarColor(color);
3521
+ });
3522
+ }
3523
+ function addToHomeScreen() {
3524
+ if (!nativeReady("8.0")) return;
3525
+ safeInvoke(() => getWebApp().addToHomeScreen());
3526
+ }
3527
+ function checkHomeScreenStatus() {
3528
+ return callNativeOrFallback({
3529
+ ready: nativeReady("8.0"),
3530
+ native: () => new Promise((resolve) => getWebApp().checkHomeScreenStatus((status) => resolve(status))),
3531
+ fallback: () => "unsupported"
3532
+ });
3533
+ }
3534
+ var haptic = {
3535
+ light: () => nativeReady("6.1") ? getWebApp().HapticFeedback.impactOccurred("light") : vibrateFallback("light"),
3536
+ medium: () => nativeReady("6.1") ? getWebApp().HapticFeedback.impactOccurred("medium") : vibrateFallback("medium"),
3537
+ heavy: () => nativeReady("6.1") ? getWebApp().HapticFeedback.impactOccurred("heavy") : vibrateFallback("heavy"),
3538
+ rigid: () => nativeReady("6.1") ? getWebApp().HapticFeedback.impactOccurred("rigid") : vibrateFallback("rigid"),
3539
+ soft: () => nativeReady("6.1") ? getWebApp().HapticFeedback.impactOccurred("soft") : vibrateFallback("soft"),
3540
+ success: () => nativeReady("6.1") ? getWebApp().HapticFeedback.notificationOccurred("success") : vibrateFallback("success"),
3541
+ warning: () => nativeReady("6.1") ? getWebApp().HapticFeedback.notificationOccurred("warning") : vibrateFallback("warning"),
3542
+ error: () => nativeReady("6.1") ? getWebApp().HapticFeedback.notificationOccurred("error") : vibrateFallback("error"),
3543
+ selection: () => nativeReady("6.1") ? getWebApp().HapticFeedback.selectionChanged() : vibrateFallback("selection")
3544
+ };
3545
+ var cloudStorageFallback = createLocalStorageFallback("cloud");
3546
+ var deviceStorageFallback = createLocalStorageFallback("device");
3547
+ var secureStorageFallback = createLocalStorageFallback("secure");
3548
+ var cloudStorage = {
3549
+ setItem: (key, value) => callNativeOrFallback({
3550
+ ready: nativeReady("6.9"),
3551
+ native: () => new Promise((resolve, reject) => getWebApp().CloudStorage.setItem(key, value, (e, ok) => e ? reject(new Error(e)) : resolve(ok != null ? ok : false))),
3552
+ fallback: () => cloudStorageFallback.setItem(key, value)
3553
+ }),
3554
+ getItem: (key) => callNativeOrFallback({
3555
+ ready: nativeReady("6.9"),
3556
+ native: () => new Promise((resolve, reject) => getWebApp().CloudStorage.getItem(key, (e, v) => e ? reject(new Error(e)) : resolve(v))),
3557
+ fallback: () => cloudStorageFallback.getItem(key)
3558
+ }),
3559
+ getItems: (keys) => callNativeOrFallback({
3560
+ ready: nativeReady("6.9"),
3561
+ native: () => new Promise((resolve, reject) => getWebApp().CloudStorage.getItems(keys, (e, v) => e ? reject(new Error(e)) : resolve(v != null ? v : {}))),
3562
+ fallback: () => cloudStorageFallback.getItems(keys)
3563
+ }),
3564
+ removeItem: (key) => callNativeOrFallback({
3565
+ ready: nativeReady("6.9"),
3566
+ native: () => new Promise((resolve, reject) => getWebApp().CloudStorage.removeItem(key, (e, ok) => e ? reject(new Error(e)) : resolve(ok != null ? ok : false))),
3567
+ fallback: () => cloudStorageFallback.removeItem(key)
3568
+ }),
3569
+ removeItems: (keys) => callNativeOrFallback({
3570
+ ready: nativeReady("6.9"),
3571
+ native: () => new Promise((resolve, reject) => getWebApp().CloudStorage.removeItems(keys, (e, ok) => e ? reject(new Error(e)) : resolve(ok != null ? ok : false))),
3572
+ fallback: () => cloudStorageFallback.removeItems(keys)
3573
+ }),
3574
+ getKeys: () => callNativeOrFallback({
3575
+ ready: nativeReady("6.9"),
3576
+ native: () => new Promise((resolve, reject) => getWebApp().CloudStorage.getKeys((e, keys) => e ? reject(new Error(e)) : resolve(keys != null ? keys : []))),
3577
+ fallback: () => cloudStorageFallback.getKeys()
3578
+ })
3579
+ };
3580
+ var deviceStorage = {
3581
+ setItem: (key, value) => callNativeOrFallback({
3582
+ ready: nativeReady("9.0"),
3583
+ native: () => new Promise((resolve, reject) => getWebApp().DeviceStorage.setItem(key, value, (e, ok) => e ? reject(new Error(e)) : resolve(ok != null ? ok : false))),
3584
+ fallback: () => deviceStorageFallback.setItem(key, value)
3585
+ }),
3586
+ getItem: (key) => callNativeOrFallback({
3587
+ ready: nativeReady("9.0"),
3588
+ native: () => new Promise((resolve, reject) => getWebApp().DeviceStorage.getItem(key, (e, v) => e ? reject(new Error(e)) : resolve(v))),
3589
+ fallback: () => deviceStorageFallback.getItem(key)
3590
+ }),
3591
+ removeItem: (key) => callNativeOrFallback({
3592
+ ready: nativeReady("9.0"),
3593
+ native: () => new Promise((resolve, reject) => getWebApp().DeviceStorage.removeItem(key, (e, ok) => e ? reject(new Error(e)) : resolve(ok != null ? ok : false))),
3594
+ fallback: () => deviceStorageFallback.removeItem(key)
3595
+ }),
3596
+ clear: () => callNativeOrFallback({
3597
+ ready: nativeReady("9.0"),
3598
+ native: () => new Promise((resolve, reject) => getWebApp().DeviceStorage.clear((e, ok) => e ? reject(new Error(e)) : resolve(ok != null ? ok : false))),
3599
+ fallback: () => deviceStorageFallback.clear()
3600
+ })
3601
+ };
3602
+ var secureStorage = {
3603
+ setItem: (key, value) => callNativeOrFallback({
3604
+ ready: nativeReady("9.0"),
3605
+ native: () => new Promise((resolve, reject) => getWebApp().SecureStorage.setItem(key, value, (e, ok) => e ? reject(new Error(e)) : resolve(ok != null ? ok : false))),
3606
+ fallback: () => secureStorageFallback.setItem(key, value)
3607
+ }),
3608
+ getItem: (key) => callNativeOrFallback({
3609
+ ready: nativeReady("9.0"),
3610
+ native: () => new Promise(
3611
+ (resolve, reject) => getWebApp().SecureStorage.getItem(key, (e, v, canRestore) => e ? reject(new Error(e)) : resolve({ value: v, canRestore: canRestore != null ? canRestore : false }))
3612
+ ),
3613
+ fallback: async () => ({ value: await secureStorageFallback.getItem(key), canRestore: false })
3614
+ }),
3615
+ removeItem: (key) => callNativeOrFallback({
3616
+ ready: nativeReady("9.0"),
3617
+ native: () => new Promise((resolve, reject) => getWebApp().SecureStorage.removeItem(key, (e, ok) => e ? reject(new Error(e)) : resolve(ok != null ? ok : false))),
3618
+ fallback: () => secureStorageFallback.removeItem(key)
3619
+ }),
3620
+ clear: () => callNativeOrFallback({
3621
+ ready: nativeReady("9.0"),
3622
+ native: () => new Promise((resolve, reject) => getWebApp().SecureStorage.clear((e, ok) => e ? reject(new Error(e)) : resolve(ok != null ? ok : false))),
3623
+ fallback: () => secureStorageFallback.clear()
3624
+ }),
3625
+ restoreItem: (key) => callNativeOrFallback({
3626
+ ready: nativeReady("9.0"),
3627
+ native: () => new Promise((resolve, reject) => getWebApp().SecureStorage.restoreItem(key, (e, v) => e ? reject(new Error(e)) : resolve(v))),
3628
+ fallback: () => secureStorageFallback.getItem(key)
3629
+ })
3630
+ };
3631
+ var dialog = {
3632
+ alert: (message) => callNativeOrFallback({
3633
+ ready: nativeReady("6.2"),
3634
+ native: () => new Promise((resolve) => getWebApp().showAlert(message, resolve)),
3635
+ fallback: () => {
3636
+ if (typeof window !== "undefined") window.alert(message);
3637
+ }
3638
+ }),
3639
+ confirm: (message) => callNativeOrFallback({
3640
+ ready: nativeReady("6.2"),
3641
+ native: () => new Promise((resolve) => getWebApp().showConfirm(message, resolve)),
3642
+ fallback: () => typeof window !== "undefined" && window.confirm(message)
3643
+ }),
3644
+ popup: (params) => callNativeOrFallback({
3645
+ ready: nativeReady("6.2"),
3646
+ native: () => new Promise((resolve) => getWebApp().showPopup(params, (buttonId) => resolve(buttonId != null ? buttonId : null))),
3647
+ fallback: () => {
3648
+ var _a;
3649
+ if (typeof window === "undefined") return null;
3650
+ const okButton = (_a = params.buttons) == null ? void 0 : _a.find((b) => b.type === "ok" || b.type === "default");
3651
+ const okButtonId = (okButton == null ? void 0 : okButton.id) != null ? String(okButton.id) : null;
3652
+ if (params.buttons && params.buttons.length > 1) {
3653
+ const ok = window.confirm(`${params.title ? params.title + "\n" : ""}${params.message}`);
3654
+ return ok ? okButtonId != null ? okButtonId : "ok" : null;
3655
+ }
3656
+ window.alert(`${params.title ? params.title + "\n" : ""}${params.message}`);
3657
+ return okButtonId;
3658
+ }
3659
+ }),
3660
+ prompt: (message, defaultValue = "") => Promise.resolve(typeof window === "undefined" ? null : window.prompt(message, defaultValue))
3661
+ };
3662
+ function readClipboard() {
3663
+ return callNativeOrFallback({
3664
+ ready: nativeReady("6.4"),
3665
+ native: () => new Promise((resolve) => getWebApp().readTextFromClipboard((text) => resolve(text != null ? text : null))),
3666
+ fallback: () => readClipboardFallback()
3667
+ });
3668
+ }
3669
+ function scanQr(text) {
3670
+ return callNativeOrFallback({
3671
+ ready: nativeReady("6.4"),
3672
+ native: () => new Promise((resolve) => {
3673
+ const wa = getWebApp();
3674
+ wa.showScanQrPopup({ text }, (result) => {
3675
+ wa.closeScanQrPopup();
3676
+ resolve(result);
3677
+ return true;
3678
+ });
3679
+ }),
3680
+ fallback: () => scanQrFallback(text)
3681
+ });
3682
+ }
3683
+ function shareToStory(mediaUrl, params) {
3684
+ if (!nativeReady("7.8")) return;
3685
+ safeInvoke(() => getWebApp().shareToStory(mediaUrl, params));
3686
+ }
3687
+ function shareMessage(msgId) {
3688
+ return callNativeOrFallback({
3689
+ ready: nativeReady("8.0"),
3690
+ native: () => new Promise((resolve) => getWebApp().shareMessage(msgId, resolve)),
3691
+ fallback: () => shareTextFallback(msgId)
3692
+ });
3693
+ }
3694
+ function downloadFile(params) {
3695
+ return callNativeOrFallback({
3696
+ ready: nativeReady("8.0"),
3697
+ native: () => new Promise((resolve) => getWebApp().downloadFile(params, resolve)),
3698
+ fallback: () => downloadFileFallback(params.url, params.file_name)
3699
+ });
3700
+ }
3701
+ function setEmojiStatus(customEmojiId, params) {
3702
+ return callNativeOrFallback({
3703
+ ready: nativeReady("8.0"),
3704
+ native: () => new Promise((resolve) => getWebApp().setEmojiStatus(customEmojiId, params, resolve)),
3705
+ fallback: () => false
3706
+ });
3707
+ }
3708
+ function requestEmojiStatusAccess() {
3709
+ return callNativeOrFallback({
3710
+ ready: nativeReady("8.0"),
3711
+ native: () => new Promise((resolve) => getWebApp().requestEmojiStatusAccess(resolve)),
3712
+ fallback: () => false
3713
+ });
3714
+ }
3715
+ function requestWriteAccess() {
3716
+ return callNativeOrFallback({
3717
+ ready: nativeReady("6.9"),
3718
+ native: () => new Promise((resolve) => getWebApp().requestWriteAccess(resolve)),
3719
+ fallback: () => false
3720
+ });
3721
+ }
3722
+ function requestContact() {
3723
+ return callNativeOrFallback({
3724
+ ready: nativeReady("6.9"),
3725
+ native: () => new Promise((resolve) => getWebApp().requestContact(resolve)),
3726
+ fallback: () => false
3727
+ });
3728
+ }
3729
+ function requestChat(reqId) {
3730
+ return callNativeOrFallback({
3731
+ ready: nativeReady("9.6"),
3732
+ native: () => new Promise((resolve) => getWebApp().requestChat(reqId, resolve)),
3733
+ fallback: () => false
3734
+ });
3735
+ }
3736
+ function invokeCustomMethod(method, params = {}) {
3737
+ return callNativeOrFallback({
3738
+ ready: nativeReady("6.9"),
3739
+ native: () => new Promise((resolve, reject) => getWebApp().invokeCustomMethod(method, params, (e, r) => e ? reject(new Error(e)) : resolve(r))),
3740
+ fallback: () => {
3741
+ throw new Error("invokeCustomMethod requires the Telegram app (Bot API 6.9+).");
3742
+ }
3743
+ });
3744
+ }
3745
+ var biometric = {
3746
+ init: () => callNativeOrFallback({
3747
+ ready: nativeReady("7.2"),
3748
+ native: () => new Promise((resolve) => getWebApp().BiometricManager.init(resolve)),
3749
+ fallback: () => void 0
3750
+ }),
3751
+ requestAccess: (reason) => callNativeOrFallback({
3752
+ ready: nativeReady("7.2"),
3753
+ native: () => new Promise((resolve) => getWebApp().BiometricManager.requestAccess({ reason }, resolve)),
3754
+ fallback: () => false
3755
+ }),
3756
+ authenticate: (reason) => callNativeOrFallback({
3757
+ ready: nativeReady("7.2"),
3758
+ native: () => new Promise(
3759
+ (resolve) => getWebApp().BiometricManager.authenticate({ reason }, (authenticated, token) => resolve({ authenticated, token: token != null ? token : void 0 }))
3760
+ ),
3761
+ fallback: () => ({ authenticated: false })
3762
+ }),
3763
+ updateBiometricToken: (token) => callNativeOrFallback({
3764
+ ready: nativeReady("7.2"),
3765
+ native: () => new Promise((resolve) => getWebApp().BiometricManager.updateBiometricToken(token, resolve)),
3766
+ fallback: () => false
3767
+ }),
3768
+ openSettings: () => {
3769
+ if (!nativeReady("7.2")) return;
3770
+ safeInvoke(() => getWebApp().BiometricManager.openSettings());
3771
+ }
3772
+ };
3773
+ var location2 = {
3774
+ init: () => callNativeOrFallback({
3775
+ ready: nativeReady("8.0"),
3776
+ native: () => new Promise((resolve) => getWebApp().LocationManager.init(() => resolve())),
3777
+ fallback: () => void 0
3778
+ }),
3779
+ getLocation: () => callNativeOrFallback({
3780
+ ready: nativeReady("8.0"),
3781
+ native: () => new Promise((resolve) => getWebApp().LocationManager.getLocation((data) => resolve(data))),
3782
+ fallback: () => getLocationFallback()
3783
+ }),
3784
+ openSettings: () => {
3785
+ if (!nativeReady("8.0")) return;
3786
+ safeInvoke(() => getWebApp().LocationManager.openSettings());
3787
+ }
3788
+ };
3789
+
3790
+ exports.addToHomeScreen = addToHomeScreen;
3791
+ exports.biometric = biometric;
3792
+ exports.checkHomeScreenStatus = checkHomeScreenStatus;
3793
+ exports.close = close;
3794
+ exports.cloudStorage = cloudStorage;
3795
+ exports.deviceStorage = deviceStorage;
3796
+ exports.dialog = dialog;
3797
+ exports.disableClosingConfirmation = disableClosingConfirmation;
3798
+ exports.disableVerticalSwipes = disableVerticalSwipes;
3799
+ exports.downloadFile = downloadFile;
3800
+ exports.enableClosingConfirmation = enableClosingConfirmation;
3801
+ exports.enableVerticalSwipes = enableVerticalSwipes;
3802
+ exports.expand = expand;
3803
+ exports.fullscreen = fullscreen;
3804
+ exports.getRawUserData = getRawUserData;
3805
+ exports.getTheme = getTheme;
3806
+ exports.getUserAvatarUrl = getUserAvatarUrl;
3807
+ exports.getUserDisplayName = getUserDisplayName;
3808
+ exports.getUserIdentifier = getUserIdentifier;
3809
+ exports.getUserInfoWithAvatar = getUserInfoWithAvatar;
3810
+ exports.getViewport = getViewport;
3811
+ exports.getWebApp = getWebApp;
3812
+ exports.haptic = haptic;
3813
+ exports.hideKeyboard = hideKeyboard;
3814
+ exports.invokeCustomMethod = invokeCustomMethod;
3815
+ exports.isInTelegram = isInTelegram;
3816
+ exports.isVersionAtLeast = isVersionAtLeast;
3817
+ exports.location = location2;
3818
+ exports.openExternalLink = openExternalLink;
3819
+ exports.openInvoice = openInvoice;
3820
+ exports.openTelegramLink = openTelegramLink;
3821
+ exports.orientation = orientation;
3822
+ exports.readClipboard = readClipboard;
3823
+ exports.ready = ready;
3824
+ exports.requestChat = requestChat;
3825
+ exports.requestContact = requestContact;
3826
+ exports.requestEmojiStatusAccess = requestEmojiStatusAccess;
3827
+ exports.requestWriteAccess = requestWriteAccess;
3828
+ exports.safeInvoke = safeInvoke;
3829
+ exports.scanQr = scanQr;
3830
+ exports.secureStorage = secureStorage;
3831
+ exports.setBackgroundColor = setBackgroundColor;
3832
+ exports.setBottomBarColor = setBottomBarColor;
3833
+ exports.setEmojiStatus = setEmojiStatus;
3834
+ exports.setHeaderColor = setHeaderColor;
3835
+ exports.shareMessage = shareMessage;
3836
+ exports.shareToStory = shareToStory;
3837
+ exports.switchInlineQuery = switchInlineQuery;