@vbotma/bridge 2.2.4

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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +59 -0
  3. package/dist/dts/applyPolyfills.d.ts +5 -0
  4. package/dist/dts/base64-url.d.ts +24 -0
  5. package/dist/dts/env/hasWebviewProxy.d.ts +10 -0
  6. package/dist/dts/env/isIframe.d.ts +5 -0
  7. package/dist/dts/env/isVBMA.d.ts +31 -0
  8. package/dist/dts/env/mockVBotEnv.d.ts +60 -0
  9. package/dist/dts/errors.d.ts +27 -0
  10. package/dist/dts/events/createEmitter.d.ts +58 -0
  11. package/dist/dts/events/emitEvent.d.ts +33 -0
  12. package/dist/dts/events/emitter.d.ts +2 -0
  13. package/dist/dts/events/types/events.d.ts +780 -0
  14. package/dist/dts/events/types/index.d.ts +3 -0
  15. package/dist/dts/events/types/listening.d.ts +5 -0
  16. package/dist/dts/events/types/misc.d.ts +16 -0
  17. package/dist/dts/globals.d.ts +53 -0
  18. package/dist/dts/index.d.ts +26 -0
  19. package/dist/dts/launch-params.d.ts +31 -0
  20. package/dist/dts/methods/captureSameReq.d.ts +10 -0
  21. package/dist/dts/methods/createPostEvent.d.ts +30 -0
  22. package/dist/dts/methods/getReleaseVersion.d.ts +15 -0
  23. package/dist/dts/methods/postEvent.d.ts +35 -0
  24. package/dist/dts/methods/postMessage.d.ts +7 -0
  25. package/dist/dts/methods/supports.d.ts +15 -0
  26. package/dist/dts/methods/types/custom-method.d.ts +59 -0
  27. package/dist/dts/methods/types/haptic-feedback.d.ts +40 -0
  28. package/dist/dts/methods/types/index.d.ts +7 -0
  29. package/dist/dts/methods/types/methods.d.ts +807 -0
  30. package/dist/dts/methods/types/misc.d.ts +27 -0
  31. package/dist/dts/methods/types/notification.d.ts +20 -0
  32. package/dist/dts/methods/types/popup.d.ts +49 -0
  33. package/dist/dts/methods/types/utils.d.ts +9 -0
  34. package/dist/dts/obj-prop-helpers.d.ts +39 -0
  35. package/dist/dts/start-param.d.ts +52 -0
  36. package/dist/dts/utils/compareVersions.d.ts +10 -0
  37. package/dist/dts/utils/invokeCustomMethod.d.ts +34 -0
  38. package/dist/dts/utils/request.d.ts +102 -0
  39. package/dist/dts/utils/request2.d.ts +62 -0
  40. package/dist/index.cjs +4 -0
  41. package/dist/index.cjs.map +1 -0
  42. package/dist/index.iife.js +4 -0
  43. package/dist/index.iife.js.map +1 -0
  44. package/dist/index.js +758 -0
  45. package/dist/index.js.map +1 -0
  46. package/package.json +54 -0
