@tma.js/bridge 2.3.2 → 4.0.0-rc.0

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 (57) hide show
  1. package/README.md +156 -35
  2. package/dist/dts/env.d.ts +69 -0
  3. package/dist/dts/errors.d.ts +55 -9
  4. package/dist/dts/events.d.ts +64 -0
  5. package/dist/dts/index.d.ts +14 -26
  6. package/dist/dts/invokeCustomMethod.d.ts +33 -0
  7. package/dist/dts/launch-params.d.ts +101 -19
  8. package/dist/dts/logger.d.ts +29 -0
  9. package/dist/dts/mockTelegramEnv.d.ts +55 -0
  10. package/dist/dts/post-event.d.ts +40 -0
  11. package/dist/dts/request.d.ts +98 -0
  12. package/dist/dts/result.d.ts +45 -0
  13. package/dist/dts/start-param.d.ts +34 -40
  14. package/dist/dts/theme-params.d.ts +10 -0
  15. package/dist/dts/types/common.d.ts +61 -0
  16. package/dist/dts/{events/types → types}/events.d.ts +75 -56
  17. package/dist/dts/types/index.d.ts +5 -0
  18. package/dist/dts/{methods/types → types}/methods.d.ts +200 -116
  19. package/dist/dts/versions.d.ts +83 -0
  20. package/dist/dts/window-hooks.d.ts +27 -0
  21. package/dist/index.cjs +2 -3
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.iife.js +2 -3
  24. package/dist/index.iife.js.map +1 -1
  25. package/dist/index.js +619 -601
  26. package/dist/index.js.map +1 -1
  27. package/package.json +11 -19
  28. package/dist/dts/applyPolyfills.d.ts +0 -5
  29. package/dist/dts/base64-url.d.ts +0 -24
  30. package/dist/dts/env/hasWebviewProxy.d.ts +0 -10
  31. package/dist/dts/env/isIframe.d.ts +0 -5
  32. package/dist/dts/env/isTMA.d.ts +0 -31
  33. package/dist/dts/env/mockTelegramEnv.d.ts +0 -60
  34. package/dist/dts/events/createEmitter.d.ts +0 -58
  35. package/dist/dts/events/emitEvent.d.ts +0 -33
  36. package/dist/dts/events/emitter.d.ts +0 -2
  37. package/dist/dts/events/types/index.d.ts +0 -3
  38. package/dist/dts/events/types/listening.d.ts +0 -5
  39. package/dist/dts/events/types/misc.d.ts +0 -16
  40. package/dist/dts/globals.d.ts +0 -53
  41. package/dist/dts/methods/captureSameReq.d.ts +0 -10
  42. package/dist/dts/methods/createPostEvent.d.ts +0 -30
  43. package/dist/dts/methods/getReleaseVersion.d.ts +0 -15
  44. package/dist/dts/methods/postEvent.d.ts +0 -35
  45. package/dist/dts/methods/postMessage.d.ts +0 -7
  46. package/dist/dts/methods/supports.d.ts +0 -15
  47. package/dist/dts/methods/types/custom-method.d.ts +0 -59
  48. package/dist/dts/methods/types/index.d.ts +0 -6
  49. package/dist/dts/methods/types/misc.d.ts +0 -27
  50. package/dist/dts/methods/types/utils.d.ts +0 -9
  51. package/dist/dts/obj-prop-helpers.d.ts +0 -39
  52. package/dist/dts/utils/compareVersions.d.ts +0 -10
  53. package/dist/dts/utils/invokeCustomMethod.d.ts +0 -34
  54. package/dist/dts/utils/request.d.ts +0 -102
  55. package/dist/dts/utils/request2.d.ts +0 -62
  56. /package/dist/dts/{methods/types → types}/haptic-feedback.d.ts +0 -0
  57. /package/dist/dts/{methods/types → types}/popup.d.ts +0 -0
package/README.md CHANGED
@@ -1,59 +1,180 @@
1
1
  # @tma.js/bridge
2
2
 
