@tma.js/bridge 1.4.1 → 2.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.
- package/LICENSE +1 -1
- package/README.md +44 -13
- package/dist/dts/applyPolyfills.d.ts +5 -0
- package/dist/dts/base64-url.d.ts +24 -0
- package/dist/dts/env/hasWebviewProxy.d.ts +10 -0
- package/dist/dts/env/isIframe.d.ts +5 -0
- package/dist/dts/env/isTMA.d.ts +31 -0
- package/dist/dts/env/mockTelegramEnv.d.ts +57 -0
- package/dist/dts/errors.d.ts +27 -0
- package/dist/dts/events/createEmitter.d.ts +58 -0
- package/dist/dts/events/emitEvent.d.ts +33 -0
- package/dist/dts/events/emitter.d.ts +2 -11
- package/dist/dts/events/types/events.d.ts +721 -0
- package/dist/dts/events/types/index.d.ts +3 -0
- package/dist/dts/events/types/listening.d.ts +5 -0
- package/dist/dts/events/types/misc.d.ts +16 -0
- package/dist/dts/globals.d.ts +45 -14
- package/dist/dts/index.d.ts +24 -7
- package/dist/dts/launch-params.d.ts +32 -0
- package/dist/dts/methods/captureSameReq.d.ts +10 -0
- package/dist/dts/methods/createPostEvent.d.ts +27 -7
- package/dist/dts/methods/postEvent.d.ts +31 -25
- package/dist/dts/methods/postMessage.d.ts +7 -0
- package/dist/dts/methods/supports.d.ts +15 -0
- package/dist/dts/methods/types/custom-method.d.ts +59 -0
- package/dist/dts/methods/types/index.d.ts +6 -0
- package/dist/dts/methods/types/methods.d.ts +756 -0
- package/dist/dts/methods/types/misc.d.ts +27 -0
- package/dist/dts/methods/{popup.d.ts → types/popup.d.ts} +1 -1
- package/dist/dts/methods/types/utils.d.ts +9 -0
- package/dist/dts/obj-prop-helpers.d.ts +39 -0
- package/dist/dts/start-param.d.ts +53 -0
- package/dist/dts/utils/compareVersions.d.ts +10 -0
- package/dist/dts/utils/invokeCustomMethod.d.ts +34 -0
- package/dist/dts/utils/request.d.ts +90 -0
- package/dist/index.cjs +3 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.iife.js +3 -1
- package/dist/index.iife.js.map +1 -1
- package/dist/index.js +977 -0
- package/dist/index.js.map +1 -0
- package/package.json +26 -26
- package/dist/dts/env.d.ts +0 -29
- package/dist/dts/errors/MethodUnsupportedError.d.ts +0 -8
- package/dist/dts/errors/ParameterUnsupportedError.d.ts +0 -8
- package/dist/dts/errors/index.d.ts +0 -2
- package/dist/dts/events/events.d.ts +0 -130
- package/dist/dts/events/index.d.ts +0 -7
- package/dist/dts/events/off.d.ts +0 -7
- package/dist/dts/events/on.d.ts +0 -10
- package/dist/dts/events/onTelegramEvent.d.ts +0 -7
- package/dist/dts/events/once.d.ts +0 -9
- package/dist/dts/events/parsers/clipboardTextReceived.d.ts +0 -13
- package/dist/dts/events/parsers/customMethodInvoked.d.ts +0 -16
- package/dist/dts/events/parsers/index.d.ts +0 -9
- package/dist/dts/events/parsers/invoiceClosed.d.ts +0 -12
- package/dist/dts/events/parsers/phoneRequested.d.ts +0 -8
- package/dist/dts/events/parsers/popupClosed.d.ts +0 -8
- package/dist/dts/events/parsers/qrTextReceived.d.ts +0 -7
- package/dist/dts/events/parsers/theme-changed.d.ts +0 -42
- package/dist/dts/events/parsers/viewportChanged.d.ts +0 -19
- package/dist/dts/events/parsers/writeAccessRequested.d.ts +0 -8
- package/dist/dts/events/subscribe.d.ts +0 -9
- package/dist/dts/events/unsubscribe.d.ts +0 -6
- package/dist/dts/methods/index.d.ts +0 -6
- package/dist/dts/methods/invoke-custom-method.d.ts +0 -24
- package/dist/dts/methods/methods.d.ts +0 -330
- package/dist/dts/request.d.ts +0 -66
- package/dist/dts/shared.d.ts +0 -5
- package/dist/dts/supports.d.ts +0 -15
- package/dist/index.mjs +0 -317
- package/dist/index.mjs.map +0 -1
- package/src/env.ts +0 -49
- package/src/errors/MethodUnsupportedError.ts +0 -13
- package/src/errors/ParameterUnsupportedError.ts +0 -13
- package/src/errors/index.ts +0 -2
- package/src/events/emitter.ts +0 -126
- package/src/events/events.ts +0 -169
- package/src/events/index.ts +0 -7
- package/src/events/off.ts +0 -12
- package/src/events/on.ts +0 -17
- package/src/events/onTelegramEvent.ts +0 -83
- package/src/events/once.ts +0 -16
- package/src/events/parsers/clipboardTextReceived.ts +0 -27
- package/src/events/parsers/customMethodInvoked.ts +0 -26
- package/src/events/parsers/index.ts +0 -9
- package/src/events/parsers/invoiceClosed.ts +0 -26
- package/src/events/parsers/phoneRequested.ts +0 -14
- package/src/events/parsers/popupClosed.ts +0 -19
- package/src/events/parsers/qrTextReceived.ts +0 -14
- package/src/events/parsers/theme-changed.ts +0 -58
- package/src/events/parsers/viewportChanged.ts +0 -33
- package/src/events/parsers/writeAccessRequested.ts +0 -14
- package/src/events/subscribe.ts +0 -16
- package/src/events/unsubscribe.ts +0 -11
- package/src/globals.ts +0 -38
- package/src/index.ts +0 -7
- package/src/methods/createPostEvent.ts +0 -39
- package/src/methods/haptic.ts +0 -52
- package/src/methods/index.ts +0 -6
- package/src/methods/invoke-custom-method.ts +0 -25
- package/src/methods/methods.ts +0 -373
- package/src/methods/popup.ts +0 -53
- package/src/methods/postEvent.ts +0 -101
- package/src/request.ts +0 -168
- package/src/shared.ts +0 -5
- package/src/supports.ts +0 -82
- /package/dist/dts/methods/{haptic.d.ts → types/haptic-feedback.d.ts} +0 -0
package/dist/index.mjs
DELETED
|
@@ -1,317 +0,0 @@
|
|
|
1
|
-
import { compareVersions as J, isRecord as p, withTimeout as L } from "@tma.js/utils";
|
|
2
|
-
import { Logger as N } from "@tma.js/logger";
|
|
3
|
-
import { EventEmitter as T } from "@tma.js/event-emitter";
|
|
4
|
-
import { json as s, string as o, rgb as j, toRecord as I, number as q, boolean as v } from "@tma.js/parsing";
|
|
5
|
-
class b extends Error {
|
|
6
|
-
constructor(t, r) {
|
|
7
|
-
super(`Method "${t}" is unsupported in the Mini Apps version ${r}.`), Object.setPrototypeOf(this, b.prototype);
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
|
-
class h extends Error {
|
|
11
|
-
constructor(t, r, n) {
|
|
12
|
-
super(`Parameter "${r}" in method "${t}" is unsupported in the Mini Apps version ${n}.`), Object.setPrototypeOf(this, h.prototype);
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
function S() {
|
|
16
|
-
return s({
|
|
17
|
-
req_id: o(),
|
|
18
|
-
data: (e) => e === null ? e : o().optional().parse(e)
|
|
19
|
-
});
|
|
20
|
-
}
|
|
21
|
-
function G() {
|
|
22
|
-
return s({
|
|
23
|
-
req_id: o(),
|
|
24
|
-
result: (e) => e,
|
|
25
|
-
error: o().optional()
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
|
-
function H() {
|
|
29
|
-
return s({
|
|
30
|
-
slug: o(),
|
|
31
|
-
status: o()
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
function z() {
|
|
35
|
-
return s({ status: o() });
|
|
36
|
-
}
|
|
37
|
-
function B() {
|
|
38
|
-
return s({
|
|
39
|
-
button_id: (e) => e == null ? void 0 : o().parse(e)
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
function U() {
|
|
43
|
-
return s({
|
|
44
|
-
data: o().optional()
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
function F() {
|
|
48
|
-
return s({
|
|
49
|
-
theme_params: (e) => {
|
|
50
|
-
const t = j().optional();
|
|
51
|
-
return Object.entries(I(e)).reduce((r, [n, i]) => (r[n] = t.parse(i), r), {});
|
|
52
|
-
}
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
function K() {
|
|
56
|
-
return s({
|
|
57
|
-
height: q(),
|
|
58
|
-
width: (e) => e == null ? window.innerWidth : q().parse(e),
|
|
59
|
-
is_state_stable: v(),
|
|
60
|
-
is_expanded: v()
|
|
61
|
-
});
|
|
62
|
-
}
|
|
63
|
-
function Q() {
|
|
64
|
-
return s({ status: o() });
|
|
65
|
-
}
|
|
66
|
-
let P = "https://web.telegram.org";
|
|
67
|
-
const _ = new N("[Bridge]", !1);
|
|
68
|
-
function _e(e) {
|
|
69
|
-
if (e) {
|
|
70
|
-
_.enable();
|
|
71
|
-
return;
|
|
72
|
-
}
|
|
73
|
-
_.disable();
|
|
74
|
-
}
|
|
75
|
-
function ae(e) {
|
|
76
|
-
P = e;
|
|
77
|
-
}
|
|
78
|
-
function X() {
|
|
79
|
-
return P;
|
|
80
|
-
}
|
|
81
|
-
const Y = s({
|
|
82
|
-
eventType: o(),
|
|
83
|
-
eventData: (e) => e
|
|
84
|
-
});
|
|
85
|
-
function Z(e, t) {
|
|
86
|
-
window.dispatchEvent(new MessageEvent("message", {
|
|
87
|
-
data: JSON.stringify({ eventType: e, eventData: t })
|
|
88
|
-
}));
|
|
89
|
-
}
|
|
90
|
-
function D() {
|
|
91
|
-
const e = window;
|
|
92
|
-
"TelegramGameProxy_receiveEvent" in e || [
|
|
93
|
-
["TelegramGameProxy_receiveEvent"],
|
|
94
|
-
// Windows Phone.
|
|
95
|
-
["TelegramGameProxy", "receiveEvent"],
|
|
96
|
-
// Desktop.
|
|
97
|
-
["Telegram", "WebView", "receiveEvent"]
|
|
98
|
-
// Android and iOS.
|
|
99
|
-
].forEach((t) => {
|
|
100
|
-
let r = e;
|
|
101
|
-
t.forEach((n, i, c) => {
|
|
102
|
-
if (i === c.length - 1) {
|
|
103
|
-
r[n] = Z;
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
|
-
n in r || (r[n] = {}), r = r[n];
|
|
107
|
-
});
|
|
108
|
-
});
|
|
109
|
-
}
|
|
110
|
-
function V(e) {
|
|
111
|
-
D(), window.addEventListener("message", (t) => {
|
|
112
|
-
try {
|
|
113
|
-
const { eventType: r, eventData: n } = Y.parse(t.data);
|
|
114
|
-
e(r, n);
|
|
115
|
-
} catch {
|
|
116
|
-
}
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
|
-
const g = "__telegram-cached-emitter__";
|
|
120
|
-
function O() {
|
|
121
|
-
const e = new T(), t = (r, ...n) => {
|
|
122
|
-
_.log("Emitting processed event:", r, ...n), e.emit(r, ...n);
|
|
123
|
-
};
|
|
124
|
-
return window.addEventListener("resize", () => {
|
|
125
|
-
t("viewport_changed", {
|
|
126
|
-
width: window.innerWidth,
|
|
127
|
-
height: window.innerHeight,
|
|
128
|
-
is_state_stable: !0,
|
|
129
|
-
is_expanded: !0
|
|
130
|
-
});
|
|
131
|
-
}), V((r, n) => {
|
|
132
|
-
_.log("Received raw event:", r, n);
|
|
133
|
-
try {
|
|
134
|
-
switch (r) {
|
|
135
|
-
case "viewport_changed":
|
|
136
|
-
return t(r, K().parse(n));
|
|
137
|
-
case "theme_changed":
|
|
138
|
-
return t(r, F().parse(n));
|
|
139
|
-
case "popup_closed":
|
|
140
|
-
return (
|
|
141
|
-
// Sent on desktop.
|
|
142
|
-
n == null ? t(r, {}) : t(r, B().parse(n))
|
|
143
|
-
);
|
|
144
|
-
case "set_custom_style":
|
|
145
|
-
return t(r, o().parse(n));
|
|
146
|
-
case "qr_text_received":
|
|
147
|
-
return t(r, U().parse(n));
|
|
148
|
-
case "clipboard_text_received":
|
|
149
|
-
return t(r, S().parse(n));
|
|
150
|
-
case "invoice_closed":
|
|
151
|
-
return t(r, H().parse(n));
|
|
152
|
-
case "phone_requested":
|
|
153
|
-
return t("phone_requested", z().parse(n));
|
|
154
|
-
case "custom_method_invoked":
|
|
155
|
-
return t("custom_method_invoked", G().parse(n));
|
|
156
|
-
case "write_access_requested":
|
|
157
|
-
return t("write_access_requested", Q().parse(n));
|
|
158
|
-
case "main_button_pressed":
|
|
159
|
-
case "back_button_pressed":
|
|
160
|
-
case "settings_button_pressed":
|
|
161
|
-
case "scan_qr_popup_closed":
|
|
162
|
-
case "reload_iframe":
|
|
163
|
-
return t(r);
|
|
164
|
-
default:
|
|
165
|
-
return t(r, n);
|
|
166
|
-
}
|
|
167
|
-
} catch (i) {
|
|
168
|
-
_.error("Error processing event:", i);
|
|
169
|
-
}
|
|
170
|
-
}), e;
|
|
171
|
-
}
|
|
172
|
-
function d() {
|
|
173
|
-
const e = window;
|
|
174
|
-
return e[g] === void 0 && (e[g] = O()), e[g];
|
|
175
|
-
}
|
|
176
|
-
function A(e, t) {
|
|
177
|
-
d().off(e, t);
|
|
178
|
-
}
|
|
179
|
-
function ee(e, t) {
|
|
180
|
-
return d().on(e, t), () => A(e, t);
|
|
181
|
-
}
|
|
182
|
-
function pe(e, t) {
|
|
183
|
-
return d().once(e, t), () => A(e, t);
|
|
184
|
-
}
|
|
185
|
-
function te(e) {
|
|
186
|
-
d().unsubscribe(e);
|
|
187
|
-
}
|
|
188
|
-
function de(e) {
|
|
189
|
-
return d().subscribe(e), () => te(e);
|
|
190
|
-
}
|
|
191
|
-
function u(e, t) {
|
|
192
|
-
return J(e, t) <= 0;
|
|
193
|
-
}
|
|
194
|
-
function k(e, t, r) {
|
|
195
|
-
if (typeof r == "string") {
|
|
196
|
-
if (e === "web_app_open_link" && t === "try_instant_view")
|
|
197
|
-
return u("6.4", r);
|
|
198
|
-
if (e === "web_app_set_header_color" && t === "color")
|
|
199
|
-
return u("6.9", r);
|
|
200
|
-
}
|
|
201
|
-
switch (e) {
|
|
202
|
-
case "web_app_open_tg_link":
|
|
203
|
-
case "web_app_open_invoice":
|
|
204
|
-
case "web_app_setup_back_button":
|
|
205
|
-
case "web_app_set_background_color":
|
|
206
|
-
case "web_app_set_header_color":
|
|
207
|
-
case "web_app_trigger_haptic_feedback":
|
|
208
|
-
return u("6.1", t);
|
|
209
|
-
case "web_app_open_popup":
|
|
210
|
-
return u("6.2", t);
|
|
211
|
-
case "web_app_close_scan_qr_popup":
|
|
212
|
-
case "web_app_open_scan_qr_popup":
|
|
213
|
-
case "web_app_read_text_from_clipboard":
|
|
214
|
-
return u("6.4", t);
|
|
215
|
-
case "web_app_switch_inline_query":
|
|
216
|
-
return u("6.7", t);
|
|
217
|
-
case "web_app_invoke_custom_method":
|
|
218
|
-
case "web_app_request_write_access":
|
|
219
|
-
case "web_app_request_phone":
|
|
220
|
-
return u("6.9", t);
|
|
221
|
-
case "web_app_setup_settings_button":
|
|
222
|
-
return u("6.10", t);
|
|
223
|
-
default:
|
|
224
|
-
return !0;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
function fe(e) {
|
|
228
|
-
return (t, r) => {
|
|
229
|
-
if (!k(t, e))
|
|
230
|
-
throw new b(t, e);
|
|
231
|
-
if (p(r)) {
|
|
232
|
-
let n;
|
|
233
|
-
if (t === "web_app_open_link" && "try_instant_view" in r ? n = "try_instant_view" : t === "web_app_set_header_color" && "color" in r && (n = "color"), n && !k(t, n, e))
|
|
234
|
-
throw new h(t, n, e);
|
|
235
|
-
}
|
|
236
|
-
return W(t, r);
|
|
237
|
-
};
|
|
238
|
-
}
|
|
239
|
-
function re(e) {
|
|
240
|
-
return "external" in e && p(e.external) && "notify" in e.external && typeof e.external.notify == "function";
|
|
241
|
-
}
|
|
242
|
-
function ne(e) {
|
|
243
|
-
return "TelegramWebviewProxy" in e && p(e.TelegramWebviewProxy) && "postEvent" in e.TelegramWebviewProxy && typeof e.TelegramWebviewProxy.postEvent == "function";
|
|
244
|
-
}
|
|
245
|
-
function ie() {
|
|
246
|
-
try {
|
|
247
|
-
return window.self !== window.top;
|
|
248
|
-
} catch {
|
|
249
|
-
return !0;
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
function W(e, t, r) {
|
|
253
|
-
let n = {}, i;
|
|
254
|
-
t === void 0 && r === void 0 ? n = {} : t !== void 0 && r !== void 0 ? (n = r, i = t) : t !== void 0 && ("targetOrigin" in t ? n = t : i = t);
|
|
255
|
-
const { targetOrigin: c = X() } = n;
|
|
256
|
-
if (_.log(`Calling method "${e}"`, i), ie()) {
|
|
257
|
-
window.parent.postMessage(JSON.stringify({
|
|
258
|
-
eventType: e,
|
|
259
|
-
eventData: i
|
|
260
|
-
}), c);
|
|
261
|
-
return;
|
|
262
|
-
}
|
|
263
|
-
if (re(window)) {
|
|
264
|
-
window.external.notify(JSON.stringify({ eventType: e, eventData: i }));
|
|
265
|
-
return;
|
|
266
|
-
}
|
|
267
|
-
if (ne(window)) {
|
|
268
|
-
window.TelegramWebviewProxy.postEvent(e, JSON.stringify(i));
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
throw new Error(
|
|
272
|
-
"Unable to determine current environment and possible way to send event."
|
|
273
|
-
);
|
|
274
|
-
}
|
|
275
|
-
function we(e, t, r, n) {
|
|
276
|
-
let i, c, w, l;
|
|
277
|
-
typeof t == "string" || Array.isArray(t) ? (w = Array.isArray(t) ? t : [t], i = r) : (c = t, w = Array.isArray(r) ? r : [r], i = n), p(c) && typeof c.req_id == "string" && (l = c.req_id);
|
|
278
|
-
const { postEvent: R = W, timeout: E } = i || {}, m = i && "capture" in i ? i.capture : null, y = new Promise(($, C) => {
|
|
279
|
-
const M = w.map((a) => ee(a, (f) => {
|
|
280
|
-
typeof l == "string" && (!p(f) || f.req_id !== l) || typeof m == "function" && !m(f) || (x(), $(f));
|
|
281
|
-
})), x = () => M.forEach((a) => a());
|
|
282
|
-
try {
|
|
283
|
-
R(e, c);
|
|
284
|
-
} catch (a) {
|
|
285
|
-
x(), C(a);
|
|
286
|
-
}
|
|
287
|
-
});
|
|
288
|
-
return typeof E == "number" ? L(y, E) : y;
|
|
289
|
-
}
|
|
290
|
-
export {
|
|
291
|
-
b as MethodUnsupportedError,
|
|
292
|
-
h as ParameterUnsupportedError,
|
|
293
|
-
S as clipboardTextReceived,
|
|
294
|
-
fe as createPostEvent,
|
|
295
|
-
G as customMethodInvoked,
|
|
296
|
-
re as hasExternalNotify,
|
|
297
|
-
ne as hasWebviewProxy,
|
|
298
|
-
H as invoiceClosed,
|
|
299
|
-
ie as isIframe,
|
|
300
|
-
A as off,
|
|
301
|
-
ee as on,
|
|
302
|
-
pe as once,
|
|
303
|
-
z as phoneRequested,
|
|
304
|
-
B as popupClosed,
|
|
305
|
-
W as postEvent,
|
|
306
|
-
U as qrTextReceived,
|
|
307
|
-
we as request,
|
|
308
|
-
_e as setDebug,
|
|
309
|
-
ae as setTargetOrigin,
|
|
310
|
-
de as subscribe,
|
|
311
|
-
k as supports,
|
|
312
|
-
F as themeChanged,
|
|
313
|
-
te as unsubscribe,
|
|
314
|
-
K as viewportChanged,
|
|
315
|
-
Q as writeAccessRequested
|
|
316
|
-
};
|
|
317
|
-
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/errors/MethodUnsupportedError.ts","../src/errors/ParameterUnsupportedError.ts","../src/events/parsers/clipboardTextReceived.ts","../src/events/parsers/customMethodInvoked.ts","../src/events/parsers/invoiceClosed.ts","../src/events/parsers/phoneRequested.ts","../src/events/parsers/popupClosed.ts","../src/events/parsers/qrTextReceived.ts","../src/events/parsers/theme-changed.ts","../src/events/parsers/viewportChanged.ts","../src/events/parsers/writeAccessRequested.ts","../src/globals.ts","../src/events/onTelegramEvent.ts","../src/events/emitter.ts","../src/events/off.ts","../src/events/on.ts","../src/events/once.ts","../src/events/unsubscribe.ts","../src/events/subscribe.ts","../src/supports.ts","../src/methods/createPostEvent.ts","../src/env.ts","../src/methods/postEvent.ts","../src/request.ts"],"sourcesContent":["import type { Version } from '@tma.js/utils';\n\nimport type { MethodName } from '../methods/index.js';\n\n/**\n * Error thrown in case, unsupported method was called.\n */\nexport class MethodUnsupportedError extends Error {\n constructor(method: MethodName, version: Version) {\n super(`Method \"${method}\" is unsupported in the Mini Apps version ${version}.`);\n Object.setPrototypeOf(this, MethodUnsupportedError.prototype);\n }\n}\n","import type { Version } from '@tma.js/utils';\n\nimport type { MethodName } from '../methods/index.js';\n\n/**\n * Error thrown in case, unsupported parameter was used.\n */\nexport class ParameterUnsupportedError extends Error {\n constructor(method: MethodName, param: string, version: Version) {\n super(`Parameter \"${param}\" in method \"${method}\" is unsupported in the Mini Apps version ${version}.`);\n Object.setPrototypeOf(this, ParameterUnsupportedError.prototype);\n }\n}\n","import { json, string } from '@tma.js/parsing';\n\nimport type { RequestId } from '../../shared.js';\n\nexport interface ClipboardTextReceivedPayload {\n /**\n * Passed during the `web_app_read_text_from_clipboard` method invocation `req_id` value.\n */\n req_id: RequestId;\n\n /**\n * Data extracted from the clipboard. The returned value will have the type `string` only in\n * the case, application has access to the clipboard.\n */\n data?: string | null;\n}\n\nexport function clipboardTextReceived() {\n return json<ClipboardTextReceivedPayload>({\n req_id: string(),\n data: (value) => (\n value === null\n ? value\n : string().optional().parse(value)\n ),\n });\n}\n","import { json, string } from '@tma.js/parsing';\n\nimport type { RequestId } from '../../shared.js';\n\nexport interface CustomMethodInvokedPayload<R = unknown> {\n /**\n * Unique identifier of this invocation.\n */\n req_id: RequestId;\n /**\n * Method invocation successful result.\n */\n result?: R;\n /**\n * Method invocation error code.\n */\n error?: string;\n}\n\nexport function customMethodInvoked() {\n return json<CustomMethodInvokedPayload>({\n req_id: string(),\n result: (value) => value,\n error: string().optional(),\n });\n}\n","import { json, string } from '@tma.js/parsing';\n\nexport type InvoiceStatus =\n | 'paid'\n | 'failed'\n | 'pending'\n | 'cancelled'\n | string;\n\nexport interface InvoiceClosedPayload {\n /**\n * Passed during the `web_app_open_invoice` method invocation `slug` value.\n */\n slug: string;\n /**\n * Invoice status\n */\n status: InvoiceStatus;\n}\n\nexport function invoiceClosed() {\n return json<InvoiceClosedPayload>({\n slug: string(),\n status: string(),\n });\n}\n","import { json, string } from '@tma.js/parsing';\n\nexport type PhoneRequestedStatus = 'sent' | string;\n\nexport interface PhoneRequestedPayload {\n /**\n * Request status.\n */\n status: PhoneRequestedStatus;\n}\n\nexport function phoneRequested() {\n return json<PhoneRequestedPayload>({ status: string() });\n}\n","import { json, string } from '@tma.js/parsing';\n\nexport interface PopupClosedPayload {\n /**\n * Identifier of the clicked button. In case, the popup was closed without clicking any button,\n * this property will be omitted.\n */\n button_id?: string;\n}\n\nexport function popupClosed() {\n return json<PopupClosedPayload>({\n button_id: (value) => (\n value === null || value === undefined\n ? undefined\n : string().parse(value)\n ),\n });\n}\n","import { json, string } from '@tma.js/parsing';\n\nexport interface QrTextReceivedPayload {\n /**\n * Data extracted from the QR.\n */\n data?: string;\n}\n\nexport function qrTextReceived() {\n return json<QrTextReceivedPayload>({\n data: string().optional(),\n });\n}\n","import { json, rgb, toRecord } from '@tma.js/parsing';\nimport type { RGB } from '@tma.js/colors';\n\nexport interface ThemeChangedPayload {\n /**\n * Map where the key is a theme stylesheet key and value is the corresponding color in\n * `#RRGGBB` format.\n */\n theme_params: {\n /**\n * @since v6.10\n */\n accent_text_color?: RGB;\n bg_color?: RGB;\n button_color?: RGB;\n button_text_color?: RGB;\n /**\n * @since v6.10\n */\n destructive_text_color?: RGB;\n /**\n * @since v6.10\n */\n header_bg_color?: RGB;\n hint_color?: RGB;\n link_color?: RGB;\n secondary_bg_color?: RGB;\n /**\n * @since v6.10\n */\n section_bg_color?: RGB;\n /**\n * @since v6.10\n */\n section_header_text_color?: RGB;\n /**\n * @since v6.10\n */\n subtitle_text_color?: RGB;\n text_color?: RGB;\n [key: string]: RGB | undefined; // Future unknown palette keys.\n };\n}\n\nexport function themeChanged() {\n return json<ThemeChangedPayload>({\n theme_params: (value) => {\n const parser = rgb().optional();\n\n return Object\n .entries(toRecord(value))\n .reduce<Partial<Record<string, RGB>>>((acc, [k, v]) => {\n acc[k] = parser.parse(v);\n return acc;\n }, {});\n },\n });\n}\n","import { boolean, json, number } from '@tma.js/parsing';\n\nexport interface ViewportChangedPayload {\n /**\n * The viewport height.\n */\n height: number;\n /**\n * The viewport width.\n */\n width: number;\n /**\n * Is the viewport currently expanded.\n */\n is_expanded: boolean;\n /**\n * Is the viewport current state stable and not going to change in the next moment.\n */\n is_state_stable: boolean;\n}\n\nexport function viewportChanged() {\n return json<ViewportChangedPayload>({\n height: number(),\n width: (value) => (\n value === null || value === undefined\n ? window.innerWidth\n : number().parse(value)\n ),\n is_state_stable: boolean(),\n is_expanded: boolean(),\n });\n}\n","import { json, string } from '@tma.js/parsing';\n\nexport type WriteAccessRequestedStatus = 'allowed' | string;\n\nexport interface WriteAccessRequestedPayload {\n /**\n * Request status.\n */\n status: WriteAccessRequestedStatus;\n}\n\nexport function writeAccessRequested() {\n return json<WriteAccessRequestedPayload>({ status: string() });\n}\n","import { Logger } from '@tma.js/logger';\n\nlet currentTargetOrigin = 'https://web.telegram.org';\n\nexport const logger = new Logger('[Bridge]', false);\n\n/**\n * Sets new debug mode. Enabling debug mode leads to printing\n * additional messages in console, related to the processes\n * inside the package.\n * @param value - should debug mode be enabled.\n */\nexport function setDebug(value: boolean): void {\n if (value) {\n logger.enable();\n return;\n }\n logger.disable();\n}\n\n/**\n * Sets new global targetOrigin, used by `postEvent` method.\n * Default value is \"https://web.telegram.org\". You don't need to\n * use this method until you know what you are doing.\n *\n * This method could be used for test purposes.\n * @param value - new target origin.\n */\nexport function setTargetOrigin(value: string): void {\n currentTargetOrigin = value;\n}\n\n/**\n * Returns current global target origin.\n */\nexport function targetOrigin(): string {\n return currentTargetOrigin;\n}\n","import { json, string } from '@tma.js/parsing';\n\n/**\n * Extracts event data from native application event.\n */\nconst eventDataJson = json<{ eventType: string; eventData?: unknown }>({\n eventType: string(),\n eventData: (value) => value,\n});\n\n/**\n * Emits event sent from Telegram native application like it was sent in\n * default web environment between 2 iframes. It dispatches new MessageEvent\n * and expects it to be handled via `window.addEventListener('message', ...)`\n * as developer would do it to handle messages sent from parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nfunction emitEvent(eventType: string, eventData: unknown): void {\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType, eventData }),\n }));\n}\n\n/**\n * Defines special handlers by known paths, which are recognized by\n * Telegram as ports to receive events. This function also sets special\n * function in global window object to prevent duplicate declaration.\n */\nfunction defineEventHandlers(): void {\n const wnd: any = window;\n\n // Prevent from duplicate event handlers definition.\n if ('TelegramGameProxy_receiveEvent' in wnd) {\n return;\n }\n\n // Iterate over each path, where \"receiveEvent\" function should be\n // defined. This function is called by external environment in case,\n // it wants to emit some event.\n [\n ['TelegramGameProxy_receiveEvent'], // Windows Phone.\n ['TelegramGameProxy', 'receiveEvent'], // Desktop.\n ['Telegram', 'WebView', 'receiveEvent'], // Android and iOS.\n ].forEach((path) => {\n // Path starts from \"window\" object.\n let pointer = wnd;\n\n path.forEach((item, idx, arr) => {\n // We are on the last iteration, where function property name is passed.\n if (idx === arr.length - 1) {\n pointer[item] = emitEvent;\n return;\n }\n\n if (!(item in pointer)) {\n pointer[item] = {};\n }\n pointer = pointer[item];\n });\n });\n}\n\n/**\n * Adds listener to window \"message\" event assuming, that this event could\n * be sent by Telegram native application. Calls passed callback with event\n * type and data.\n * @param cb - callback to call.\n */\nexport function onTelegramEvent(cb: (eventType: string, eventData: unknown) => void): void {\n // Define event handlers to make sure, message handler will work correctly.\n defineEventHandlers();\n\n // We expect Telegram to send us new event through \"message\" event.\n window.addEventListener('message', (event) => {\n try {\n const { eventType, eventData } = eventDataJson.parse(event.data);\n cb(eventType, eventData);\n } catch {\n // We ignore incorrect messages as they could be generated by any other code.\n }\n });\n}\n","import { EventEmitter as UtilEventEmitter } from '@tma.js/event-emitter';\nimport { string } from '@tma.js/parsing';\n\nimport { logger } from '../globals.js';\nimport {\n clipboardTextReceived,\n customMethodInvoked,\n invoiceClosed,\n phoneRequested,\n popupClosed,\n qrTextReceived,\n themeChanged,\n viewportChanged,\n writeAccessRequested,\n} from './parsers/index.js';\nimport { onTelegramEvent } from './onTelegramEvent.js';\n\nimport type { EventEmitter, EventName } from './events.js';\n\nconst CACHED_EMITTER = '__telegram-cached-emitter__';\n\n/**\n * Returns event emitter which could be safely used, to process events from\n * Telegram native application.\n */\nexport function createEmitter(): EventEmitter {\n const emitter: EventEmitter = new UtilEventEmitter();\n const emit: EventEmitter['emit'] = (event: any, ...data: any[]) => {\n logger.log('Emitting processed event:', event, ...data);\n emitter.emit(event, ...data);\n };\n\n // Desktop version of Telegram is sometimes not sending the viewport_changed\n // event. For example, when main button is shown. That's why we should\n // add our own listener to make sure, viewport information is always fresh.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/10\n window.addEventListener('resize', () => {\n emit('viewport_changed', {\n width: window.innerWidth,\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n });\n });\n\n // In case, any Telegram event was received, we should prepare data before\n // passing it to emitter.\n onTelegramEvent((eventType: EventName | string, eventData): void => {\n logger.log('Received raw event:', eventType, eventData);\n\n try {\n switch (eventType) {\n case 'viewport_changed':\n return emit(eventType, viewportChanged().parse(eventData));\n\n case 'theme_changed':\n return emit(eventType, themeChanged().parse(eventData));\n\n case 'popup_closed':\n // FIXME: Payloads are different on different platforms.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/2\n if (\n // Sent on desktop.\n eventData === undefined\n // Sent on iOS.\n || eventData === null\n ) {\n return emit(eventType, {});\n }\n return emit(eventType, popupClosed().parse(eventData));\n\n case 'set_custom_style':\n return emit(eventType, string().parse(eventData));\n\n case 'qr_text_received':\n return emit(eventType, qrTextReceived().parse(eventData));\n\n case 'clipboard_text_received':\n return emit(eventType, clipboardTextReceived().parse(eventData));\n\n case 'invoice_closed':\n return emit(eventType, invoiceClosed().parse(eventData));\n\n case 'phone_requested':\n return emit('phone_requested', phoneRequested().parse(eventData));\n\n case 'custom_method_invoked':\n return emit('custom_method_invoked', customMethodInvoked().parse(eventData));\n\n case 'write_access_requested':\n return emit('write_access_requested', writeAccessRequested().parse(eventData));\n\n // Events which have no parameters.\n case 'main_button_pressed':\n case 'back_button_pressed':\n case 'settings_button_pressed':\n case 'scan_qr_popup_closed':\n case 'reload_iframe':\n return emit(eventType);\n\n // All other event listeners will receive unknown type of data.\n default:\n return emit(eventType as any, eventData);\n }\n } catch (cause) {\n logger.error('Error processing event:', cause);\n }\n });\n\n return emitter;\n}\n\n/**\n * Returns singleton instance of bridge EventEmitter. Also, defines\n * Telegram event handlers.\n */\nexport function singletonEmitter(): EventEmitter {\n const wnd: any = window;\n const cachedEmitter = wnd[CACHED_EMITTER];\n\n if (cachedEmitter === undefined) {\n wnd[CACHED_EMITTER] = createEmitter();\n }\n\n return wnd[CACHED_EMITTER];\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { EventName, EventListener } from './events.js';\n\n/**\n * Removes listener from specified event.\n * @param event - event to listen.\n * @param listener - event listener.\n */\nexport function off<E extends EventName>(event: E, listener: EventListener<E>): void {\n singletonEmitter().off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Adds new listener to the specified event. Returns handler\n * which allows to stop listening to event.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function on<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().on(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Works the same as \"on\" method, but after catching the event, will remove event listener.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function once<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().once(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { GlobalEventListener } from './events.js';\n\n/**\n * Removes global event listener.\n * @param listener - event listener.\n */\nexport function unsubscribe(listener: GlobalEventListener): void {\n singletonEmitter().unsubscribe(listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { unsubscribe } from './unsubscribe.js';\n\nimport type { GlobalEventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Subscribes to all events sent from the native Telegram application.\n * Returns function used to remove added event listener.\n * @param listener - event listener.\n */\nexport function subscribe(listener: GlobalEventListener): StopListening {\n singletonEmitter().subscribe(listener);\n return () => unsubscribe(listener);\n}\n","import { compareVersions, type Version } from '@tma.js/utils';\n\nimport type {\n MethodVersionedParams,\n MethodWithVersionedParams,\n MethodName,\n} from './methods/index.js';\n\n/**\n * Returns true if \"a\" version is less than or equal to \"b\" version.\n * @param a\n * @param b\n */\nfunction versionLessOrEqual(a: Version, b: Version): boolean {\n return compareVersions(a, b) <= 0;\n}\n\n/**\n * Returns true in case, passed parameter in specified method is supported.\n * @param method - method name\n * @param param - method parameter\n * @param inVersion - platform version.\n */\nexport function supports<M extends MethodWithVersionedParams>(\n method: M,\n param: MethodVersionedParams<M>,\n inVersion: Version,\n): boolean;\n\n/**\n * Returns true in case, specified method is supported in passed version.\n * @param method - method name.\n * @param inVersion - platform version.\n */\nexport function supports(method: MethodName, inVersion: Version): boolean;\n\nexport function supports(\n method: MethodName,\n paramOrVersion: Version | string,\n inVersion?: string,\n): boolean {\n // Method name, parameter, target version.\n if (typeof inVersion === 'string') {\n if (method === 'web_app_open_link') {\n if (paramOrVersion === 'try_instant_view') {\n return versionLessOrEqual('6.4', inVersion);\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if (paramOrVersion === 'color') {\n return versionLessOrEqual('6.9', inVersion);\n }\n }\n }\n\n switch (method) {\n case 'web_app_open_tg_link':\n case 'web_app_open_invoice':\n case 'web_app_setup_back_button':\n case 'web_app_set_background_color':\n case 'web_app_set_header_color':\n case 'web_app_trigger_haptic_feedback':\n return versionLessOrEqual('6.1', paramOrVersion);\n case 'web_app_open_popup':\n return versionLessOrEqual('6.2', paramOrVersion);\n case 'web_app_close_scan_qr_popup':\n case 'web_app_open_scan_qr_popup':\n case 'web_app_read_text_from_clipboard':\n return versionLessOrEqual('6.4', paramOrVersion);\n case 'web_app_switch_inline_query':\n return versionLessOrEqual('6.7', paramOrVersion);\n case 'web_app_invoke_custom_method':\n case 'web_app_request_write_access':\n case 'web_app_request_phone':\n return versionLessOrEqual('6.9', paramOrVersion);\n case 'web_app_setup_settings_button':\n return versionLessOrEqual('6.10', paramOrVersion);\n default:\n return true;\n }\n}\n","import { isRecord, type Version } from '@tma.js/utils';\n\nimport { supports } from '../supports.js';\nimport { MethodUnsupportedError, ParameterUnsupportedError } from '../errors/index.js';\nimport { postEvent, type PostEvent } from './index.js';\n\n/**\n * Creates function which checks if specified method and parameters are supported. In case,\n * method or parameters are unsupported, an error will be thrown.\n * @param version - Telegram Mini Apps version.\n * @throws {MethodUnsupportedError} Method is unsupported.\n * @throws {ParameterUnsupportedError} Method parameter is unsupported.\n */\nexport function createPostEvent(version: Version): PostEvent {\n return (method: any, params: any) => {\n // Firstly, check if method itself is supported.\n if (!supports(method, version)) {\n throw new MethodUnsupportedError(method, version);\n }\n\n // Method could use parameters, which are supported only in specific versions of Telegram\n // Mini Apps.\n if (isRecord(params)) {\n let validateParam: string | undefined;\n\n if (method === 'web_app_open_link' && 'try_instant_view' in params) {\n validateParam = 'try_instant_view';\n } else if (method === 'web_app_set_header_color' && 'color' in params) {\n validateParam = 'color';\n }\n\n if (validateParam && !supports(method, validateParam, version)) {\n throw new ParameterUnsupportedError(method, validateParam, version);\n }\n }\n\n return postEvent(method, params);\n };\n}\n","import { isRecord } from '@tma.js/utils';\n\ntype AnyFunc = (...args: unknown[]) => unknown;\n\ntype WithExternalNotify<T> = T & {\n external: { notify: AnyFunc }\n};\n\ntype WithWebviewProxy<T> = T & {\n TelegramWebviewProxy: {\n postEvent: AnyFunc;\n }\n};\n\n/**\n * Returns true in case, passed value contains path `external.notify` property and `notify` is a\n * function.\n * @param value - value to check.\n */\nexport function hasExternalNotify<T extends {}>(value: T): value is WithExternalNotify<T> {\n return 'external' in value\n && isRecord(value.external)\n && 'notify' in value.external\n && typeof value.external.notify === 'function';\n}\n\n/**\n * Returns true in case, passed value contains path `TelegramWebviewProxy.postEvent` property and\n * `postEvent` is a function.\n * @param value - value to check.\n */\nexport function hasWebviewProxy<T extends {}>(value: T): value is WithWebviewProxy<T> {\n return 'TelegramWebviewProxy' in value\n && isRecord(value.TelegramWebviewProxy)\n && 'postEvent' in value.TelegramWebviewProxy\n && typeof value.TelegramWebviewProxy.postEvent === 'function';\n}\n\n/**\n * Returns true in case, current environment is iframe.\n * @see https://stackoverflow.com/a/326076\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch (e) {\n return true;\n }\n}\n","import {\n isIframe,\n hasExternalNotify,\n hasWebviewProxy,\n} from '../env.js';\nimport { logger, targetOrigin as globalTargetOrigin } from '../globals.js';\nimport type {\n EmptyMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods.js';\n\ninterface PostEventOptions {\n /**\n * Origin used while posting message. This option is only used in case,\n * current environment is browser (Web version of Telegram) and could\n * be used for test purposes.\n * @default 'https://web.telegram.org'\n */\n targetOrigin?: string;\n}\n\nexport type PostEvent = typeof postEvent;\n\n/**\n * Sends event to native application which launched Mini App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param params - event parameters.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current environment and possible way to send event.\n */\nexport function postEvent<E extends NonEmptyMethodName>(\n eventType: E,\n params: MethodParams<E>,\n options?: PostEventOptions,\n): void;\n\n/**\n * Sends event to native application which launched Mini App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current environment and possible way to send event.\n */\nexport function postEvent(eventType: EmptyMethodName, options?: PostEventOptions): void;\n\nexport function postEvent(\n eventType: MethodName,\n paramsOrOptions?: MethodParams<MethodName> | PostEventOptions,\n options?: PostEventOptions,\n): void {\n let postOptions: PostEventOptions = {};\n let eventData: any;\n\n if (paramsOrOptions === undefined && options === undefined) {\n // Parameters and options were not passed.\n postOptions = {};\n } else if (paramsOrOptions !== undefined && options !== undefined) {\n // Both parameters and options passed.\n postOptions = options;\n eventData = paramsOrOptions;\n } else if (paramsOrOptions !== undefined) {\n // Only parameters were passed.\n if ('targetOrigin' in paramsOrOptions) {\n postOptions = paramsOrOptions;\n } else {\n eventData = paramsOrOptions;\n }\n }\n const { targetOrigin = globalTargetOrigin() } = postOptions;\n\n logger.log(`Calling method \"${eventType}\"`, eventData);\n\n // Telegram Web.\n if (isIframe()) {\n window.parent.postMessage(JSON.stringify({\n eventType,\n eventData,\n }), targetOrigin);\n return;\n }\n\n // Telegram for Windows Phone or Android.\n if (hasExternalNotify(window)) {\n window.external.notify(JSON.stringify({ eventType, eventData }));\n return;\n }\n\n // Telegram for iOS and macOS.\n if (hasWebviewProxy(window)) {\n window.TelegramWebviewProxy.postEvent(eventType, JSON.stringify(eventData));\n return;\n }\n\n // Otherwise current environment is unknown, and we are not able to send event.\n throw new Error(\n 'Unable to determine current environment and possible way to send event.',\n );\n}\n","import { withTimeout, isRecord } from '@tma.js/utils';\nimport type { And, If, IsNever } from '@tma.js/util-types';\n\nimport { postEvent as defaultPostEvent, type PostEvent } from './methods/postEvent.js';\nimport { on, type EventName, type EventParams, type EventHasParams } from './events/index.js';\n\nimport type {\n EmptyMethodName,\n MethodAcceptParams,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/methods.js';\n\n/**\n * Names of methods, which require passing \"req_id\" parameter.\n */\ntype MethodWithRequestId = {\n [M in MethodName]: If<\n And<MethodAcceptParams<M>, MethodParams<M> extends { req_id: string } ? true : false>,\n M,\n never\n >;\n}[MethodName];\n\n/**\n * Names of events, which contain \"req_id\" parameter.\n */\ntype EventWithRequestId = {\n [E in EventName]: If<\n And<EventHasParams<E>, EventParams<E> extends { req_id: string } ? true : false>,\n E,\n never\n >;\n}[EventName];\n\nexport interface RequestOptions {\n /**\n * Bridge postEvent method.\n * @default Global postEvent method.\n */\n postEvent?: PostEvent;\n\n /**\n * Execution timeout.\n */\n timeout?: number;\n}\n\nexport interface RequestOptionsAdvanced<EventPayload> extends RequestOptions {\n /**\n * Should return true in case, this event should be captured. If not specified,\n * request is not skipping captured events.\n */\n capture?: If<IsNever<EventPayload>, () => boolean, (payload: EventPayload) => boolean>;\n}\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, event with specified in method request identifier\n * was captured.\n * @param method - method to execute.\n * @param params - method parameters.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<M extends MethodWithRequestId, E extends EventWithRequestId>(\n method: M,\n params: MethodParams<M>,\n event: E | E[],\n options?: RequestOptions,\n): Promise<EventParams<E>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<M extends EmptyMethodName, E extends EventName>(\n method: M,\n event: E | E[],\n options?: RequestOptionsAdvanced<EventParams<E>>,\n): Promise<EventParams<E>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute\n * @param params - method parameters.\n * @param event - event or events to listen\n * @param options - additional execution options.\n */\nexport function request<M extends NonEmptyMethodName, E extends EventName>(\n method: M,\n params: MethodParams<M>,\n event: E | E[],\n options?: RequestOptionsAdvanced<EventParams<E>>,\n): Promise<EventParams<E>>;\n\nexport function request(\n method: MethodName,\n eventOrParams: EventName | EventName[] | EventParams<any>,\n eventOrOptions?: EventName | EventName[] | RequestOptions | RequestOptionsAdvanced<any>,\n options?: RequestOptions | RequestOptionsAdvanced<any>,\n): Promise<any> {\n let executionOptions: RequestOptions | RequestOptionsAdvanced<any> | undefined;\n let methodParams: EventParams<any> | undefined;\n let events: EventName[];\n let requestId: string | undefined;\n\n if (typeof eventOrParams === 'string' || Array.isArray(eventOrParams)) {\n // Override: [method, event, options?]\n events = Array.isArray(eventOrParams) ? eventOrParams : [eventOrParams] as EventName[];\n executionOptions = eventOrOptions as (RequestOptionsAdvanced<any> | undefined);\n } else {\n // Override: [method, params, event, options?]\n methodParams = eventOrParams as EventParams<any>;\n events = Array.isArray(eventOrOptions) ? eventOrOptions : [eventOrOptions] as EventName[];\n executionOptions = options;\n }\n\n // In case, method parameters were passed, and they contained request identifier, we should store\n // it and wait for the event with this identifier to occur.\n if (isRecord(methodParams) && typeof methodParams.req_id === 'string') {\n requestId = methodParams.req_id;\n }\n\n const { postEvent = defaultPostEvent, timeout } = executionOptions || {};\n const capture = executionOptions && 'capture' in executionOptions\n ? executionOptions.capture\n : null;\n\n const promise = new Promise((res, rej) => {\n // Iterate over each event and create event listener.\n const stoppers = events.map((ev) => on(ev, (data?) => {\n // If request identifier was specified, we are waiting for event with the same value\n // to occur.\n if (typeof requestId === 'string' && (!isRecord(data) || data.req_id !== requestId)) {\n return;\n }\n\n if (typeof capture === 'function' && !capture(data)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n stopListening();\n res(data);\n }));\n\n // Function which removes all event listeners.\n const stopListening = () => stoppers.forEach((stop) => stop());\n\n try {\n // We are wrapping this call in try catch, because it can throw errors in case,\n // compatibility check was enabled. We want an error to be captured by promise, not by\n // another one external try catch.\n postEvent(method as any, methodParams);\n } catch (e) {\n stopListening();\n rej(e);\n }\n });\n\n return typeof timeout === 'number' ? withTimeout(promise, timeout) : promise;\n}\n"],"names":["MethodUnsupportedError","method","version","ParameterUnsupportedError","param","clipboardTextReceived","json","string","value","customMethodInvoked","invoiceClosed","phoneRequested","popupClosed","qrTextReceived","themeChanged","parser","rgb","toRecord","acc","k","v","viewportChanged","number","boolean","writeAccessRequested","currentTargetOrigin","logger","Logger","setDebug","setTargetOrigin","targetOrigin","eventDataJson","emitEvent","eventType","eventData","defineEventHandlers","wnd","path","pointer","item","idx","arr","onTelegramEvent","cb","event","CACHED_EMITTER","createEmitter","emitter","UtilEventEmitter","emit","data","cause","singletonEmitter","off","listener","on","once","unsubscribe","subscribe","versionLessOrEqual","a","b","compareVersions","supports","paramOrVersion","inVersion","createPostEvent","params","isRecord","validateParam","postEvent","hasExternalNotify","hasWebviewProxy","isIframe","paramsOrOptions","options","postOptions","globalTargetOrigin","request","eventOrParams","eventOrOptions","executionOptions","methodParams","events","requestId","defaultPostEvent","timeout","capture","promise","res","rej","stoppers","ev","stopListening","stop","e","withTimeout"],"mappings":";;;;AAOO,MAAMA,UAA+B,MAAM;AAAA,EAChD,YAAYC,GAAoBC,GAAkB;AACh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KACdH,EAAIK,CAAC;AAAA,IACP;AAAA,EAAA,CACD;AAED,SAAO,OAAOT,KAAY,WAAWU,EAAYR,GAASF,CAAO,IAAIE;AACvE;"}
|
package/src/env.ts
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import { isRecord } from '@tma.js/utils';
|
|
2
|
-
|
|
3
|
-
type AnyFunc = (...args: unknown[]) => unknown;
|
|
4
|
-
|
|
5
|
-
type WithExternalNotify<T> = T & {
|
|
6
|
-
external: { notify: AnyFunc }
|
|
7
|
-
};
|
|
8
|
-
|
|
9
|
-
type WithWebviewProxy<T> = T & {
|
|
10
|
-
TelegramWebviewProxy: {
|
|
11
|
-
postEvent: AnyFunc;
|
|
12
|
-
}
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Returns true in case, passed value contains path `external.notify` property and `notify` is a
|
|
17
|
-
* function.
|
|
18
|
-
* @param value - value to check.
|
|
19
|
-
*/
|
|
20
|
-
export function hasExternalNotify<T extends {}>(value: T): value is WithExternalNotify<T> {
|
|
21
|
-
return 'external' in value
|
|
22
|
-
&& isRecord(value.external)
|
|
23
|
-
&& 'notify' in value.external
|
|
24
|
-
&& typeof value.external.notify === 'function';
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Returns true in case, passed value contains path `TelegramWebviewProxy.postEvent` property and
|
|
29
|
-
* `postEvent` is a function.
|
|
30
|
-
* @param value - value to check.
|
|
31
|
-
*/
|
|
32
|
-
export function hasWebviewProxy<T extends {}>(value: T): value is WithWebviewProxy<T> {
|
|
33
|
-
return 'TelegramWebviewProxy' in value
|
|
34
|
-
&& isRecord(value.TelegramWebviewProxy)
|
|
35
|
-
&& 'postEvent' in value.TelegramWebviewProxy
|
|
36
|
-
&& typeof value.TelegramWebviewProxy.postEvent === 'function';
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Returns true in case, current environment is iframe.
|
|
41
|
-
* @see https://stackoverflow.com/a/326076
|
|
42
|
-
*/
|
|
43
|
-
export function isIframe(): boolean {
|
|
44
|
-
try {
|
|
45
|
-
return window.self !== window.top;
|
|
46
|
-
} catch (e) {
|
|
47
|
-
return true;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import type { Version } from '@tma.js/utils';
|
|
2
|
-
|
|
3
|
-
import type { MethodName } from '../methods/index.js';
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Error thrown in case, unsupported method was called.
|
|
7
|
-
*/
|
|
8
|
-
export class MethodUnsupportedError extends Error {
|
|
9
|
-
constructor(method: MethodName, version: Version) {
|
|
10
|
-
super(`Method "${method}" is unsupported in the Mini Apps version ${version}.`);
|
|
11
|
-
Object.setPrototypeOf(this, MethodUnsupportedError.prototype);
|
|
12
|
-
}
|
|
13
|
-
}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import type { Version } from '@tma.js/utils';
|
|
2
|
-
|
|
3
|
-
import type { MethodName } from '../methods/index.js';
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Error thrown in case, unsupported parameter was used.
|
|
7
|
-
*/
|
|
8
|
-
export class ParameterUnsupportedError extends Error {
|
|
9
|
-
constructor(method: MethodName, param: string, version: Version) {
|
|
10
|
-
super(`Parameter "${param}" in method "${method}" is unsupported in the Mini Apps version ${version}.`);
|
|
11
|
-
Object.setPrototypeOf(this, ParameterUnsupportedError.prototype);
|
|
12
|
-
}
|
|
13
|
-
}
|
package/src/errors/index.ts
DELETED
package/src/events/emitter.ts
DELETED
|
@@ -1,126 +0,0 @@
|
|
|
1
|
-
import { EventEmitter as UtilEventEmitter } from '@tma.js/event-emitter';
|
|
2
|
-
import { string } from '@tma.js/parsing';
|
|
3
|
-
|
|
4
|
-
import { logger } from '../globals.js';
|
|
5
|
-
import {
|
|
6
|
-
clipboardTextReceived,
|
|
7
|
-
customMethodInvoked,
|
|
8
|
-
invoiceClosed,
|
|
9
|
-
phoneRequested,
|
|
10
|
-
popupClosed,
|
|
11
|
-
qrTextReceived,
|
|
12
|
-
themeChanged,
|
|
13
|
-
viewportChanged,
|
|
14
|
-
writeAccessRequested,
|
|
15
|
-
} from './parsers/index.js';
|
|
16
|
-
import { onTelegramEvent } from './onTelegramEvent.js';
|
|
17
|
-
|
|
18
|
-
import type { EventEmitter, EventName } from './events.js';
|
|
19
|
-
|
|
20
|
-
const CACHED_EMITTER = '__telegram-cached-emitter__';
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Returns event emitter which could be safely used, to process events from
|
|
24
|
-
* Telegram native application.
|
|
25
|
-
*/
|
|
26
|
-
export function createEmitter(): EventEmitter {
|
|
27
|
-
const emitter: EventEmitter = new UtilEventEmitter();
|
|
28
|
-
const emit: EventEmitter['emit'] = (event: any, ...data: any[]) => {
|
|
29
|
-
logger.log('Emitting processed event:', event, ...data);
|
|
30
|
-
emitter.emit(event, ...data);
|
|
31
|
-
};
|
|
32
|
-
|
|
33
|
-
// Desktop version of Telegram is sometimes not sending the viewport_changed
|
|
34
|
-
// event. For example, when main button is shown. That's why we should
|
|
35
|
-
// add our own listener to make sure, viewport information is always fresh.
|
|
36
|
-
// Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/10
|
|
37
|
-
window.addEventListener('resize', () => {
|
|
38
|
-
emit('viewport_changed', {
|
|
39
|
-
width: window.innerWidth,
|
|
40
|
-
height: window.innerHeight,
|
|
41
|
-
is_state_stable: true,
|
|
42
|
-
is_expanded: true,
|
|
43
|
-
});
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
// In case, any Telegram event was received, we should prepare data before
|
|
47
|
-
// passing it to emitter.
|
|
48
|
-
onTelegramEvent((eventType: EventName | string, eventData): void => {
|
|
49
|
-
logger.log('Received raw event:', eventType, eventData);
|
|
50
|
-
|
|
51
|
-
try {
|
|
52
|
-
switch (eventType) {
|
|
53
|
-
case 'viewport_changed':
|
|
54
|
-
return emit(eventType, viewportChanged().parse(eventData));
|
|
55
|
-
|
|
56
|
-
case 'theme_changed':
|
|
57
|
-
return emit(eventType, themeChanged().parse(eventData));
|
|
58
|
-
|
|
59
|
-
case 'popup_closed':
|
|
60
|
-
// FIXME: Payloads are different on different platforms.
|
|
61
|
-
// Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/2
|
|
62
|
-
if (
|
|
63
|
-
// Sent on desktop.
|
|
64
|
-
eventData === undefined
|
|
65
|
-
// Sent on iOS.
|
|
66
|
-
|| eventData === null
|
|
67
|
-
) {
|
|
68
|
-
return emit(eventType, {});
|
|
69
|
-
}
|
|
70
|
-
return emit(eventType, popupClosed().parse(eventData));
|
|
71
|
-
|
|
72
|
-
case 'set_custom_style':
|
|
73
|
-
return emit(eventType, string().parse(eventData));
|
|
74
|
-
|
|
75
|
-
case 'qr_text_received':
|
|
76
|
-
return emit(eventType, qrTextReceived().parse(eventData));
|
|
77
|
-
|
|
78
|
-
case 'clipboard_text_received':
|
|
79
|
-
return emit(eventType, clipboardTextReceived().parse(eventData));
|
|
80
|
-
|
|
81
|
-
case 'invoice_closed':
|
|
82
|
-
return emit(eventType, invoiceClosed().parse(eventData));
|
|
83
|
-
|
|
84
|
-
case 'phone_requested':
|
|
85
|
-
return emit('phone_requested', phoneRequested().parse(eventData));
|
|
86
|
-
|
|
87
|
-
case 'custom_method_invoked':
|
|
88
|
-
return emit('custom_method_invoked', customMethodInvoked().parse(eventData));
|
|
89
|
-
|
|
90
|
-
case 'write_access_requested':
|
|
91
|
-
return emit('write_access_requested', writeAccessRequested().parse(eventData));
|
|
92
|
-
|
|
93
|
-
// Events which have no parameters.
|
|
94
|
-
case 'main_button_pressed':
|
|
95
|
-
case 'back_button_pressed':
|
|
96
|
-
case 'settings_button_pressed':
|
|
97
|
-
case 'scan_qr_popup_closed':
|
|
98
|
-
case 'reload_iframe':
|
|
99
|
-
return emit(eventType);
|
|
100
|
-
|
|
101
|
-
// All other event listeners will receive unknown type of data.
|
|
102
|
-
default:
|
|
103
|
-
return emit(eventType as any, eventData);
|
|
104
|
-
}
|
|
105
|
-
} catch (cause) {
|
|
106
|
-
logger.error('Error processing event:', cause);
|
|
107
|
-
}
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
return emitter;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* Returns singleton instance of bridge EventEmitter. Also, defines
|
|
115
|
-
* Telegram event handlers.
|
|
116
|
-
*/
|
|
117
|
-
export function singletonEmitter(): EventEmitter {
|
|
118
|
-
const wnd: any = window;
|
|
119
|
-
const cachedEmitter = wnd[CACHED_EMITTER];
|
|
120
|
-
|
|
121
|
-
if (cachedEmitter === undefined) {
|
|
122
|
-
wnd[CACHED_EMITTER] = createEmitter();
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
return wnd[CACHED_EMITTER];
|
|
126
|
-
}
|