@@ -0,0 +1,27 @@
1
+ import { RGB } from '@vbotma/types';
2
+ type KnownColorKey = 'bg_color' | 'secondary_bg_color';
3
+ /**
4
+ * Color key which could be used to update header color.
5
+ */
6
+ export type HeaderColorKey = KnownColorKey;
7
+ /**
8
+ * Color key which could be used to update Mini App background color.
9
+ */
10
+ export type BackgroundColor = RGB;
11
+ /**
12
+ * Color key which could be used to update bottom bar background color.
13
+ */
14
+ export type BottomBarColor = RGB;
15
+ /**
16
+ * Position of the secondary button related to the main one.
17
+ */
18
+ export type SecondaryButtonPosition = 'left' | 'right' | 'top' | 'bottom';
19
+ /**
20
+ * Values expected by the `web_app_open_link.try_browser` option.
21
+ */
22
+ export type OpenLinkBrowser = 'google-chrome' | 'chrome' | 'mozilla-firefox' | 'firefox' | 'microsoft-edge' | 'edge' | 'opera' | 'opera-mini' | 'brave' | 'brave-browser' | 'duckduckgo' | 'duckduckgo-browser' | 'samsung' | 'samsung-browser' | 'vivaldi' | 'vivaldi-browser' | 'kiwi' | 'kiwi-browser' | 'uc' | 'uc-browser' | 'tor' | 'tor-browser';
23
+ /**
24
+ * Chat type which could be used when calling `web_app_switch_inline_query` method.
25
+ */
26
+ export type SwitchInlineQueryChatType = 'users' | 'bots' | 'groups' | 'channels';
27
+ export {};
@@ -0,0 +1,20 @@
1
+ export type NotificationType = 'default' | 'info' | 'success' | 'warning' | 'error';
2
+ export interface NotificationParams {
3
+ /**
4
+ * Unique identifier for this notification.
5
+ */
6
+ id: string;
7
+ /**
8
+ * The message content to display in the notification.
9
+ */
10
+ message: string;
11
+ /**
12
+ * Optional title for the notification.
13
+ */
14
+ title?: string;
15
+ /**
16
+ * The type of notification.
17
+ * @default 'default'
18
+ */
19
+ type?: NotificationType;
20
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Describes the native popup.
3
+ */
4
+ export interface PopupParams {
5
+ /**
6
+ * The text to be displayed in the popup title, 0-64 characters.
7
+ */
8
+ title: string;
9
+ /**
10
+ * The message to be displayed in the body of the popup, 1-256 characters.
11
+ */
12
+ message: string;
13
+ /**
14
+ * List of buttons to be displayed in the popup, 1-3 buttons.
15
+ */
16
+ buttons: PopupButton[];
17
+ }
18
+ /**
19
+ * Describes the native popup button.
20
+ * @see https://docs.vbot-mini-apps.com/platform/methods#popupbutton
21
+ */
22
+ export type PopupButton = {
23
+ /**
24
+ * Identifier of the button, 0-64 characters.
25
+ */
26
+ id: string;
27
+ } & ({
28
+ /**
29
+ * Type of the button:
30
+ * - `default`, a button with the default style;
31
+ * - `destructive`, a button with a style that indicates a destructive
32
+ * action (e.g. "Remove", "Delete", etc.).
33
+ *
34
+ * @default "default"
35
+ */
36
+ type?: 'default' | 'destructive';
37
+ /**
38
+ * The text to be displayed on the button, 0-64 characters.
39
+ */
40
+ text: string;
41
+ } | {
42
+ /**
43
+ * Type of the button:
44
+ * - `ok`, a button with the localized text "OK";
45
+ * - `close`, a button with the localized text "Close";
46
+ * - `cancel`, a button with the localized text "Cancel".
47
+ */
48
+ type: 'ok' | 'close' | 'cancel';
49
+ });
@@ -0,0 +1,9 @@
1
+ type UnionKeys<T> = T extends T ? keyof T : never;
2
+ /**
3
+ * Creates Mini Apps method parameters types.
4
+ */
5
+ export interface CreateMethodParams<Params = never, VersionedParam extends UnionKeys<Params> = never> {
6
+ params: Params;
7
+ versionedParams: VersionedParam;
8
+ }
9
+ export {};
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Defines a property, that is a functions compose. Trying to set a value in this property
3
+ * will lead to adding it to a function's pool. The property value will always be equal to a
4
+ * function, calling all collected functions in the pool.
5
+ *
6
+ * Returned function performs a cleanup. It does one of the following:
7
+ * 1. Removes the property if no functions were to the pool added other than the initial one.
8
+ * 2. Sets the value equal to the first added function to the pool after the initial one if
9
+ * the only one additional function was added at all. In other words, if the pool length is equal
10
+ * to 2, the second item will be selected as the property value.
11
+ * 3. Leaves the value equal to a function calling all pool functions, but removes the initially
12
+ * added one.
13
+ * @param obj - object.
14
+ * @param propertyName - object property.
15
+ * @param initialFn - an initial function to set.
16
+ */
17
+ export declare function defineFnComposer(obj: any, propertyName: string, initialFn: (...args: any) => any): void;
18
+ /**
19
+ * Wires the specified property in the object preventing it from being overwritten. Instead, it
20
+ * enhances the previous value by merging the current one with the passed one.
21
+ * @param obj - object.
22
+ * @param prop - object property to rewire.
23
+ */
24
+ export declare function defineMergeableProperty(obj: any, prop: string): void;
25
+ /**
26
+ * Defines an enumerable and configurable property with a getter and setter.
27
+ * @param obj - object.
28
+ * @param prop - object property name.
29
+ * @param get - getter to use.
30
+ * @param set - setter to use.
31
+ */
32
+ export declare function defineProxiedProperty(obj: any, prop: string, get: () => unknown, set: (v: any) => void): void;
33
+ /**
34
+ * Defines an enumerable, configurable and writable property with the initial value.
35
+ * @param obj - object.
36
+ * @param prop - object property name.
37
+ * @param value - value to set.
38
+ */
39
+ export declare function defineStaticProperty(obj: any, prop: string, value: any): void;
@@ -0,0 +1,52 @@
1
+ import { either as E, json as J } from 'fp-ts';
2
+ import { DecodeBase64UrlError } from './base64-url.js';
3
+ /**
4
+ * Creates a safe start parameter value. If the value is not a string, the
5
+ * function applies JSON.stringify to it, so make sure you are not passing an
6
+ * object with circular references.
7
+ *
8
+ * @param value - value to create start parameter from.
9
+ * @see Learn more about start parameter:
10
+ * https://docs.vbot-mini-apps.com/platform/start-parameter
11
+ */
12
+ export declare function createStartParamFp(value: unknown): E.Either<Error, string>;
13
+ /**
14
+ * @see createStartParamFp
15
+ */
16
+ export declare const createStartParam: ((value: unknown) => string) & {};
17
+ /**
18
+ * @see decodeStartParamFp
19
+ */
20
+ export declare function decodeStartParam<T>(value: string, parse: (value: string) => T): T;
21
+ /**
22
+ * @see decodeStartParamFp
23
+ */
24
+ export declare function decodeStartParam(value: string, as: 'json'): J.Json;
25
+ /**
26
+ * @see decodeStartParamFp
27
+ */
28
+ export declare function decodeStartParam(value: string): string;
29
+ /**
30
+ * Decodes a start parameter using a custom parser.
31
+ * @param value - a start parameter value.
32
+ * @param parse - a custom value parser.
33
+ */
34
+ export declare function decodeStartParamFp<L, R>(value: string, parse: (value: string) => E.Either<L, R>): E.Either<L | DecodeBase64UrlError, R>;
35
+ /**
36
+ * Decodes a start parameter assuming that the result is a JSON value.
37
+ * @param value - a start parameter value.
38
+ * @param as - result kind.
39
+ */
40
+ export declare function decodeStartParamFp(value: string, as: 'json'): E.Either<SyntaxError | DecodeBase64UrlError, J.Json>;
41
+ /**
42
+ * Decodes a start parameter and returns its decoded representation.
43
+ * @param value - a value to decode.
44
+ */
45
+ export declare function decodeStartParamFp(value: string): E.Either<DecodeBase64UrlError, string>;
46
+ /**
47
+ * @returns True if the passed value is safe to be used to create a start parameter value from it.
48
+ * If true is returned, the value can be safely passed to the `createStartParam` function.
49
+ * @param value - value to check.
50
+ * @see createStartParam
51
+ */
52
+ export declare function isSafeToCreateStartParam(value: string): boolean;
@@ -0,0 +1,10 @@
1
+ import { Version } from '@vbotma/types';
2
+ /**
3
+ * @param a - first version.
4
+ * @param b - second version.
5
+ * @returns
6
+ * - `1` if the version "a" is greater than "b".
7
+ * - `0` the version "a" is equal to "b".
8
+ * - `-1` the version "a" is lower than "b".
9
+ */
10
+ export declare function compareVersions(a: Version, b: Version): number;
@@ -0,0 +1,34 @@
1
+ import { BetterPromise } from 'better-promises';
2
+ import { taskEither as TE } from 'fp-ts';
3
+ import { InvokeCustomMethodFailedError } from '../errors.js';
4
+ import { CustomMethodName, CustomMethodParams } from '../methods/types/index.js';
5
+ import { Request2Error, Request2FpOptions, Request2Options } from './request2.js';
6
+ export type InvokeCustomMethodError = Request2Error | InvokeCustomMethodFailedError;
7
+ export type InvokeCustomMethodOptions = Omit<Request2Options<'custom_method_invoked'>, 'capture'>;
8
+ export type InvokeCustomMethodFn = typeof invokeCustomMethod;
9
+ export type InvokeCustomMethodFpOptions = Omit<Request2FpOptions<'custom_method_invoked'>, 'capture'>;
10
+ export type InvokeCustomMethodFpFn = typeof invokeCustomMethodFp;
11
+ /**
12
+ * Invokes known custom method. Returns method execution result.
13
+ * @param method - method name.
14
+ * @param params - method parameters.
15
+ * @param requestId - request identifier.
16
+ * @param options - additional options.
17
+ */
18
+ export declare function invokeCustomMethodFp<M extends CustomMethodName>(method: M, params: CustomMethodParams<M>, requestId: string, options?: InvokeCustomMethodFpOptions): TE.TaskEither<InvokeCustomMethodError, unknown>;
19
+ /**
20
+ * Invokes unknown custom method. Returns method execution result.
21
+ * @param method - method name.
22
+ * @param params - method parameters.
23
+ * @param requestId - request identifier.
24
+ * @param options - additional options.
25
+ */
26
+ export declare function invokeCustomMethodFp(method: string, params: object, requestId: string, options?: InvokeCustomMethodFpOptions): TE.TaskEither<Request2Error, unknown>;
27
+ /**
28
+ * @see invokeCustomMethodFp
29
+ */
30
+ export declare function invokeCustomMethod<M extends CustomMethodName>(method: M, params: CustomMethodParams<M>, requestId: string, options?: InvokeCustomMethodOptions): BetterPromise<unknown>;
31
+ /**
32
+ * @see invokeCustomMethodFp
33
+ */
34
+ export declare function invokeCustomMethod(method: string, params: object, requestId: string, options?: InvokeCustomMethodOptions): BetterPromise<unknown>;
@@ -0,0 +1,102 @@
1
+ import { If, IsNever } from '@vbotma/toolkit';
2
+ import { BetterPromise, BetterPromiseOptions, TimeoutError } from 'better-promises';
3
+ import { taskEither as TE } from 'fp-ts';
4
+ import { EventName, EventPayload } from '../events/types/index.js';
5
+ import { PostEventError, PostEventFn, PostEventFpFn } from '../methods/postEvent.js';
6
+ import { MethodNameWithOptionalParams, MethodNameWithoutParams, MethodNameWithRequiredParams, MethodParams } from '../methods/types/index.js';
7
+ type AnyEventName = EventName | EventName[];
8
+ export type RequestError = PostEventError | TimeoutError;
9
+ /**
10
+ * @example
11
+ * { event: 'scan_qr_closed' }
12
+ * @example
13
+ * {
14
+ * event: 'popup_closed',
15
+ * payload: { button_id: 'ok' }
16
+ * }
17
+ */
18
+ export type RequestCaptureFnEventsPayload<E extends EventName[]> = E extends (infer U extends EventName)[] ? {
19
+ [K in U]: If<IsNever<EventPayload<K>>, {
20
+ event: K;
21
+ }, {
22
+ event: K;
23
+ payload: EventPayload<K>;
24
+ }>;
25
+ }[U] : never;
26
+ export type RequestCaptureEventsFn<E extends EventName[]> = (payload: RequestCaptureFnEventsPayload<E>) => boolean;
27
+ export type RequestCaptureEventFn<E extends EventName> = If<IsNever<EventPayload<E>>, () => boolean, (payload: EventPayload<E>) => boolean>;
28
+ export type RequestCaptureFn<E extends AnyEventName> = E extends EventName[] ? RequestCaptureEventsFn<E> : E extends EventName ? RequestCaptureEventFn<E> : never;
29
+ export interface RequestOptions<E extends AnyEventName> extends Omit<RequestFpOptions<E>, 'postEvent'> {
30
+ /**
31
+ * Custom function to call mini apps methods.
32
+ */
33
+ postEvent?: PostEventFn;
34
+ }
35
+ export type RequestResult<E extends AnyEventName> = E extends (infer U extends EventName)[] ? U extends infer K extends EventName ? If<IsNever<EventPayload<K>>, undefined, EventPayload<K>> : never : E extends EventName ? If<IsNever<EventPayload<E>>, undefined, EventPayload<E>> : never;
36
+ export interface RequestFpOptions<E extends AnyEventName> extends Pick<BetterPromiseOptions, 'abortSignal' | 'timeout'> {
37
+ /**
38
+ * A function that should return true if the event should be captured.
39
+ * The first compatible request will be captured if this property is omitted.
40
+ */
41
+ capture?: RequestCaptureFn<E>;
42
+ /**
43
+ * A custom function to call mini apps methods.
44
+ */
45
+ postEvent?: PostEventFpFn;
46
+ }
47
+ export type RequestFn = typeof request;
48
+ export type RequestFpFn = typeof requestFp;
49
+ /**
50
+ * Calls a method waiting for the specified event(-s) to occur.
51
+ * @param method - method name.
52
+ * @param eventOrEvents - tracked event or events.
53
+ * @param options - additional options.
54
+ * @deprecated To be removed in the next major update. Use `request2fp` instead, it provides
55
+ * a proper way of handling multiple events.
56
+ */
57
+ export declare function requestFp<M extends MethodNameWithRequiredParams, E extends AnyEventName, AbortError = never>(method: M, eventOrEvents: E, options: RequestFpOptions<E> & {
58
+ params: MethodParams<M>;
59
+ }): TE.TaskEither<RequestError | AbortError, RequestResult<E>>;
60
+ /**
61
+ * Calls a method waiting for the specified event(-s) to occur.
62
+ * @param method - method name.
63
+ * @param eventOrEvents - tracked event or events.
64
+ * @param options - additional options.
65
+ * @deprecated To be removed in the next major update. Use `request2fp` instead, it provides
66
+ * a proper way of handling multiple events.
67
+ */
68
+ export declare function requestFp<M extends MethodNameWithOptionalParams, E extends AnyEventName, AbortError = never>(method: M, eventOrEvents: E, options?: RequestFpOptions<E> & {
69
+ params?: MethodParams<M>;
70
+ }): TE.TaskEither<RequestError | AbortError, RequestResult<E>>;
71
+ /**
72
+ * Calls a method waiting for the specified event(-s) to occur.
73
+ * @param method - method name.
74
+ * @param eventOrEvents - tracked event or events.
75
+ * @param options - additional options.
76
+ * @deprecated To be removed in the next major update. Use `request2fp` instead, it provides
77
+ * a proper way of handling multiple events.
78
+ */
79
+ export declare function requestFp<M extends MethodNameWithoutParams, E extends AnyEventName, AbortError = never>(method: M, eventOrEvents: E, options?: RequestFpOptions<E>): TE.TaskEither<RequestError | AbortError, RequestResult<E>>;
80
+ /**
81
+ * @see requestFp
82
+ * @deprecated To be removed in the next major update. Use `request2` instead, it provides
83
+ * a proper way of handling multiple events.
84
+ */
85
+ export declare function request<M extends MethodNameWithRequiredParams, E extends AnyEventName>(method: M, eventOrEvents: E, options: RequestOptions<E> & {
86
+ params: MethodParams<M>;
87
+ }): BetterPromise<RequestResult<E>>;
88
+ /**
89
+ * @see requestFp
90
+ * @deprecated To be removed in the next major update. Use `request2` instead, it provides
91
+ * a proper way of handling multiple events.
92
+ */
93
+ export declare function request<M extends MethodNameWithOptionalParams, E extends AnyEventName>(method: M, eventOrEvents: E, options?: RequestOptions<E> & {
94
+ params?: MethodParams<M>;
95
+ }): BetterPromise<RequestResult<E>>;
96
+ /**
97
+ * @see requestFp
98
+ * @deprecated To be removed in the next major update. Use `request2` instead, it provides
99
+ * a proper way of handling multiple events.
100
+ */
101
+ export declare function request<M extends MethodNameWithoutParams, E extends AnyEventName>(method: M, eventOrEvents: E, options?: RequestOptions<E>): BetterPromise<RequestResult<E>>;
102
+ export {};
@@ -0,0 +1,62 @@
1
+ import { If, IsNever } from '@vbotma/toolkit';
2
+ import { BetterPromise } from 'better-promises';
3
+ import { taskEither as TE } from 'fp-ts';
4
+ import { EventName, EventPayload } from '../events/types/index.js';
5
+ import { MethodNameWithOptionalParams, MethodNameWithRequiredParams, MethodNameWithoutParams, MethodParams } from '../methods/types/index.js';
6
+ import { RequestCaptureEventFn, RequestCaptureEventsFn, RequestCaptureFn, RequestError, RequestFpOptions, RequestOptions, RequestCaptureFnEventsPayload } from './request.js';
7
+ type AnyEventName = EventName | EventName[];
8
+ export type Request2Error = RequestError;
9
+ export type Request2CaptureEventsFn<E extends EventName[]> = RequestCaptureEventsFn<E>;
10
+ export type Request2CaptureEventFn<E extends EventName> = RequestCaptureEventFn<E>;
11
+ export type Request2CaptureFn<E extends AnyEventName> = RequestCaptureFn<E>;
12
+ export type Request2Options<E extends AnyEventName> = RequestOptions<E>;
13
+ export type Request2FpOptions<E extends AnyEventName> = RequestFpOptions<E>;
14
+ export type Request2CaptureFnEventsPayload<E extends EventName[]> = RequestCaptureFnEventsPayload<E>;
15
+ export type Request2Result<E extends AnyEventName> = E extends (infer U extends EventName)[] ? U extends infer K extends EventName ? {
16
+ event: K;
17
+ payload: If<IsNever<EventPayload<K>>, undefined, EventPayload<K>>;
18
+ } : never : E extends EventName ? If<IsNever<EventPayload<E>>, undefined, EventPayload<E>> : never;
19
+ export type Request2Fn = typeof request2;
20
+ export type Request2FpFn = typeof request2Fp;
21
+ /**
22
+ * Calls a method waiting for the specified event(-s) to occur.
23
+ * @param method - method name.
24
+ * @param eventOrEvents - tracked event or events.
25
+ * @param options - additional options.
26
+ */
27
+ export declare function request2Fp<M extends MethodNameWithRequiredParams, E extends AnyEventName, AbortError = never>(method: M, eventOrEvents: E, options: Request2FpOptions<E> & {
28
+ params: MethodParams<M>;
29
+ }): TE.TaskEither<Request2Error | AbortError, Request2Result<E>>;
30
+ /**
31
+ * Calls a method waiting for the specified event(-s) to occur.
32
+ * @param method - method name.
33
+ * @param eventOrEvents - tracked event or events.
34
+ * @param options - additional options.
35
+ */
36
+ export declare function request2Fp<M extends MethodNameWithOptionalParams, E extends AnyEventName, AbortError = never>(method: M, eventOrEvents: E, options?: Request2FpOptions<E> & {
37
+ params?: MethodParams<M>;
38
+ }): TE.TaskEither<Request2Error | AbortError, Request2Result<E>>;
39
+ /**
40
+ * Calls a method waiting for the specified event(-s) to occur.
41
+ * @param method - method name.
42
+ * @param eventOrEvents - tracked event or events.
43
+ * @param options - additional options.
44
+ */
45
+ export declare function request2Fp<M extends MethodNameWithoutParams, E extends AnyEventName, AbortError = never>(method: M, eventOrEvents: E, options?: Request2FpOptions<E>): TE.TaskEither<Request2Error | AbortError, Request2Result<E>>;
46
+ /**
47
+ * @see request2Fp
48
+ */
49
+ export declare function request2<M extends MethodNameWithRequiredParams, E extends AnyEventName>(method: M, eventOrEvents: E, options: Request2Options<E> & {
50
+ params: MethodParams<M>;
51
+ }): BetterPromise<Request2Result<E>>;
52
+ /**
53
+ * @see request2Fp
54
+ */
55
+ export declare function request2<M extends MethodNameWithOptionalParams, E extends AnyEventName>(method: M, eventOrEvents: E, options?: Request2Options<E> & {
56
+ params?: MethodParams<M>;
57
+ }): BetterPromise<Request2Result<E>>;
58
+ /**
59
+ * @see request2Fp
60
+ */
61
+ export declare function request2<M extends MethodNameWithoutParams, E extends AnyEventName>(method: M, eventOrEvents: E, options?: Request2Options<E>): BetterPromise<Request2Result<E>>;
62
+ export {};
package/dist/index.cjs ADDED
@@ -0,0 +1,4 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("valibot"),f=require("@vbotma/toolkit"),k=require("better-promises"),a=require("fp-ts"),y=require("error-kid"),d=require("@vbotma/transformers"),b=require("@vbotma/signals"),he=require("mitt");function B(e){return i.is(i.looseObject({VBotWebviewProxy:i.looseObject({postEvent:i.function()})}),e)}function L(){try{return window.self!==window.top}catch{return!0}}class N extends y.errorClass("MethodUnsupportedError",(t,r)=>[`Method "${t}" is unsupported in Mini Apps version ${r}`]){}class H extends y.errorClass("MethodParameterUnsupportedError",(t,r,n)=>[`Parameter "${r}" of "${t}" method is unsupported in Mini Apps version ${n}`]){}class Y extends y.errorClassWithData("LaunchParamsRetrieveError",t=>({errors:t}),t=>[["Unable to retrieve launch parameters from any known source. Perhaps, you have opened your app outside Telegram?","📖 Refer to docs for more information:","https://docs.vbot-mini-apps.com/packages/tma-js-bridge/environment","","Collected errors:",...t.map(({source:r,error:n})=>`Source: ${r} / ${n instanceof Error?n.message:String(n)}`)].join(`
2
+ `)]){}class X extends y.errorClass("InvalidLaunchParamsError",(t,r)=>[`Invalid value for launch params: ${t}`,{cause:r}]){}class T extends y.errorClass("UnknownEnvError"){}class Z extends y.errorClass("InvokeCustomMethodError",t=>[`Server returned error: ${t}`]){}const $="launchParams";function z(e){return e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&")}function ee(){return a.function.pipe(S(),a.either.chainW(d.parseLaunchParamsQueryFp))}const me=f.throwifyFpFn(ee);function te(){return a.function.pipe(S(),a.either.map(e=>{const t=new URLSearchParams(e).get("vbWebAppData");return t?a.option.some(t):a.option.none}))}function de(){return a.function.pipe(te(),a.either.fold(e=>{throw e},e=>e),a.option.match(()=>{},e=>e))}function S(){const e=[];for(const[t,r]of[[()=>z(window.location.href),"window.location.href"],[()=>{const n=performance.getEntriesByType("navigation")[0];return n&&z(n.name)},"performance navigation entries"],[()=>f.getStorageValue($),"local storage"]]){const n=t();if(!n){e.push({source:r,error:new Error("Source is empty")});continue}const s=a.function.pipe(d.parseLaunchParamsQueryFp(n),a.either.foldW(o=>o,()=>!0));if(typeof s!="boolean"){e.push({source:r,error:s});continue}return f.setStorageValue($,n),a.either.right(n)}return a.either.left(new Y(e))}const be=f.throwifyFpFn(S);function we(e,t){const r=new Map,n=he(),s=(o,c,u=!1)=>{const _=r.get(o)||new Map;r.set(o,_);const p=_.get(c)||[];_.set(c,p);const l=p.findIndex(h=>h[1]===u);if(l>=0&&(n.off(o,p[l][0]),p.splice(l,1),!p.length&&(_.delete(c),!_.size))){const h=r.size;r.delete(o),h&&!r.size&&t()}};return{on(o,c,u){!r.size&&e();const _=()=>{s(o,c,u)},p=(...m)=>{u&&_(),o==="*"?c({name:m[0],payload:m[1]}):c(...m)};n.on(o,p);const l=r.get(o)||new Map;r.set(o,l);const h=l.get(c)||[];return l.set(c,h),h.push([p,u||!1]),_},off:s,emit:n.emit,clear(){const o=r.size;n.all.clear(),r.clear(),o&&t()}}}function C(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}const F=b.signal(!1),V=b.signal("https://web.telegram.org"),ge=e=>{w().log("Event received:",e)},R=b.computed(F);function ye(e){e!==F()&&(F.set(e),(e?x:ne)("*",ge))}const W=b.computed(V);function ve(e){V.set(e),w().log("New target origin set",e)}const g=b.signal((...e)=>{window.parent.postMessage(...e)}),w=b.signal(f.createLogger("Bridge",{bgColor:"#9147ff",textColor:"white",shouldLog:R}));function Ee(){oe(),[g,V,W,F,R,w].forEach(e=>{e.unsubAll(),"reset"in e&&e.reset()})}function A(e,t,r){const n=[r],s=e[t];typeof s=="function"&&n.push(s);const o=(...u)=>{n.forEach(_=>_(...u))},c=Object.assign((...u)=>{o(...u)},{unwrap(){const{length:u}=n;if(u===1){delete e[t];return}if(u===2){G(e,t,n[1]);return}n.unshift(1),G(e,t,o)}});re(e,t,()=>c,u=>n.push(u))}function D(e,t){const r=e[t];re(e,t,()=>r,n=>{Object.entries(n).forEach(([s,o])=>{r[s]=o})})}function re(e,t,r,n){Object.defineProperty(e,t,{enumerable:!0,configurable:!0,get:r,set:n})}function G(e,t,r){Object.defineProperty(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r})}const Pe={clipboard_text_received:i.looseObject({req_id:i.string(),data:i.nullish(i.string())}),custom_method_invoked:i.looseObject({req_id:i.string(),result:i.optional(i.unknown()),error:i.optional(i.string())}),popup_closed:i.nullish(i.looseObject({button_id:i.nullish(i.string(),()=>{})}),{}),viewport_changed:i.nullish(i.looseObject({height:i.number(),width:i.nullish(i.number(),()=>window.innerWidth),is_state_stable:i.boolean(),is_expanded:i.boolean()}),()=>({height:window.innerHeight,is_state_stable:!0,is_expanded:!0})),theme_changed:i.looseObject({theme_params:d.themeParams()})};function J(e){if(e.source!==window.parent)return;let t;try{t=i.parse(d.pipeJsonToSchema(d.miniAppsMessage()),e.data)}catch{return}const{eventType:r,eventData:n}=t,s=Pe[r];let o;try{o=s?i.parse(s,n):n}catch(c){return w().forceError([`An error occurred processing the "${r}" event from the VBot application.`,"Please, file an issue here:","https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose"].join(`
3
+ `),t,c)}ke(r,o)}const{on:x,off:ne,emit:ke,clear:oe}=we(()=>{const e=window;!e.TelegramGameProxy&&(e.TelegramGameProxy={}),A(e.TelegramGameProxy,"receiveEvent",C),D(e,"TelegramGameProxy"),!e.Telegram&&(e.Telegram={}),!e.VBot.WebView&&(e.VBot.WebView={}),A(e.VBot.WebView,"receiveEvent",C),D(e.Telegram,"WebView"),A(e,"TelegramGameProxy_receiveEvent",C),window.addEventListener("message",J)},()=>{[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{const t=window;let r=[void 0,t];for(const o of e)if(r=[r[1],r[1][o]],!r[1])return;const[n,s]=r;"unwrap"in s&&(s.unwrap(),n&&n!==t&&!Object.keys(n).length&&delete t[e[0]])}),window.removeEventListener("message",J)}),ae=(...e)=>g()(...e);function se(e,t){a.function.pipe(v(e,t),a.either.mapLeft(r=>{throw r}))}function v(e,t){w().log("Posting event:",t?{eventType:e,eventData:t}:{eventType:e});const r=window,n=JSON.stringify({eventType:e,eventData:t});return L()?(ae(n,W()),a.either.right(void 0)):B(r)?(r.VBotWebviewProxy.postEvent(e,JSON.stringify(t)),a.either.right(void 0)):i.is(i.looseObject({external:i.looseObject({notify:i.function()})}),r)?(r.external.notify(n),a.either.right(void 0)):a.either.left(new T)}function M(e,t,r={}){const{capture:n=()=>!0,postEvent:s=v}=r,o=b.signal(),[c,u]=f.createCbCollector();(Array.isArray(t)?t:[t]).forEach(p=>{c(x(p,l=>{const h=Array.isArray(t);n(h?{event:p,payload:l}:l)&&o.set([h?{event:p,payload:l}:l])}))});const _=p=>(u(),p);return a.function.pipe(async()=>s(e,r.params),a.taskEither.chainW(()=>f.BetterTaskEither((p,l,h)=>{const m=o();if(m)return p(m[0]);const E=P=>{P&&p(P[0])},q=()=>{o.unsub(E)};o.sub(E),h.on("finalized",q)},r)),a.taskEither.mapBoth(_,_))}function Se(e,t,r){const{postEvent:n}=r||{};return f.throwifyAnyEither(M(e,t,{...r,postEvent:n?(...s)=>{try{return n(...s),a.either.right(void 0)}catch(o){return a.either.left(o)}}:v}))}function Ce(e,t){const r=ie(e,t);return typeof r=="function"?k.BetterPromise.fn(()=>f.throwifyAnyEither(r)):r}function ie(e,t){const r=B(window);if(!e)return r||a.function.pipe(S(),a.either.match(()=>!1,()=>!0));if(r)return a.taskEither.right(!0);const{timeout:n=100}=t||{};return a.function.pipe(M("web_app_request_theme","theme_changed",{...t,timeout:n}),a.taskEither.match(s=>k.TimeoutError.is(s)||T.is(s)?a.either.right(!1):a.either.left(s),()=>a.either.right(!0)))}function Fe({launchParams:e,onEvent:t,resetPostMessage:r}={}){if(e){const o=typeof e=="string"||e instanceof URLSearchParams?e.toString():d.serializeLaunchParamsQuery({...e,vbWebAppData:void 0})+(e.vbWebAppData?`&vbWebAppData=${encodeURIComponent(e.vbWebAppData.toString())}`:"");try{d.parseLaunchParamsQuery(o)}catch(c){throw new X(o,c)}f.setStorageValue("launchParams",o)}if(L()){if(!t)return;r&&g.reset();const o=g();g.set((...c)=>{const[u]=c,_=()=>{o(...c)};try{const p=i.parse(d.pipeJsonToSchema(d.miniAppsMessage()),u);t({name:p.eventType,params:p.eventData},_)}catch{_()}});return}const n=window.VBotWebviewProxy||{},s=n.postEvent||(()=>{});window.VBotWebviewProxy={...n,postEvent(o,c){const u=()=>{s(o,c)};t?t({name:o,params:c?JSON.parse(c):void 0},u):u()}},w().log("Environment was mocked by the mockVBotEnv function")}function ce(e){return({req_id:t})=>t===e}const Q={"6.0":["iframe_ready","iframe_will_reload","web_app_close","web_app_data_send","web_app_expand","web_app_open_link","web_app_ready","web_app_request_theme","web_app_request_viewport","web_app_setup_main_button","web_app_setup_closing_behavior"],6.1:["web_app_open_tg_link","web_app_open_invoice","web_app_setup_back_button","web_app_set_background_color","web_app_set_header_color","web_app_trigger_haptic_feedback"],6.2:["web_app_open_popup"],6.4:["web_app_close_scan_qr_popup","web_app_open_scan_qr_popup","web_app_read_text_from_clipboard",{method:"web_app_open_link",param:"try_instant_view"}],6.7:["web_app_switch_inline_query"],6.9:["web_app_invoke_custom_method","web_app_request_write_access","web_app_request_phone",{method:"web_app_set_header_color",param:"color"}],"6.10":["web_app_setup_settings_button"],7.2:["web_app_biometry_get_info","web_app_biometry_open_settings","web_app_biometry_request_access","web_app_biometry_request_auth","web_app_biometry_update_token"],7.6:[{method:"web_app_open_link",param:"try_browser"},{method:"web_app_close",param:"return_back"}],7.7:["web_app_setup_swipe_behavior"],7.8:["web_app_share_to_story"],"7.10":["web_app_setup_secondary_button","web_app_set_bottom_bar_color",{method:"web_app_setup_main_button",param:"has_shine_effect"}],"8.0":["web_app_request_safe_area","web_app_request_content_safe_area","web_app_request_fullscreen","web_app_exit_fullscreen","web_app_set_emoji_status","web_app_add_to_home_screen","web_app_check_home_screen","web_app_request_emoji_status_access","web_app_check_location","web_app_open_location_settings","web_app_request_file_download","web_app_request_location","web_app_send_prepared_message","web_app_start_accelerometer","web_app_start_device_orientation","web_app_start_gyroscope","web_app_stop_accelerometer","web_app_stop_device_orientation","web_app_stop_gyroscope","web_app_toggle_orientation_lock"],"9.0":["web_app_device_storage_clear","web_app_device_storage_get_key","web_app_device_storage_save_key","web_app_secure_storage_clear","web_app_secure_storage_get_key","web_app_secure_storage_restore_key","web_app_secure_storage_save_key"],9.1:["web_app_hide_keyboard"],9.2:["web_app_send_notification","web_app_finish_refresh"]};function O(e,t){return Object.keys(Q).find(n=>Q[n].some(s=>t?typeof s=="object"&&s.method===e&&s.param===t:s===e))||null}function K(e){return e.split(".").map(Number)}function pe(e,t){const r=K(e),n=K(t),s=Math.max(r.length,n.length);for(let o=0;o<s;o+=1){const c=r[o]||0,u=n[o]||0;if(c!==u)return c>u?1:-1}return 0}function j(e,t,r){const n=r?O(e,t):O(e);return n?pe(n,r||t)<=0:!1}function xe(e,t="strict"){const r=typeof t=="function"?t:n=>{const{method:s,version:o}=n,c="param"in n?new H(s,n.param,o):new N(s,o);if(t==="strict")throw c;return w().forceWarn(c.message)};return((n,s)=>j(n,e)?n==="web_app_set_header_color"&&i.is(i.looseObject({color:i.any()}),s)&&!j(n,"color",e)?r({version:e,method:n,param:"color"}):se(n,s):r({version:e,method:n}))}function ue(e,t,r,n){return a.function.pipe(M("web_app_invoke_custom_method","custom_method_invoked",{...n||{},params:{method:e,params:t,req_id:r},capture:ce(r)}),a.taskEither.chain(({result:s,error:o})=>o?a.taskEither.left(new Z(o)):a.taskEither.right(s)))}function Me(e,t,r,n){return k.BetterPromise.fn(()=>a.function.pipe(ue(e,t,r,n),a.taskEither.match(s=>{throw s},s=>s))())}function _e(e,t,r={}){const{capture:n=()=>!0,postEvent:s=v}=r,o=b.signal(),[c,u]=f.createCbCollector();(Array.isArray(t)?t:[t]).forEach(p=>{c(x(p,l=>{(Array.isArray(t)?n({event:p,payload:l}):n(l))&&o.set([l])}))});const _=p=>(u(),p);return a.function.pipe(async()=>s(e,r.params),a.taskEither.chainW(()=>f.BetterTaskEither((p,l,h)=>{const m=o();if(m)return p(m[0]);const E=P=>{P&&p(P[0])},q=()=>{o.unsub(E)};o.sub(E),h.on("finalized",q)},r)),a.taskEither.mapBoth(_,_))}function qe(e,t,r){const{postEvent:n}=r||{};return f.throwifyAnyEither(_e(e,t,{...r,postEvent:n?(...s)=>{try{return n(...s),a.either.right(void 0)}catch(o){return a.either.left(o)}}:v}))}function Ae(){Object.hasOwn||(Object.hasOwn=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)})}function U(e){return a.either.tryCatch(()=>decodeURIComponent(atob(e.replace(/-/g,"+").replace(/_/g,"/")).split("").map(t=>"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)).join("")),t=>t)}const Oe=f.throwifyFpFn(U);function I(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(t,r)=>String.fromCharCode(parseInt(`0x${r}`)))).replace(/\+/g,"-").replace(/\//g,"_")}function le(e){const t=I(typeof e=="string"?e:JSON.stringify(e));return t.length>512?a.either.left(new Error("Value is too long for start parameter")):a.either.right(t)}const je=f.throwifyFpFn(le);function Be(e,t){return f.throwifyAnyEither(fe(e,typeof t=="function"?r=>a.either.tryCatch(()=>t(r),n=>n):t))}function fe(e,t){return a.function.pipe(U(e),a.either.chain(r=>t?typeof t=="function"?t(r):a.json.parse(r):a.either.right(r)))}function Le(e){return I(e).length<=512}Object.defineProperty(exports,"createLogger",{enumerable:!0,get:()=>f.createLogger});Object.defineProperty(exports,"deepSnakeToCamelObjKeys",{enumerable:!0,get:()=>f.deepSnakeToCamelObjKeys});Object.defineProperty(exports,"CancelledError",{enumerable:!0,get:()=>k.CancelledError});Object.defineProperty(exports,"TimeoutError",{enumerable:!0,get:()=>k.TimeoutError});exports.InvalidLaunchParamsError=X;exports.InvokeCustomMethodFailedError=Z;exports.LaunchParamsRetrieveError=Y;exports.MethodParameterUnsupportedError=H;exports.MethodUnsupportedError=N;exports.UnknownEnvError=T;exports.applyPolyfills=Ae;exports.captureSameReq=ce;exports.compareVersions=pe;exports.createPostEvent=xe;exports.createStartParam=je;exports.createStartParamFp=le;exports.debug=R;exports.decodeBase64Url=Oe;exports.decodeBase64UrlFp=U;exports.decodeStartParam=Be;exports.decodeStartParamFp=fe;exports.emitEvent=C;exports.encodeBase64Url=I;exports.getReleaseVersion=O;exports.hasWebviewProxy=B;exports.invokeCustomMethod=Me;exports.invokeCustomMethodFp=ue;exports.isIframe=L;exports.isSafeToCreateStartParam=Le;exports.isVBMA=Ce;exports.isVBMAFp=ie;exports.logger=w;exports.mockVBotEnv=Fe;exports.off=ne;exports.offAll=oe;exports.on=x;exports.postEvent=se;exports.postEventFp=v;exports.postMessage=ae;exports.postMessageImpl=g;exports.request=qe;exports.request2=Se;exports.request2Fp=M;exports.requestFp=_e;exports.resetGlobals=Ee;exports.retrieveLaunchParams=me;exports.retrieveLaunchParamsFp=ee;exports.retrieveRawInitData=de;exports.retrieveRawInitDataFp=te;exports.retrieveRawLaunchParams=be;exports.retrieveRawLaunchParamsFp=S;exports.setDebug=ye;exports.setTargetOrigin=ve;exports.supports=j;exports.targetOrigin=W;
4
+ //# sourceMappingURL=index.cjs.map