3
- [code-badge]: https://img.shields.io/badge/source-black?logo=github
3
+ Communication layer between a Telegram Mini App and the Telegram client. It has no runtime
4
+ dependencies and works together with the official SDK
5
+ ([telegram-web-app.js](https://telegram.org/js/telegram-web-app.js)) loaded on the same page.
4
6
 
5
- [docs-badge]: https://img.shields.io/badge/documentation-blue?logo=gitbook&logoColor=white
7
+ ```bash
8
+ pnpm i @tma.js/bridge
9
+ ```
6
10
 
7
- [link]: https://github.com/Telegram-Mini-Apps/tma.js/tree/master/tma.js/bridge
11
+ ## Calling methods
8
12
 
9
- [docs-link]: https://docs.telegram-mini-apps.com/packages/tma-js-bridge
13
+ ```ts
14
+ import { postEvent } from '@tma.js/bridge';
10
15
 
11
- [npm-link]: https://npmjs.com/package/@tma.js/bridge
16
+ postEvent('web_app_ready');
17
+ postEvent('web_app_setup_back_button', { is_visible: true });
18
+ ```
12
19
 
13
- [npm-badge]: https://img.shields.io/npm/v/@tma.js/bridge?logo=npm
20
+ Method names and parameters are typed. `postEvent` throws `UnknownEnvError` if the app was
21
+ opened outside Telegram.
14
22
 
15
- [size-badge]: https://img.shields.io/bundlephobia/minzip/@tma.js/bridge
23
+ To make sure the method is supported by the current Telegram client, create a checked function:
16
24
 
17
- [![NPM][npm-badge]][npm-link]
18
- ![Size][size-badge]
19
- [![docs-badge]][docs-link]
20
- [![code-badge]][link]
25
+ ```ts
26
+ import { createPostEvent, retrieveLaunchParams } from '@tma.js/bridge';
21
27
 
22
- The lowest level communication layer with Telegram Mini Apps.
28
+ const postEvent = createPostEvent(retrieveLaunchParams().tgWebAppVersion);
29
+ // Throws MethodUnsupportedError in Mini Apps versions lower than 6.2.
30
+ postEvent('web_app_open_popup', { title: 'Hi', message: 'Hello', buttons: [{ id: 'ok', type: 'ok' }] });
31
+ ```
23
32
 
24
- This package provides fundamental utilities and types for developing applications on the Telegram
25
- Mini Apps platform.
33
+ Pass `'non-strict'` or a function as the second argument to warn or handle unsupported calls
34
+ yourself. Use `supports` and `getReleaseVersion` for manual checks.
26
35
 
27
- While a developer can use this package alone, it's recommended to use a higher-level package
28
- like [@tma.js/sdk](https://docs.telegram-mini-apps.com/packages/tma-js-sdk).
36
+ ## Listening to events
29
37
 
30
- ## Installation
38
+ ```ts
39
+ import { onEvent, offEvent, onAnyEvent } from '@tma.js/bridge';
31
40
 
32
- ```bash
33
- pnpm i @tma.js/bridge
34
- # or
35
- npm i @tma.js/bridge
36
- # or
37
- yarn add @tma.js/bridge
41
+ const stop = onEvent('viewport_changed', ({ height, is_expanded }) => {
42
+ console.log(height, is_expanded);
43
+ });
44
+ stop();
45
+
46
+ onEvent('back_button_pressed', () => history.back(), { once: true });
47
+ onEvent('theme_changed', console.log, { signal: abortController.signal });
48
+ onAnyEvent(({ name, payload }) => console.log(name, payload));
38
49
  ```
39
50
 
40
- ## Usage
51
+ ## Requests
41
52
 
42
- Here’s a basic example of how to use this package. For more details, refer to the package complete
43
- [documentation](https://docs.telegram-mini-apps.com/packages/tma-js-bridge).
53
+ `request` calls a method and waits for an event:
44
54
 
45
55
  ```ts
46
- import { on, postEvent, applyPolyfills } from '@tma.js/bridge';
56
+ import { request, createRequestId, captureSameReq } from '@tma.js/bridge';
47
57
 
48
- // The package uses some polyfills, so let's use them.
49
- applyPolyfills();
58
+ const { button_id } = await request('web_app_open_popup', 'popup_closed', {
59
+ params: { title: 'Hi', message: 'Hello', buttons: [{ id: 'ok', type: 'ok' }] },
60
+ });
50
61
 
51
- // Show the back button, wait for it to be clicked once,
52
- // then hide it.
53
- postEvent('web_app_setup_back_button', { is_visible: true });
62
+ // Waiting for one of several events.
63
+ const { event, payload } = await request(
64
+ 'web_app_request_fullscreen',
65
+ ['fullscreen_changed', 'fullscreen_failed'],
66
+ { timeout: 5000, signal },
67
+ );
68
+
69
+ // Capturing the event related to the request.
70
+ const reqId = createRequestId();
71
+ const { data } = await request('web_app_read_text_from_clipboard', 'clipboard_text_received', {
72
+ params: { req_id: reqId },
73
+ capture: captureSameReq(reqId),
74
+ });
75
+ ```
76
+
77
+ Custom methods have a dedicated helper:
78
+
79
+ ```ts
80
+ import { invokeCustomMethod } from '@tma.js/bridge';
81
+
82
+ const keys = await invokeCustomMethod('getStorageKeys', {});
83
+ ```
84
+
85
+ ## Handling errors
86
+
87
+ Functions failing with expected errors have a `safe` counterpart returning the error instead of
88
+ throwing it. The error type is a union of all possible errors, so the compiler knows what to
89
+ handle:
54
90
 
55
- const off = on('back_button_pressed', () => {
56
- postEvent('web_app_setup_back_button', { is_visible: false });
57
- off();
91
+ ```ts
92
+ import { matchError, safeInvokeCustomMethod } from '@tma.js/bridge';
93
+
94
+ const result = await safeInvokeCustomMethod('getStorageKeys', {}, { timeout: 5000 });
95
+ if (!result.ok) {
96
+ // Compilation fails if any error is left unhandled.
97
+ return matchError(result.error, {
98
+ InvokeCustomMethodFailedError: e => console.error('Method failed:', e.data.error),
99
+ TimeoutError: () => console.error('No response from Telegram'),
100
+ });
101
+ }
102
+ const keys = result.data;
103
+ ```
104
+
105
+ | Function | Safe counterpart | Errors |
106
+ |----------------------------|--------------------------------|--------------------------------------------------|
107
+ | `request` | `safeRequest` | `TimeoutError` |
108
+ | `invokeCustomMethod` | `safeInvokeCustomMethod` | `InvokeCustomMethodFailedError`, `TimeoutError` |
109
+ | `parseLaunchParams` | `safeParseLaunchParams` | `InvalidLaunchParamsError` |
110
+ | `retrieveLaunchParams` | `safeRetrieveLaunchParams` | `LaunchParamsRetrieveError` |
111
+ | `retrieveRawLaunchParams` | `safeRetrieveRawLaunchParams` | `LaunchParamsRetrieveError` |
112
+ | `retrieveRawInitData` | `safeRetrieveRawInitData` | `LaunchParamsRetrieveError` |
113
+ | `createStartParam` | `safeCreateStartParam` | `StartParamTooLongError` |
114
+
115
+ Environment and usage errors are always thrown: `UnknownEnvError` when the app is opened outside
116
+ Telegram, and `MethodUnsupportedError` or `MethodParameterUnsupportedError` from functions created
117
+ with `createPostEvent`. Aborted requests are rejected with `signal.reason`, as other abortable APIs
118
+ are.
119
+
120
+ ## Environment
121
+
122
+ ```ts
123
+ import {
124
+ isTMA,
125
+ isTMAAsync,
126
+ retrieveLaunchParams,
127
+ retrieveRawInitData,
128
+ } from '@tma.js/bridge';
129
+
130
+ isTMA(); // Synchronous check based on environment traits.
131
+ await isTMAAsync(); // Asks the Telegram client and waits for a response.
132
+
133
+ const { tgWebAppPlatform, tgWebAppVersion, tgWebAppThemeParams } = retrieveLaunchParams();
134
+ const initData = retrieveRawInitData(); // Send it to your server.
135
+ ```
136
+
137
+ Launch parameters are looked up in the URL, the navigation entry, and the session storage
138
+ (including the one written by the official SDK), so they survive page reloads.
139
+
140
+ ## Mocking
141
+
142
+ `mockTelegramEnv` imitates the Telegram client. Outside iframes, it defines
143
+ `window.TelegramWebviewProxy`, so calls made by other libraries, including the official SDK, are
144
+ intercepted too. In Telegram Web (iframe), only calls made by this package are intercepted.
145
+
146
+ ```ts
147
+ import { emitEvent, mockTelegramEnv } from '@tma.js/bridge';
148
+
149
+ const restore = mockTelegramEnv({
150
+ launchParams: {
151
+ tgWebAppPlatform: 'tdesktop',
152
+ tgWebAppVersion: '9.0',
153
+ tgWebAppThemeParams: { bg_color: '#17212b', text_color: '#f5f5f5' },
154
+ },
155
+ onMethod({ name }, next) {
156
+ if (name === 'web_app_request_theme') {
157
+ return emitEvent('theme_changed', { theme_params: { bg_color: '#17212b' } });
158
+ }
159
+ next();
160
+ },
58
161
  });
59
162
  ```
163
+
164
+ ## Start parameter
165
+
166
+ ```ts
167
+ import { createStartParam, decodeStartParam } from '@tma.js/bridge';
168
+
169
+ const param = createStartParam({ page: 'product', id: 42 });
170
+ decodeStartParam(param, 'json'); // { page: 'product', id: 42 }
171
+ ```
172
+
173
+ ## Debugging
174
+
175
+ ```ts
176
+ import { setDebug, setLogger } from '@tma.js/bridge';
177
+
178
+ setDebug(true); // Logs outgoing methods and incoming events.
179
+ setLogger(myLogger); // { log, warn, error }
180
+ ```
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Window properties used by the Telegram clients and the official SDK to communicate with
3
+ * a mini app.
4
+ */
5
+ export interface TelegramWindow {
6
+ /**
7
+ * Telegram for iOS, macOS, Android and Telegram Desktop.
8
+ */
9
+ TelegramWebviewProxy?: {
10
+ postEvent: (eventType: string, eventData: string) => void;
11
+ };
12
+ /**
13
+ * Telegram for Windows Phone.
14
+ */
15
+ external?: {
16
+ notify?: (message: string) => void;
17
+ };
18
+ Telegram?: {
19
+ WebView?: {
20
+ receiveEvent?: ReceiveEventFn;
21
+ [key: string]: unknown;
22
+ };
23
+ [key: string]: unknown;
24
+ };
25
+ TelegramGameProxy?: {
26
+ receiveEvent?: ReceiveEventFn;
27
+ [key: string]: unknown;
28
+ };
29
+ TelegramGameProxy_receiveEvent?: ReceiveEventFn;
30
+ }
31
+ export type ReceiveEventFn = (eventType: string, eventData?: unknown) => void;
32
+ /**
33
+ * @returns The current window with Telegram-specific properties typed.
34
+ */
35
+ export declare function telegramWindow(): Window & TelegramWindow;
36
+ /**
37
+ * @returns True if the current environment is an iframe. Telegram Web clients open mini apps
38
+ * in an iframe.
39
+ * @see https://stackoverflow.com/a/326076
40
+ */
41
+ export declare function isIframe(): boolean;
42
+ /**
43
+ * @returns True if the `window.TelegramWebviewProxy.postEvent` function exists. Native Telegram
44
+ * clients define it to receive method calls.
45
+ */
46
+ export declare function hasWebviewProxy(): boolean;
47
+ /**
48
+ * @returns True if the current environment looks like a Telegram Mini App: the Telegram webview
49
+ * proxy is defined, or launch parameters are available.
50
+ *
51
+ * Use `isTMAAsync` for a stricter check.
52
+ */
53
+ export declare function isTMA(): boolean;
54
+ /**
55
+ * Checks if the current environment is a Telegram Mini App by calling a method and waiting for
56
+ * the Telegram client response.
57
+ * @param options - additional options.
58
+ */
59
+ export declare function isTMAAsync(options?: {
60
+ /**
61
+ * Time in milliseconds to wait for the response.
62
+ * @default 100
63
+ */
64
+ timeout?: number;
65
+ /**
66
+ * Signal to abort the check.
67
+ */
68
+ signal?: AbortSignal;
69
+ }): Promise<boolean>;
@@ -1,10 +1,30 @@
1
- declare const MethodUnsupportedError_base: import('error-kid').ErrorClass<[method: string, version: string]>;
1
+ declare const UnknownEnvError_base: import('error-kid').ErrorClass<[], "UnknownEnvError">;
2
+ /**
3
+ * Thrown when the current environment provides no known way to communicate with the Telegram
4
+ * client. Usually, it means the app was opened outside Telegram.
5
+ */
6
+ export declare class UnknownEnvError extends /* @__PURE__ */ UnknownEnvError_base {
7
+ }
8
+ declare const MethodUnsupportedError_base: import('error-kid').ErrorClassWithData<[method: string, version: string], {
9
+ method: string;
10
+ version: string;
11
+ }, "MethodUnsupportedError">;
12
+ /**
13
+ * Thrown when a method is not supported in the current Mini Apps version.
14
+ */
2
15
  export declare class MethodUnsupportedError extends /* @__PURE__ */ MethodUnsupportedError_base {
3
16
  }
4
- declare const MethodParameterUnsupportedError_base: import('error-kid').ErrorClass<[method: string, param: string, version: string]>;
17
+ declare const MethodParameterUnsupportedError_base: import('error-kid').ErrorClassWithData<[method: string, param: string, version: string], {
18
+ method: string;
19
+ param: string;
20
+ version: string;
21
+ }, "MethodParameterUnsupportedError">;
22
+ /**
23
+ * Thrown when a method parameter is not supported in the current Mini Apps version.
24
+ */
5
25
  export declare class MethodParameterUnsupportedError extends /* @__PURE__ */ MethodParameterUnsupportedError_base {
6
26
  }
7
- declare const LaunchParamsRetrieveError_base: import('error-kid').ErrorClassWithData<[{
27
+ declare const LaunchParamsRetrieveError_base: import('error-kid').ErrorClassWithData<[errors: {
8
28
  source: string;
9
29
  error: unknown;
10
30
  }[]], {
@@ -12,16 +32,42 @@ declare const LaunchParamsRetrieveError_base: import('error-kid').ErrorClassWith
12
32
  source: string;
13
33
  error: unknown;
14
34
  }[];
15
- }>;
35
+ }, "LaunchParamsRetrieveError">;
36
+ /**
37
+ * Thrown when launch parameters can't be found in any known source.
38
+ */
16
39
  export declare class LaunchParamsRetrieveError extends /* @__PURE__ */ LaunchParamsRetrieveError_base {
17
40
  }
18
- declare const InvalidLaunchParamsError_base: import('error-kid').ErrorClass<[launchParams: string, cause: unknown]>;
41
+ declare const InvalidLaunchParamsError_base: import('error-kid').ErrorClassWithData<[_value: string, cause?: unknown], {
42
+ value: string;
43
+ }, "InvalidLaunchParamsError">;
44
+ /**
45
+ * Thrown when a value doesn't represent valid launch parameters.
46
+ */
19
47
  export declare class InvalidLaunchParamsError extends /* @__PURE__ */ InvalidLaunchParamsError_base {
20
48
  }
21
- declare const UnknownEnvError_base: import('error-kid').ErrorClass<[]>;
22
- export declare class UnknownEnvError extends /* @__PURE__ */ UnknownEnvError_base {
23
- }
24
- declare const InvokeCustomMethodFailedError_base: import('error-kid').ErrorClass<[error: string]>;
49
+ declare const InvokeCustomMethodFailedError_base: import('error-kid').ErrorClassWithData<[error: string], {
50
+ error: string;
51
+ }, "InvokeCustomMethodFailedError">;
52
+ /**
53
+ * Thrown when a custom method invocation completed with an error.
54
+ */
25
55
  export declare class InvokeCustomMethodFailedError extends /* @__PURE__ */ InvokeCustomMethodFailedError_base {
26
56
  }
57
+ declare const TimeoutError_base: import('error-kid').ErrorClassWithData<[timeout: number], {
58
+ timeout: number;
59
+ }, "TimeoutError">;
60
+ /**
61
+ * Thrown when an operation didn't complete in time.
62
+ */
63
+ export declare class TimeoutError extends /* @__PURE__ */ TimeoutError_base {
64
+ }
65
+ declare const StartParamTooLongError_base: import('error-kid').ErrorClassWithData<[length: number], {
66
+ length: number;
67
+ }, "StartParamTooLongError">;
68
+ /**
69
+ * Thrown when a value is too long to be used as a start parameter.
70
+ */
71
+ export declare class StartParamTooLongError extends /* @__PURE__ */ StartParamTooLongError_base {
72
+ }
27
73
  export {};
@@ -0,0 +1,64 @@
1
+ import { AnyEventListener, EventListener, EventName, EventPayload } from './types/index.js';
2
+ export interface OnOptions {
3
+ /**
4
+ * Remove the listener after the first call.
5
+ */
6
+ once?: boolean;
7
+ /**
8
+ * Signal removing the listener when aborted.
9
+ */
10
+ signal?: AbortSignal;
11
+ }
12
+ /**
13
+ * Arguments following the event name when emitting the event.
14
+ */
15
+ export type EmitEventArgs<E extends EventName> = [EventPayload<E>] extends [never] ? [] : [payload: EventPayload<E>];
16
+ /**
17
+ * Schema of a message sent by Telegram Web clients via `window.postMessage`.
18
+ */
19
+ export declare const MiniAppsMessageSchema: import('valibot').SchemaWithPipe<readonly [import('valibot').StringSchema<undefined>, import('valibot').ParseJsonAction<string, undefined, undefined>, import('valibot').LooseObjectSchema<{
20
+ readonly eventType: import('valibot').StringSchema<undefined>;
21
+ readonly eventData: import('valibot').OptionalSchema<import('valibot').UnknownSchema, undefined>;
22
+ }, undefined>]>;
23
+ /**
24
+ * Adds a listener of the specified Mini Apps event. Adding the same listener twice has no
25
+ * effect.
26
+ * @param event - event name.
27
+ * @param listener - event listener.
28
+ * @param options - additional options.
29
+ * @returns Function removing the listener.
30
+ * @see https://docs.telegram-mini-apps.com/platform/events
31
+ */
32
+ export declare function onEvent<E extends EventName>(event: E, listener: EventListener<E>, options?: OnOptions): VoidFunction;
33
+ /**
34
+ * Removes a listener of the specified Mini Apps event.
35
+ * @param event - event name.
36
+ * @param listener - event listener.
37
+ */
38
+ export declare function offEvent<E extends EventName>(event: E, listener: EventListener<E>): void;
39
+ /**
40
+ * Adds a listener of all Mini Apps events. Adding the same listener twice has no effect.
41
+ * @param listener - events listener.
42
+ * @param options - additional options.
43
+ * @returns Function removing the listener.
44
+ */
45
+ export declare function onAnyEvent(listener: AnyEventListener, options?: OnOptions): VoidFunction;
46
+ /**
47
+ * Removes a listener of all Mini Apps events.
48
+ * @param listener - events listener.
49
+ */
50
+ export declare function offAnyEvent(listener: AnyEventListener): void;
51
+ /**
52
+ * Removes all event listeners and stops receiving events from the Telegram client.
53
+ */
54
+ export declare function offAll(): void;
55
+ /**
56
+ * Emits an event as if it was sent by the Telegram client. Use it to imitate the Telegram
57
+ * client, for example, in the `mockTelegramEnv` function `onEvent` option.
58
+ *
59
+ * The event is delivered the same way a real Telegram client would deliver it, so other
60
+ * libraries (e.g. the official SDK) receive it too.
61
+ * @param event - event name.
62
+ * @param args - event payload.
63
+ */
64
+ export declare function emitEvent<E extends EventName>(event: E, ...args: EmitEventArgs<E>): void;
@@ -1,26 +1,14 @@
1
- export { hasWebviewProxy } from './env/hasWebviewProxy.js';
2
- export { isIframe } from './env/isIframe.js';
3
- export { isTMA, isTMAFp, type isTMAError } from './env/isTMA.js';
4
- export { mockTelegramEnv } from './env/mockTelegramEnv.js';
5
- export { off, offAll, on } from './events/emitter.js';
6
- export { emitEvent } from './events/emitEvent.js';
7
- export type { EventListener, SubscribeListener, Events, WriteAccessRequestedStatus, EmojiStatusAccessRequestedStatus, BiometryAuthRequestStatus, BiometryTokenUpdateStatus, BiometryType, EmojiStatusFailedError, EventName, EventPayload, EventWithoutPayload, EventWithPayload, PhoneRequestedStatus, FullScreenErrorStatus, HomeScreenStatus, InvoiceStatus, SafeAreaInsets, } from './events/types/index.js';
8
- export { captureSameReq } from './methods/captureSameReq.js';
9
- export { createPostEvent, type CreatePostEventMode, type OnUnsupportedFn, } from './methods/createPostEvent.js';
10
- export { getReleaseVersion } from './methods/getReleaseVersion.js';
11
- export { postEvent, postEventFp, type PostEventFn, type PostEventFpFn, type PostEventError, } from './methods/postEvent.js';
12
- export { postMessage, type PostMessage } from './methods/postMessage.js';
13
- export { supports } from './methods/supports.js';
14
- export type { AnyHapticFeedbackParams, AnyInvokeCustomMethodParams, CreateMethodParams, CustomMethodName, ImpactHapticFeedbackParams, ImpactHapticFeedbackStyle, CustomMethodsParams, CustomMethodParams, MethodName, MethodVersionedParams, NotificationHapticFeedbackParams, NotificationHapticFeedbackType, Methods, SelectionHapticFeedbackParams, MethodNameWithOptionalParams, MethodNameWithoutParams, MethodNameWithRequiredParams, MethodNameWithVersionedParams, MethodParams, PopupParams, BackgroundColor, BottomBarColor, HeaderColorKey, PopupButton, OpenLinkBrowser, SecondaryButtonPosition, SwitchInlineQueryChatType, } from './methods/types/index.js';
15
- export { compareVersions } from './utils/compareVersions.js';
16
- export { invokeCustomMethod, invokeCustomMethodFp, type InvokeCustomMethodFn, type InvokeCustomMethodOptions, type InvokeCustomMethodFpFn, type InvokeCustomMethodError, type InvokeCustomMethodFpOptions, } from './utils/invokeCustomMethod.js';
17
- export { request, requestFp, type RequestCaptureEventFn, type RequestCaptureEventsFn, type RequestCaptureFn, type RequestCaptureFnEventsPayload, type RequestFn, type RequestOptions, type RequestResult, type RequestError, type RequestFpOptions, type RequestFpFn, } from './utils/request.js';
18
- export { request2, request2Fp, type Request2CaptureEventFn, type Request2CaptureEventsFn, type Request2CaptureFn, type Request2CaptureFnEventsPayload, type Request2Fn, type Request2Options, type Request2Result, type Request2Error, type Request2FpOptions, type Request2FpFn, } from './utils/request2.js';
19
- export { applyPolyfills } from './applyPolyfills.js';
20
- export { decodeBase64Url, encodeBase64Url, decodeBase64UrlFp, type DecodeBase64UrlError, } from './base64-url.js';
21
- export { LaunchParamsRetrieveError, InvalidLaunchParamsError, InvokeCustomMethodFailedError, MethodParameterUnsupportedError, MethodUnsupportedError, UnknownEnvError, } from './errors.js';
22
- export { setDebug, debug, resetGlobals, postMessageImpl, logger, setTargetOrigin, targetOrigin, } from './globals.js';
23
- export { retrieveLaunchParams, retrieveRawInitData, retrieveRawInitDataFp, retrieveRawLaunchParams, retrieveRawLaunchParamsFp, retrieveLaunchParamsFp, type RetrieveLaunchParamsError, type RetrieveLaunchParamsResult, type RetrieveRawInitDataError, type RetrieveRawLaunchParamsError, } from './launch-params.js';
24
- export { createStartParam, createStartParamFp, decodeStartParam, decodeStartParamFp, isSafeToCreateStartParam, } from './start-param.js';
25
- export { createLogger, deepSnakeToCamelObjKeys, type DeepConvertSnakeKeysToCamelCase, type Logger, type LoggerFn, type LoggerForceFn, type LoggerOptions, type LogLevel, } from '@tma.js/toolkit';
26
- export { CancelledError, TimeoutError, } from 'better-promises';
1
+ export { matchError } from 'error-kid';
2
+ export { hasWebviewProxy, isIframe, isTMA, isTMAAsync } from './env.js';
3
+ export { InvalidLaunchParamsError, InvokeCustomMethodFailedError, LaunchParamsRetrieveError, MethodParameterUnsupportedError, MethodUnsupportedError, StartParamTooLongError, TimeoutError, UnknownEnvError, } from './errors.js';
4
+ export { emitEvent, offAll, offAnyEvent, offEvent, onAnyEvent, onEvent, type EmitEventArgs, type OnOptions, } from './events.js';
5
+ export { invokeCustomMethod, safeInvokeCustomMethod, type InvokeCustomMethodOptions, } from './invokeCustomMethod.js';
6
+ export { parseLaunchParams, retrieveLaunchParams, retrieveRawInitData, retrieveRawLaunchParams, safeParseLaunchParams, safeRetrieveLaunchParams, safeRetrieveRawInitData, safeRetrieveRawLaunchParams, serializeLaunchParams, type LaunchParams, } from './launch-params.js';
7
+ export { getLogger, isDebug, setDebug, setLogger, type Logger } from './logger.js';
8
+ export { mockTelegramEnv, type MockedMethodCall, type MockTelegramEnvOptions, } from './mockTelegramEnv.js';
9
+ export { getTargetOrigin, postEvent, setTargetOrigin, type PostEventFn } from './post-event.js';
10
+ export { captureSameReq, createRequestId, request, safeRequest, type RequestFnArgs, type RequestFnOptions, type RequestOptions, type RequestResult, } from './request.js';
11
+ export { createStartParam, decodeBase64Url, decodeStartParam, encodeBase64Url, isSafeToCreateStartParam, safeCreateStartParam, } from './start-param.js';
12
+ export { err, ok, type Result, throwing, unwrap } from './result.js';
13
+ export { compareVersions, createPostEvent, getReleaseVersion, supports, type MethodNameWithVersionedParams, type MethodVersionedParam, type OnUnsupportedFn, } from './versions.js';
14
+ export type * from './types/index.js';
@@ -0,0 +1,33 @@
1
+ import { InvokeCustomMethodFailedError, TimeoutError } from './errors.js';
2
+ import { RequestOptions } from './request.js';
3
+ import { Result } from './result.js';
4
+ import { CustomMethodName, CustomMethodParams } from './types/index.js';
5
+ export interface InvokeCustomMethodOptions extends Omit<RequestOptions<'custom_method_invoked'>, 'capture'> {
6
+ /**
7
+ * Request identifier. Generated automatically if omitted.
8
+ */
9
+ requestId?: string;
10
+ }
11
+ /**
12
+ * Invokes a custom method and returns its result.
13
+ * @param method - method name.
14
+ * @param params - method parameters.
15
+ * @param options - additional options.
16
+ * @returns Method result, or one of the errors:
17
+ * - `InvokeCustomMethodFailedError`: the method returned an error;
18
+ * - `TimeoutError`: the timeout was reached.
19
+ */
20
+ export declare function safeInvokeCustomMethod<M extends CustomMethodName>(method: M, params: CustomMethodParams<M>, options?: InvokeCustomMethodOptions): Promise<Result<InvokeCustomMethodFailedError | TimeoutError, unknown>>;
21
+ export declare function safeInvokeCustomMethod(method: string, params: object, options?: InvokeCustomMethodOptions): Promise<Result<InvokeCustomMethodFailedError | TimeoutError, unknown>>;
22
+ /**
23
+ * Invokes a custom method and returns its result.
24
+ *
25
+ * Throwing version of `safeInvokeCustomMethod`.
26
+ * @param method - method name.
27
+ * @param params - method parameters.
28
+ * @param options - additional options.
29
+ * @throws {InvokeCustomMethodFailedError} The method returned an error.
30
+ * @throws {TimeoutError} The timeout was reached.
31
+ */
32
+ export declare function invokeCustomMethod<M extends CustomMethodName>(method: M, params: CustomMethodParams<M>, options?: InvokeCustomMethodOptions): Promise<unknown>;
33
+ export declare function invokeCustomMethod(method: string, params: object, options?: InvokeCustomMethodOptions): Promise<unknown>;
@@ -1,31 +1,113 @@
1
- import { LaunchParamsGenType, ParseLaunchParamsQueryError } from '@tma.js/transformers';
2
- import { either as E, option as O } from 'fp-ts';
3
- import { LaunchParamsRetrieveError } from './errors.js';
4
- export type RetrieveRawInitDataError = RetrieveRawLaunchParamsError;
5
- export type RetrieveRawLaunchParamsError = LaunchParamsRetrieveError;
6
- export type RetrieveLaunchParamsError = RetrieveRawLaunchParamsError | ParseLaunchParamsQueryError;
7
- export type RetrieveLaunchParamsResult = LaunchParamsGenType;
1
+ import { InvalidLaunchParamsError, LaunchParamsRetrieveError } from './errors.js';
2
+ import { Result } from './result.js';
3
+ import { Platform, ThemeParams, Version } from './types/index.js';
8
4
  /**
9
- * @returns Launch parameters from any known source.
5
+ * Launch parameters passed by the Telegram client to the mini app.
6
+ * @see https://docs.telegram-mini-apps.com/platform/launch-parameters
10
7
  */
11
- export declare function retrieveLaunchParamsFp(): E.Either<RetrieveLaunchParamsError, RetrieveLaunchParamsResult>;
8
+ export interface LaunchParams {
9
+ /**
10
+ * True if the mini app was launched in inline mode.
11
+ */
12
+ tgWebAppBotInline?: boolean;
13
+ /**
14
+ * Init data in the raw format. Pass it to your server to authorize the user.
15
+ * @see https://docs.telegram-mini-apps.com/platform/init-data
16
+ */
17
+ tgWebAppData?: string;
18
+ /**
19
+ * Default theme colors.
20
+ */
21
+ tgWebAppDefaultColors?: ThemeParams;
22
+ /**
23
+ * True if the mini app was launched in fullscreen mode.
24
+ */
25
+ tgWebAppFullscreen?: boolean;
26
+ /**
27
+ * Telegram client platform.
28
+ */
29
+ tgWebAppPlatform: Platform;
30
+ /**
31
+ * True if the Settings Button should be displayed.
32
+ */
33
+ tgWebAppShowSettings?: boolean;
34
+ /**
35
+ * Start parameter passed in the mini app link.
36
+ * @see https://docs.telegram-mini-apps.com/platform/start-parameter
37
+ */
38
+ tgWebAppStartParam?: string;
39
+ /**
40
+ * Theme parameters.
41
+ */
42
+ tgWebAppThemeParams: ThemeParams;
43
+ /**
44
+ * Mini Apps version supported by the Telegram client.
45
+ */
46
+ tgWebAppVersion: Version;
47
+ }
12
48
  /**
13
- * @see retrieveLaunchParamsFp
49
+ * Parses launch parameters from their query representation.
50
+ * @param value - launch parameters query.
51
+ * @returns Launch parameters, or `InvalidLaunchParamsError` if the value doesn't represent
52
+ * valid launch parameters.
14
53
  */
15
- export declare const retrieveLaunchParams: () => RetrieveLaunchParamsResult;
54
+ export declare function safeParseLaunchParams(value: string | URLSearchParams): Result<InvalidLaunchParamsError, LaunchParams>;
16
55
  /**
17
- * @returns Raw init data from any known source.
56
+ * Parses launch parameters from their query representation.
57
+ *
58
+ * Throwing version of `safeParseLaunchParams`.
59
+ * @param value - launch parameters query.
60
+ * @throws {InvalidLaunchParamsError} The value doesn't represent valid launch parameters.
18
61
  */
19
- export declare function retrieveRawInitDataFp(): E.Either<RetrieveRawInitDataError, O.Option<string>>;
62
+ export declare const parseLaunchParams: (value: string | URLSearchParams) => LaunchParams;
20
63
  /**
21
- * @see retrieveRawInitDataFp
64
+ * Converts launch parameters to their query representation.
65
+ * @param value - launch parameters.
22
66
  */
23
- export declare function retrieveRawInitData(): string | undefined;
67
+ export declare function serializeLaunchParams(value: LaunchParams): string;
24
68
  /**
25
- * @returns Launch parameters in a raw format from any known source.
69
+ * Saves launch parameters to the session storage, so they could be retrieved after the page
70
+ * reload.
71
+ * @param value - launch parameters query.
26
72
  */
27
- export declare function retrieveRawLaunchParamsFp(): E.Either<RetrieveRawLaunchParamsError, string>;
73
+ export declare function saveLaunchParams(value: string): void;
28
74
  /**
29
- * @see retrieveRawLaunchParamsFp
75
+ * Retrieves launch parameters in the raw format from any known source and saves them in
76
+ * the session storage.
77
+ * @returns Launch parameters, or `LaunchParamsRetrieveError` if they were not found.
30
78
  */
31
- export declare const retrieveRawLaunchParams: (() => string) & {};
79
+ export declare function safeRetrieveRawLaunchParams(): Result<LaunchParamsRetrieveError, string>;
80
+ /**
81
+ * Retrieves launch parameters in the raw format from any known source and saves them in
82
+ * the session storage.
83
+ *
84
+ * Throwing version of `safeRetrieveRawLaunchParams`.
85
+ * @throws {LaunchParamsRetrieveError} Launch parameters were not found.
86
+ */
87
+ export declare const retrieveRawLaunchParams: () => string;
88
+ /**
89
+ * Retrieves launch parameters from any known source.
90
+ * @returns Launch parameters, or `LaunchParamsRetrieveError` if they were not found.
91
+ */
92
+ export declare function safeRetrieveLaunchParams(): Result<LaunchParamsRetrieveError, LaunchParams>;
93
+ /**
94
+ * Retrieves launch parameters from any known source.
95
+ *
96
+ * Throwing version of `safeRetrieveLaunchParams`.
97
+ * @throws {LaunchParamsRetrieveError} Launch parameters were not found.
98
+ */
99
+ export declare const retrieveLaunchParams: () => LaunchParams;
100
+ /**
101
+ * Retrieves init data in the raw format. Pass it to your server to authorize the user.
102
+ * @returns Init data (`undefined` if it is missing in launch parameters), or
103
+ * `LaunchParamsRetrieveError` if launch parameters were not found.
104
+ */
105
+ export declare function safeRetrieveRawInitData(): Result<LaunchParamsRetrieveError, string | undefined>;
106
+ /**
107
+ * Retrieves init data in the raw format. Pass it to your server to authorize the user.
108
+ *
109
+ * Throwing version of `safeRetrieveRawInitData`.
110
+ * @returns Init data, or `undefined` if it is missing in launch parameters.
111
+ * @throws {LaunchParamsRetrieveError} Launch parameters were not found.
112
+ */
113
+ export declare const retrieveRawInitData: () => string | undefined;