@vbotma/bridge 2.2.4 → 2.2.6

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/env/hasWebviewProxy.ts","../src/env/isIframe.ts","../src/errors.ts","../src/launch-params.ts","../src/events/createEmitter.ts","../src/events/emitEvent.ts","../src/globals.ts","../src/obj-prop-helpers.ts","../src/events/emitter.ts","../src/methods/postMessage.ts","../src/methods/postEvent.ts","../src/utils/request2.ts","../src/env/isVBMA.ts","../src/env/mockVBotEnv.ts","../src/methods/captureSameReq.ts","../src/methods/getReleaseVersion.ts","../src/utils/compareVersions.ts","../src/methods/supports.ts","../src/methods/createPostEvent.ts","../src/utils/invokeCustomMethod.ts","../src/utils/request.ts","../src/applyPolyfills.ts","../src/base64-url.ts","../src/start-param.ts"],"sourcesContent":["import { looseObject, function as fn, is } from 'valibot';\n\n/**\n * Returns true in case, passed value contains path `VBotWebviewProxy.postEvent` property and\n * `postEvent` is a function.\n * @param value - value to check.\n */\nexport function hasWebviewProxy<T>(value: T): value is T & {\n VBotWebviewProxy: {\n postEvent: (...args: unknown[]) => unknown;\n };\n} {\n return is(\n looseObject({ VBotWebviewProxy: looseObject({ postEvent: fn() }) }),\n value,\n );\n}\n","/**\n * @see https://stackoverflow.com/a/326076\n * @returns True, if current environment is iframe.\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch {\n return true;\n }\n}\n","import type { Version } from '@vbotma/types';\nimport { errorClass, errorClassWithData } from 'error-kid';\n\nexport class MethodUnsupportedError extends /* @__PURE__ */ errorClass<\n [method: string, version: Version]\n>('MethodUnsupportedError', (method, version) => [\n `Method \"${method}\" is unsupported in Mini Apps version ${version}`,\n]) {\n}\n\nexport class MethodParameterUnsupportedError extends /* @__PURE__ */ errorClass<\n [method: string, param: string, version: Version]\n>('MethodParameterUnsupportedError', (method, param, version) => [\n `Parameter \"${param}\" of \"${method}\" method is unsupported in Mini Apps version ${version}`,\n]) {\n}\n\nexport class LaunchParamsRetrieveError extends /* @__PURE__ */ errorClassWithData<\n { errors: { source: string; error: unknown }[] },\n [{ source: string; error: unknown }[]]\n>(\n 'LaunchParamsRetrieveError',\n errors => ({ errors }),\n errors => [\n [\n 'Unable to retrieve launch parameters from any known source. Perhaps, you have opened your app outside Telegram?',\n '📖 Refer to docs for more information:',\n 'https://docs.vbot-mini-apps.com/packages/tma-js-bridge/environment',\n '',\n 'Collected errors:',\n ...errors.map(({ source, error }) => {\n return `Source: ${source} / ${error instanceof Error ? error.message : String(error)}`;\n }),\n ].join('\\n'),\n ],\n) {\n}\n\nexport class InvalidLaunchParamsError extends /* @__PURE__ */ errorClass<\n [launchParams: string, cause: unknown]\n>('InvalidLaunchParamsError', (launchParams, cause) => [\n `Invalid value for launch params: ${launchParams}`,\n { cause },\n]) {\n}\n\nexport class UnknownEnvError extends /* @__PURE__ */ errorClass('UnknownEnvError') {\n}\n\nexport class InvokeCustomMethodFailedError extends /* @__PURE__ */ errorClass<[error: string]>(\n 'InvokeCustomMethodError',\n error => [`Server returned error: ${error}`],\n) {\n}\n","import { throwifyFpFn, getStorageValue, setStorageValue } from '@vbotma/toolkit';\nimport {\n parseLaunchParamsQueryFp,\n type LaunchParamsGenType,\n type ParseLaunchParamsQueryError,\n} from '@vbotma/transformers';\nimport { either as E, function as fn, option as O } from 'fp-ts';\n\nimport { LaunchParamsRetrieveError } from '@/errors.js';\n\nconst SESSION_STORAGE_KEY = 'launchParams';\n\nexport type RetrieveRawInitDataError = RetrieveRawLaunchParamsError;\nexport type RetrieveRawLaunchParamsError = LaunchParamsRetrieveError;\nexport type RetrieveLaunchParamsError = RetrieveRawLaunchParamsError | ParseLaunchParamsQueryError;\nexport type RetrieveLaunchParamsResult = LaunchParamsGenType;\n\n/**\n * @param urlString - URL to extract launch parameters from.\n * @returns Launch parameters from the specified URL.\n * @throws Error if function was unable to extract launch parameters from the\n * passed URL.\n */\nfunction retrieveLpFromUrl(urlString: string): string {\n return urlString\n // Replace everything before this first hashtag or question sign.\n .replace(/^[^?#]*[?#]/, '')\n // Replace all hashtags and question signs to make it look like some search\n // params.\n .replace(/[?#]/g, '&');\n}\n\n/**\n * @returns Launch parameters from any known source.\n */\nexport function retrieveLaunchParamsFp(): E.Either<\n RetrieveLaunchParamsError,\n RetrieveLaunchParamsResult\n> {\n return fn.pipe(\n retrieveRawLaunchParamsFp(),\n E.chainW(parseLaunchParamsQueryFp),\n );\n}\n\n/**\n * @see retrieveLaunchParamsFp\n */\nexport const retrieveLaunchParams: () => RetrieveLaunchParamsResult =\n throwifyFpFn(retrieveLaunchParamsFp);\n\n/**\n * @returns Raw init data from any known source.\n */\nexport function retrieveRawInitDataFp(): E.Either<RetrieveRawInitDataError, O.Option<string>> {\n return fn.pipe(\n retrieveRawLaunchParamsFp(),\n E.map(raw => {\n const v = new URLSearchParams(raw).get('vbWebAppData');\n return v ? O.some(v) : O.none;\n }),\n );\n}\n\n/**\n * @see retrieveRawInitDataFp\n */\nexport function retrieveRawInitData(): string | undefined {\n return fn.pipe(\n retrieveRawInitDataFp(),\n E.fold(err => {\n throw err;\n }, v => v),\n O.match(() => undefined, v => v),\n );\n}\n\n/**\n * @returns Launch parameters in a raw format from any known source.\n */\nexport function retrieveRawLaunchParamsFp(): E.Either<RetrieveRawLaunchParamsError, string> {\n const errors: { source: string; error: unknown }[] = [];\n\n for (const [retrieve, source] of [\n // Try to retrieve launch parameters from the current location. This method\n // can return nothing in case, location was changed, and then the page was\n // reloaded.\n [() => retrieveLpFromUrl(window.location.href), 'window.location.href'],\n // Then, try using the lower level API - window.performance.\n [() => {\n const navigationEntry = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined;\n return navigationEntry && retrieveLpFromUrl(navigationEntry.name);\n }, 'performance navigation entries'],\n // Finally, try using the session storage.\n [() => getStorageValue<string>(SESSION_STORAGE_KEY), 'local storage'],\n ] as const) {\n const v = retrieve();\n if (!v) {\n errors.push({ source, error: new Error('Source is empty') });\n continue;\n }\n const maybeError = fn.pipe(\n parseLaunchParamsQueryFp(v),\n E.foldW(err => err, () => true as const),\n );\n if (typeof maybeError !== 'boolean') {\n errors.push({ source, error: maybeError });\n continue;\n }\n setStorageValue(SESSION_STORAGE_KEY, v);\n return E.right(v);\n }\n return E.left(new LaunchParamsRetrieveError(errors));\n}\n\n/**\n * @see retrieveRawLaunchParamsFp\n */\nexport const retrieveRawLaunchParams = throwifyFpFn(retrieveRawLaunchParamsFp);\n","import type { If, IsNever, IsUndefined, Or } from '@vbotma/toolkit';\nimport mitt, {\n type Emitter,\n type EventHandlerMap,\n type EventType,\n type Handler,\n} from 'mitt';\n\nexport type WildcardHandler<E> = Handler<{\n [K in keyof E]: {\n name: K;\n payload: If<Or<IsNever<E[K]>, IsUndefined<E[K]>>, never, E[K]>;\n };\n}[keyof E]>;\n\nexport interface OnFn<E> {\n /**\n * Adds a new listener for the specified event.\n * @param type - event name.\n * @param handler - event listener.\n * @param once - should this listener be called only once.\n * @returns Function to remove bound event listener.\n */\n <K extends keyof E>(type: K, handler: Handler<E[K]>, once?: boolean): VoidFunction;\n /**\n * Adds a listener to the wildcard event.\n * @param type - event name.\n * @param handler - event listener.\n * @param once - should this listener be called only once.\n * @returns Function to remove bound event listener.\n */\n (type: '*', handler: WildcardHandler<E>, once?: boolean): VoidFunction;\n}\n\nexport interface OffFn<E> {\n /**\n * Removes a listener from the specified event.\n * @param type - event to listen.\n * @param handler - event listener to remove.\n * @param once - had this listener to be called only once.\n */\n <K extends keyof E>(type: K, handler: Handler<E[K]>, once?: boolean): void;\n /**\n * Removes a listener from the wildcard event.\n * @param type - event to stop listening.\n * @param handler - event listener to remove.\n * @param once - should this listener be called only once.\n */\n (type: '*', handler: WildcardHandler<E>, once?: boolean): void;\n}\n\nexport interface EmitFn<E> {\n <K extends keyof E>(type: K, event: E[K]): void;\n <K extends keyof E>(type: undefined extends E[K] ? K : never): void;\n}\n\n/**\n * Creates a new enhanced event emitter.\n * @param onFirst - a function to call every time when the events map appeared to be empty during\n * the event listener creation.\n * @param onEmpty - a function to call every tume when the events map became empty.\n */\nexport function createEmitter<E extends object>(\n onFirst: VoidFunction,\n onEmpty: VoidFunction,\n): {\n on: OnFn<E>;\n off: OffFn<E>;\n emit: EmitFn<E>;\n clear: VoidFunction;\n} {\n // To understand the event handlers concept here, let's tell the underlying idea.\n //\n // We use a Map, where key is an event name, and the value is a Map we call HandlersMap.\n //\n // The HandlersMap is a Map, where the key is an event handler, added by the developer.\n // The corresponding value is a list of tuples, with an internally generated function and a\n // boolean value responsible for determining if the handler must be called only once. So, you\n // can imagine the following map as:\n //\n // HandlersMap {\n // { developer_handler }: Array<[ internally_created_handler, once ]>;\n // }\n //\n // The value for the key represents an array of tuples, as long as a single handler may be added\n // many times, and for each addition we add a new tuple entry.\n //\n // The handler may also be added to be called only once. Trying to remove such kind of handler\n // using a different value of the \"once\" argument will lead to nothing. The developer must\n // specify the same argument value to avoid confusions.\n //\n // Here is the final EventToHandlersMap definition:\n //\n // EventToHandlersMap {\n // { event_name }: HandlersMap {\n // { developer_handler }: Array<[ internally_created_handler, once ]>;\n // }\n // }\n type HandlersMap = Map<\n (...args: any) => void,\n [handler: (...args: any) => void, once: boolean][]\n >;\n\n const eventToHandlersMap = new Map<keyof E | '*', HandlersMap>();\n\n const emitter = (mitt as any as {\n <E extends Record<EventType, unknown>>(all?: EventHandlerMap<E>): Emitter<E>;\n })<E & Record<string | symbol, unknown>>();\n\n const off: OffFn<E> = (\n event: keyof E | '*',\n handler: (...args: any) => void,\n once = false,\n ) => {\n const handlersMap: HandlersMap = eventToHandlersMap.get(event) || new Map();\n eventToHandlersMap.set(event, handlersMap);\n\n const handlers = handlersMap.get(handler) || [];\n handlersMap.set(handler, handlers);\n\n const index = handlers.findIndex(item => item[1] === once);\n if (index >= 0) {\n // Remove the related handler.\n emitter.off(event, handlers[index][0]);\n\n // Remove the handler from the cache array.\n handlers.splice(index, 1);\n\n // If after removal, there are no handlers left, we should remove the entry from the cache.\n if (!handlers.length) {\n handlersMap.delete(handler);\n if (!handlersMap.size) {\n const prevSize = eventToHandlersMap.size;\n eventToHandlersMap.delete(event);\n prevSize && !eventToHandlersMap.size && onEmpty();\n }\n }\n }\n };\n\n return {\n on(event: keyof E | '*', handler: (...args: any[]) => any, once?: boolean) {\n // The events' map became non-empty. Call the onFirst callback.\n !eventToHandlersMap.size && onFirst();\n\n const cleanup = () => {\n off(event as any, handler, once);\n };\n\n const internalHandler = (...args: any[]) => {\n once && cleanup();\n if (event === '*') {\n handler({ name: args[0], payload: args[1] });\n } else {\n handler(...args);\n }\n };\n\n emitter.on(event, internalHandler);\n\n // Add this handler to the cache, so we could remove it using the passed listener.\n const handlersMap: HandlersMap = eventToHandlersMap.get(event) || new Map();\n eventToHandlersMap.set(event, handlersMap);\n\n const handlers = handlersMap.get(handler) || [];\n handlersMap.set(handler, handlers);\n handlers.push([internalHandler, once || false]);\n\n return cleanup;\n },\n off,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n emit: emitter.emit,\n clear() {\n const prevSize = eventToHandlersMap.size;\n emitter.all.clear();\n eventToHandlersMap.clear();\n prevSize && onEmpty();\n },\n };\n}\n","import type { EventPayload, EventWithoutPayload, EventWithPayload } from '@/events/types/index.js';\n\n/**\n * Emits an event without payload sent from the Telegram native application like it was sent in\n * a default web environment between two iframes.\n *\n * It dispatches a new MessageEvent and expects it to be handled via\n * the `window.addEventListener('message', ...)` call, as a developer would do it to handle\n * messages sent from the parent iframe.\n * @param eventType - event name.\n */\nexport function emitEvent<E extends EventWithoutPayload>(eventType: E): void;\n\n/**\n * Emits an event with payload sent from the Telegram native application like it was sent in\n * a default web environment between two iframes.\n *\n * It dispatches a new MessageEvent and expects it to be handled via\n * the `window.addEventListener('message', ...)` call, as a developer would do it to handle\n * messages sent from the parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nexport function emitEvent<E extends EventWithPayload>(\n eventType: E,\n eventData: EventPayload<E>,\n): void;\n\n/**\n * Emits an unknown event sent from the Telegram native application like it was sent in a default\n * web environment between two iframes.\n *\n * It dispatches a new MessageEvent and expects it to be handled via\n * the `window.addEventListener('message', ...)` call, as a developer would do it to handle\n * messages sent from the parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nexport function emitEvent<E extends string>(\n eventType: E,\n eventData: E extends EventWithoutPayload\n ? never\n : E extends EventWithPayload\n ? EventPayload<E>\n : unknown,\n): void;\n\n/**\n * Emits an event sent from the Telegram native application like it was sent in a default web\n * environment between two iframes.\n *\n * It dispatches a new MessageEvent and expects it to be handled via\n * the `window.addEventListener('message', ...)` call, as a developer would do it to handle\n * messages sent from the parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nexport function emitEvent(eventType: string, eventData?: unknown): void {\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType, eventData }),\n // We specify this kind of source here in order to allow the package's \"on\" function to\n // capture it. The reason is this function always checks the event source and relies on\n // it to be the parent window.\n source: window.parent,\n }));\n}\n","import { signal, computed } from '@vbotma/signals';\nimport { createLogger, type Logger } from '@vbotma/toolkit';\n\nimport { off, offAll, on } from '@/events/emitter.js';\nimport type { SubscribeListener } from '@/events/types/index.js';\nimport type { PostMessage } from '@/methods/postMessage.js';\n\n/**\n * @internal\n */\nconst _debug = signal(false);\n/**\n * @internal\n */\nconst _targetOrigin = signal('https://web.telegram.org');\n\nconst onEventReceived: SubscribeListener = event => {\n logger().log('Event received:', event);\n};\n\n/**\n * The current debug mode state.\n *\n * To update the value, use the `setDebug` function.\n * @see setDebug\n */\nexport const debug = computed(_debug);\n\n/**\n * Sets the package debug mode.\n *\n * Enabling debug mode leads to printing additional messages in the console related to the\n * processes inside the package.\n * @param value - enable debug mode.\n */\nexport function setDebug(value: boolean): void {\n if (value !== _debug()) {\n _debug.set(value);\n (value ? on : off)('*', onEventReceived);\n }\n}\n\n/**\n * The current target origin used by the `postEvent` method.\n *\n * You don't need to override this value until you know what you are doing.\n * To update the value, use the `setTargetOrigin` function.\n * @default 'https://web.telegram.org'\n * @see setTargetOrigin\n */\nexport const targetOrigin = computed(_targetOrigin);\n\n/**\n * Sets a new target origin that is being used when calling the `postEvent` function in Telegram\n * web versions.\n *\n * You don't need to override this value until you know what you are doing.\n * @param origin - allowed target origin value.\n * @see _targetOrigin\n */\nexport function setTargetOrigin(origin: string) {\n _targetOrigin.set(origin);\n logger().log('New target origin set', origin);\n}\n\n/**\n * Signal containing a custom implementation of the method to post a message to the parent\n * window. We usually use it to send a message in web versions of Telegram.\n *\n * @default A function behaving like the `window.parent.postMessage` method.\n */\nexport const postMessageImpl = signal<PostMessage>((...args) => {\n window.parent.postMessage(...args as unknown as Parameters<PostMessage>);\n});\n\n/**\n * The package logger. You can override this value in order to use your own implementation.\n */\nexport const logger = signal<Logger>(createLogger('Bridge', {\n bgColor: '#9147ff',\n textColor: 'white',\n shouldLog: debug,\n}));\n\n/**\n * Resets the package global values. Normally, you don't use this function in your application.\n * We are using it only for test purposes.\n */\nexport function resetGlobals() {\n offAll();\n [postMessageImpl, _targetOrigin, targetOrigin, _debug, debug, logger].forEach(s => {\n s.unsubAll();\n 'reset' in s && s.reset();\n });\n}\n","/**\n * Defines a property, that is a functions compose. Trying to set a value in this property\n * will lead to adding it to a function's pool. The property value will always be equal to a\n * function, calling all collected functions in the pool.\n *\n * Returned function performs a cleanup. It does one of the following:\n * 1. Removes the property if no functions were to the pool added other than the initial one.\n * 2. Sets the value equal to the first added function to the pool after the initial one if\n * the only one additional function was added at all. In other words, if the pool length is equal\n * to 2, the second item will be selected as the property value.\n * 3. Leaves the value equal to a function calling all pool functions, but removes the initially\n * added one.\n * @param obj - object.\n * @param propertyName - object property.\n * @param initialFn - an initial function to set.\n */\nexport function defineFnComposer(\n obj: any,\n propertyName: string,\n initialFn: (...args: any) => any,\n): void {\n const assignedFunctions: any[] = [initialFn];\n\n const property = obj[propertyName];\n if (typeof property === 'function') {\n assignedFunctions.push(property);\n }\n\n const callAssignedFunctions = (...args: any) => {\n assignedFunctions.forEach(fn => fn(...args));\n };\n\n // Wrap the callPool function and add \"unwrap\" method to it.\n const unwrappableCallAssignedFunctions = Object.assign((...args: any) => {\n callAssignedFunctions(...args);\n }, {\n // Unwraps the composer.\n unwrap() {\n const { length: poolSize } = assignedFunctions;\n if (poolSize === 1) {\n // Only the initial handler is in the pool. In this case we just remove the property.\n delete obj[propertyName];\n return;\n }\n if (poolSize === 2) {\n // Only one additional handler was added. We set it as a value for the property.\n defineStaticProperty(obj, propertyName, assignedFunctions[1]);\n return;\n }\n // Many additional handlers were added. In this case we remove the initially added function\n // from the pool and leave the property value almost as is - only \"unwrap\" method will be\n // removed.\n assignedFunctions.unshift(1);\n defineStaticProperty(obj, propertyName, callAssignedFunctions);\n },\n });\n\n // This property should now always return our special function. Trying to set it to another\n // function should lead to just adding it to the pool of called functions.\n defineProxiedProperty(\n obj,\n propertyName,\n () => unwrappableCallAssignedFunctions,\n value => assignedFunctions.push(value),\n );\n}\n\n/**\n * Wires the specified property in the object preventing it from being overwritten. Instead, it\n * enhances the previous value by merging the current one with the passed one.\n * @param obj - object.\n * @param prop - object property to rewire.\n */\nexport function defineMergeableProperty(obj: any, prop: string): void {\n const value = obj[prop];\n defineProxiedProperty(obj, prop, () => value, v => {\n Object.entries(v).forEach(([objKey, objValue]) => {\n value[objKey] = objValue;\n });\n });\n}\n\n/**\n * Defines an enumerable and configurable property with a getter and setter.\n * @param obj - object.\n * @param prop - object property name.\n * @param get - getter to use.\n * @param set - setter to use.\n */\nexport function defineProxiedProperty(\n obj: any,\n prop: string,\n get: () => unknown,\n set: (v: any) => void,\n) {\n Object.defineProperty(obj, prop, {\n enumerable: true,\n configurable: true,\n get,\n set,\n });\n}\n\n/**\n * Defines an enumerable, configurable and writable property with the initial value.\n * @param obj - object.\n * @param prop - object property name.\n * @param value - value to set.\n */\nexport function defineStaticProperty(obj: any, prop: string, value: any): void {\n Object.defineProperty(obj, prop, {\n enumerable: true,\n configurable: true,\n writable: true,\n value,\n });\n}\n","import { miniAppsMessage, pipeJsonToSchema, themeParams } from '@vbotma/transformers';\nimport {\n boolean,\n looseObject,\n nullish,\n number,\n optional,\n parse,\n string,\n unknown,\n type BaseSchema,\n} from 'valibot';\n\nimport { createEmitter } from '@/events/createEmitter.js';\nimport { emitEvent } from '@/events/emitEvent.js';\nimport type { EventName, EventPayload, Events } from '@/events/types/index.js';\nimport { logger } from '@/globals.js';\nimport { defineFnComposer, defineMergeableProperty } from '@/obj-prop-helpers.js';\n\n/**\n * Transformers for problematic Mini Apps events.\n */\nconst transformers = {\n clipboard_text_received: looseObject({\n req_id: string(),\n data: nullish(string()),\n }),\n custom_method_invoked: looseObject({\n req_id: string(),\n result: optional(unknown()),\n error: optional(string()),\n }),\n popup_closed: nullish(\n looseObject({ button_id: nullish(string(), () => undefined) }),\n {},\n ),\n viewport_changed: nullish(\n looseObject({\n height: number(),\n width: nullish(number(), () => window.innerWidth),\n is_state_stable: boolean(),\n is_expanded: boolean(),\n }),\n // TODO: At the moment, macOS has a bug with the invalid event payload - it is always equal to\n // null. Leaving this default value until the bug is fixed.\n () => ({\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n }),\n ),\n theme_changed: looseObject({\n theme_params: themeParams(),\n }),\n} as const satisfies { [E in EventName]?: BaseSchema<unknown, EventPayload<E>, any> };\n\nfunction windowMessageListener(event: MessageEvent): void {\n // Ignore non-parent window messages.\n if (event.source !== window.parent) {\n return;\n }\n\n // Parse incoming event data.\n let message: { eventType: string; eventData?: unknown };\n try {\n message = parse(pipeJsonToSchema(miniAppsMessage()), event.data);\n } catch {\n // We ignore incorrect messages as they could be generated by any other code.\n return;\n }\n\n const { eventType, eventData } = message;\n const schema = transformers[eventType as keyof typeof transformers];\n\n let data: unknown;\n try {\n data = schema ? parse(schema, eventData) : eventData;\n } catch (cause) {\n return logger().forceError(\n [\n `An error occurred processing the \"${eventType}\" event from the VBot application.`,\n 'Please, file an issue here:',\n 'https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose',\n ].join('\\n'),\n message,\n cause,\n );\n }\n emit(eventType as any, data);\n}\n\nexport const {\n on,\n off,\n emit,\n clear: offAll,\n} = createEmitter<Events>(\n () => {\n const wnd = window as any;\n\n // Define all functions responsible for receiving an event from the VBot client.\n // All these \"ports\" should narrow the communication way to a single specific one - the way\n // accepted by the web version of Telegram between iframes.\n //\n // Here we consider 2 cases:\n // 1. When the Telegram SDK is already connected. In this case the Telegram SDK already\n // installed its own ports, and we should rewire them. The cleanup function should also work\n // properly in this context, removing @vbotma/bridge handler only, not\n // the Telegram SDK one.\n // 2. When the Telegram SDK is not connected, but probably will be. We know, that\n // the Telegram SDK is going to overwrite our own handlers. Due to this reason, we should\n // protect them from being overwritten, but still support handlers defined by the Telegram SDK.\n\n // TelegramGameProxy.receiveEvent\n !wnd.TelegramGameProxy && (wnd.TelegramGameProxy = {});\n defineFnComposer(wnd.TelegramGameProxy, 'receiveEvent', emitEvent);\n defineMergeableProperty(wnd, 'TelegramGameProxy');\n\n // VBot.WebView.receiveEvent\n !wnd.Telegram && (wnd.Telegram = {});\n !wnd.VBot.WebView && (wnd.VBot.WebView = {});\n defineFnComposer(wnd.VBot.WebView, 'receiveEvent', emitEvent);\n defineMergeableProperty(wnd.Telegram, 'WebView');\n\n // TelegramGameProxy_receiveEvent\n defineFnComposer(wnd, 'TelegramGameProxy_receiveEvent', emitEvent);\n\n // Add a listener handling events sent from the Telegram web application and also events\n // generated by the local emitEvent function.\n // This handler should emit a new event using the library event emitter.\n window.addEventListener('message', windowMessageListener);\n },\n () => {\n [\n ['TelegramGameProxy_receiveEvent'],\n ['TelegramGameProxy', 'receiveEvent'],\n ['Telegram', 'WebView', 'receiveEvent'],\n ].forEach(path => {\n const wnd = window as any;\n\n // A tuple, where the first value is the receiveEvent function owner, and the second\n // value is the receiveEvent itself.\n let cursor: [obj: any, receieveEvent: any] = [undefined, wnd];\n for (const item of path) {\n cursor = [cursor[1], cursor[1][item]];\n if (!cursor[1]) {\n return;\n }\n }\n const [receiveEventOwner, receiveEvent] = cursor;\n if ('unwrap' in receiveEvent) {\n receiveEvent.unwrap();\n if (\n receiveEventOwner\n && receiveEventOwner !== wnd\n && !Object.keys(receiveEventOwner).length\n ) {\n delete wnd[path[0]];\n }\n }\n });\n window.removeEventListener('message', windowMessageListener);\n },\n);\n","import { postMessageImpl } from '@/globals.js';\n\nexport type PostMessage = typeof window.parent.postMessage;\n\n/**\n * Posts a message to the parent window. We usually use it to send a message in web versions of\n * Telegram.\n * @param args - `window.parent.postMessage` arguments.\n */\nexport const postMessage: PostMessage = (...args) => {\n return postMessageImpl()(...args as unknown as Parameters<PostMessage>);\n};\n","import { either as E, function as fpFn } from 'fp-ts';\nimport { function as fn, is, looseObject } from 'valibot';\n\nimport { hasWebviewProxy } from '@/env/hasWebviewProxy.js';\nimport { isIframe } from '@/env/isIframe.js';\nimport { UnknownEnvError } from '@/errors.js';\nimport { logger, targetOrigin } from '@/globals.js';\nimport type {\n MethodName,\n MethodNameWithOptionalParams,\n MethodNameWithoutParams,\n MethodNameWithRequiredParams,\n MethodParams,\n} from '@/methods/types/index.js';\n\nimport { postMessage } from './postMessage.js';\n\nexport type PostEventError = UnknownEnvError;\nexport type PostEventFn = typeof postEvent;\nexport type PostEventFpFn = typeof postEventFp;\n\n/**\n * @see postEventFp\n */\nexport function postEvent<Method extends MethodNameWithRequiredParams>(\n method: Method,\n params: MethodParams<Method>,\n): void;\n/**\n * @see postEventFp\n */\nexport function postEvent(method: MethodNameWithoutParams): void;\n/**\n * @see postEventFp\n */\nexport function postEvent<Method extends MethodNameWithOptionalParams>(\n method: Method,\n params?: MethodParams<Method>,\n): void;\n\nexport function postEvent(\n eventType: MethodName,\n eventData?: MethodParams<MethodName>,\n): void {\n fpFn.pipe(\n postEventFp(\n // @ts-expect-error It's ok, TS can't determine a specific override.\n eventType,\n eventData,\n ),\n E.mapLeft(err => {\n throw err;\n }),\n );\n}\n\n/**\n * Calls Mini Apps methods requiring parameters.\n * @param method - method name.\n * @param params - options along with params.\n */\nexport function postEventFp<Method extends MethodNameWithRequiredParams>(\n method: Method,\n params: MethodParams<Method>,\n): E.Either<PostEventError, void>;\n\n/**\n * Calls Mini Apps methods accepting no parameters at all.\n * @param method - method name.\n */\nexport function postEventFp(method: MethodNameWithoutParams): E.Either<PostEventError, void>;\n\n/**\n * Calls Mini Apps methods accepting optional parameters.\n * @param method - method name.\n * @param params - options along with params.\n */\nexport function postEventFp<Method extends MethodNameWithOptionalParams>(\n method: Method,\n params?: MethodParams<Method>,\n): E.Either<PostEventError, void>;\n\nexport function postEventFp(\n eventType: MethodName,\n eventData?: MethodParams<MethodName>,\n): E.Either<PostEventError, void> {\n logger().log('Posting event:', eventData ? { eventType, eventData } : { eventType });\n\n const w = window;\n const message = JSON.stringify({ eventType, eventData });\n\n // Telegram Web.\n if (isIframe()) {\n postMessage(message, targetOrigin());\n return E.right(undefined);\n }\n\n // Telegram for iOS, macOS, Android and Telegram Desktop.\n if (hasWebviewProxy(w)) {\n w.VBotWebviewProxy.postEvent(eventType, JSON.stringify(eventData));\n return E.right(undefined);\n }\n\n // Telegram for Windows Phone or Android.\n if (is(looseObject({ external: looseObject({ notify: fn() }) }), w)) {\n w.external.notify(message);\n return E.right(undefined);\n }\n\n // Otherwise, the current environment is unknown, and we are not able to send event.\n return E.left(new UnknownEnvError());\n}\n","import { signal } from '@vbotma/signals';\nimport {\n BetterTaskEither,\n type If,\n type IsNever,\n createCbCollector,\n throwifyAnyEither,\n} from '@vbotma/toolkit';\nimport { BetterPromise } from 'better-promises';\nimport { either as E, taskEither as TE, function as fn } from 'fp-ts';\n\nimport { on } from '@/events/emitter.js';\nimport type { EventName, EventPayload } from '@/events/types/index.js';\nimport { postEventFp } from '@/methods/postEvent.js';\nimport type {\n MethodName,\n MethodNameWithOptionalParams,\n MethodNameWithRequiredParams,\n MethodNameWithoutParams,\n MethodParams,\n} from '@/methods/types/index.js';\n\nimport type {\n RequestCaptureEventFn,\n RequestCaptureEventsFn,\n RequestCaptureFn,\n RequestError,\n RequestFpOptions,\n RequestOptions,\n RequestCaptureFnEventsPayload,\n} from './request.js';\n\ntype AnyEventName = EventName | EventName[];\n\nexport type Request2Error = RequestError;\nexport type Request2CaptureEventsFn<E extends EventName[]> = RequestCaptureEventsFn<E>;\nexport type Request2CaptureEventFn<E extends EventName> = RequestCaptureEventFn<E>;\nexport type Request2CaptureFn<E extends AnyEventName> = RequestCaptureFn<E>;\nexport type Request2Options<E extends AnyEventName> = RequestOptions<E>;\nexport type Request2FpOptions<E extends AnyEventName> = RequestFpOptions<E>;\nexport type Request2CaptureFnEventsPayload<E extends EventName[]> =\n RequestCaptureFnEventsPayload<E>;\nexport type Request2Result<E extends AnyEventName> =\n E extends (infer U extends EventName)[]\n ? U extends infer K extends EventName\n ? { event: K; payload: If<IsNever<EventPayload<K>>, undefined, EventPayload<K>> }\n : never\n : E extends EventName\n ? If<IsNever<EventPayload<E>>, undefined, EventPayload<E>>\n : never;\n\nexport type Request2Fn = typeof request2;\nexport type Request2FpFn = typeof request2Fp;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n */\nexport function request2Fp<\n M extends MethodNameWithRequiredParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options: Request2FpOptions<E> & { params: MethodParams<M> },\n): TE.TaskEither<Request2Error | AbortError, Request2Result<E>>;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n */\nexport function request2Fp<\n M extends MethodNameWithOptionalParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options?: Request2FpOptions<E> & { params?: MethodParams<M> },\n): TE.TaskEither<Request2Error | AbortError, Request2Result<E>>;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n */\nexport function request2Fp<\n M extends MethodNameWithoutParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options?: Request2FpOptions<E>,\n): TE.TaskEither<Request2Error | AbortError, Request2Result<E>>;\n\nexport function request2Fp<\n M extends MethodName,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options: Request2FpOptions<E> & { params?: MethodParams<M> } = {},\n): TE.TaskEither<Request2Error | AbortError, Request2Result<E>> {\n const {\n // If no capture function was passed, we capture the first compatible event.\n capture = () => true,\n postEvent = postEventFp,\n } = options;\n\n // TODO: Maybe we want to rewrite it using a simple BetterPromise.\n\n const result = signal<undefined | [Request2Result<E>]>();\n const [addCleanup, cleanup] = createCbCollector();\n // Iterate over all the tracked events and add a listener, checking if the event should be\n // captured.\n (Array.isArray(eventOrEvents) ? eventOrEvents : [eventOrEvents]).forEach(event => {\n // Each event listener waits for the event to occur.\n // Then, if the capture function was passed, we should check if the event should\n // be captured. If the function is omitted, we instantly capture the event.\n addCleanup(\n on(event, payload => {\n const isEventsArray = Array.isArray(eventOrEvents);\n if (\n isEventsArray\n ? (capture as Request2CaptureEventsFn<EventName[]>)({ event, payload })\n : (capture as Request2CaptureEventFn<EventName>)(payload)\n ) {\n result.set([\n (isEventsArray ? { event, payload } : payload) as Request2Result<E>,\n ]);\n }\n }),\n );\n });\n const withCleanup = <T>(value: T): T => {\n cleanup();\n return value;\n };\n\n return fn.pipe(\n async () => postEvent(method as any, (options as any).params),\n TE.chainW(() => {\n return BetterTaskEither<AbortError, Request2Result<E>>((resolve, _, context) => {\n // When creating this BetterTaskEither, we could already have a value stored in\n // the result signal. For example, when tracked events were generated via emitEvent in\n // mockVBotEnv.onEvent.\n const data = result();\n if (data) {\n return resolve(data[0]);\n }\n\n const listener = (data: [Request2Result<E>] | undefined) => {\n if (data) {\n resolve(data[0]);\n }\n };\n const unsub = () => {\n result.unsub(listener);\n };\n result.sub(listener);\n context.on('finalized', unsub);\n }, options);\n }),\n TE.mapBoth(withCleanup, withCleanup),\n );\n}\n\n/**\n * @see request2Fp\n */\nexport function request2<M extends MethodNameWithRequiredParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options: Request2Options<E> & { params: MethodParams<M> },\n): BetterPromise<Request2Result<E>>;\n\n/**\n * @see request2Fp\n */\nexport function request2<M extends MethodNameWithOptionalParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: Request2Options<E> & { params?: MethodParams<M> },\n): BetterPromise<Request2Result<E>>;\n\n/**\n * @see request2Fp\n */\nexport function request2<M extends MethodNameWithoutParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: Request2Options<E>,\n): BetterPromise<Request2Result<E>>;\n\nexport function request2<M extends MethodName, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: Request2Options<E> & { params?: MethodParams<M> },\n): BetterPromise<Request2Result<E>> {\n const { postEvent } = options || {};\n\n return throwifyAnyEither(\n // @ts-expect-error TypeScript will not be able to handle our overrides here.\n request2Fp(method, eventOrEvents, {\n ...options,\n postEvent: postEvent\n ? (...args: any[]) => {\n try {\n // @ts-expect-error TypeScript will not be able to handle our overrides here.\n postEvent(...args);\n return E.right(undefined);\n } catch (e) {\n return E.left(e);\n }\n }\n : postEventFp,\n }),\n );\n}\n","import { throwifyAnyEither } from '@vbotma/toolkit';\nimport {\n BetterPromise,\n type BetterPromiseOptions,\n TimeoutError,\n} from 'better-promises';\nimport { either as E, taskEither as TE, function as fn } from 'fp-ts';\n\nimport { hasWebviewProxy } from '@/env/hasWebviewProxy.js';\nimport { UnknownEnvError } from '@/errors.js';\nimport { retrieveRawLaunchParamsFp } from '@/launch-params.js';\nimport { type Request2Error, request2Fp } from '@/utils/request2.js';\n\nexport type isVBMAError = Exclude<Request2Error, TimeoutError>;\n\n/**\n * @see isVBMAFp\n */\nexport function isVBMA(): boolean;\n/**\n * @see isVBMAFp\n */\nexport function isVBMA(type: 'complete', options?: BetterPromiseOptions): BetterPromise<boolean>;\nexport function isVBMA(\n type?: 'complete',\n options?: BetterPromiseOptions,\n): boolean | BetterPromise<boolean> {\n const monad = isVBMAFp(\n // @ts-expect-error TS doesn't get what override we are going to use.\n type,\n options,\n );\n return typeof monad === 'function'\n ? BetterPromise.fn(() => throwifyAnyEither(monad as TE.TaskEither<any, boolean>))\n : monad;\n}\n\n/**\n * Returns true if the current environment is VBot Mini Apps.\n *\n * It uses the `retrieveLaunchParams` function to determine if the environment\n * contains launch parameters. In case it does, true will be returned.\n *\n * In case you need stricter checks, use async override of this function.\n */\nexport function isVBMAFp(): boolean;\n/**\n * Returns promise with true if the current environment is VBot Mini Apps.\n *\n * First of all, it checks if the current environment contains traits specific\n * to the Mini Apps environment. Then, it attempts to call a Mini Apps method\n * and waits for a response to be received.\n *\n * In case you need less strict checks, use sync override of this function.\n */\nexport function isVBMAFp(\n type: 'complete',\n options?: BetterPromiseOptions,\n): TE.TaskEither<isVBMAError, boolean>;\nexport function isVBMAFp(\n type?: 'complete',\n options?: BetterPromiseOptions,\n): boolean | TE.TaskEither<isVBMAError, boolean> {\n const hasProxy = hasWebviewProxy(window);\n if (!type) {\n return hasProxy || fn.pipe(retrieveRawLaunchParamsFp(), E.match(() => false, () => true));\n }\n if (hasProxy) {\n return TE.right(true);\n }\n const { timeout = 100 } = options || {};\n\n return fn.pipe(\n request2Fp('web_app_request_theme', 'theme_changed', { ...options, timeout }),\n TE.match(\n error => (\n TimeoutError.is(error) || UnknownEnvError.is(error)\n ? E.right(false)\n : E.left(error)\n ),\n () => E.right(true),\n ),\n );\n}\n","import { setStorageValue } from '@vbotma/toolkit';\nimport {\n miniAppsMessage,\n parseLaunchParamsQuery,\n pipeJsonToSchema,\n serializeLaunchParamsQuery,\n type LaunchParamsLike,\n} from '@vbotma/transformers';\nimport { parse } from 'valibot';\n\nimport { isIframe } from '@/env/isIframe.js';\nimport { InvalidLaunchParamsError } from '@/errors.js';\nimport { logger, postMessageImpl } from '@/globals.js';\nimport type { MethodName, MethodParams } from '@/methods/types/index.js';\n\n/**\n * Mocks the environment and imitates VBot Mini Apps behavior.\n *\n * We usually use this function in the following cases:\n * 1. We are developing an application outside the VBot environment and would like to imitate\n * the VBot client in order to re-create the same communication behavior.\n * 2. We would like to intercept some VBot Mini Apps methods' calls in order to enhance them\n * or write a custom behavior. It is extremely useful in some VBot clients improperly handling\n * Mini Apps methods' calls and not even responding.\n *\n * Note that calling this function in Telegram web clients, the `postMessageImplementation` signal\n * value will be updated with a new one, enhancing previously set signal value to allow wrapping\n * the original `window.parent.postMessage` function. In other words, calling `mockVBotEnv`\n * function N times, you will effectively wrap previously set implementation N times, so be\n * careful calling this function several times during a single lifecycle of the app. In case you\n * would like to avoid such kind of behavior, use the `resetPostMessage` option.\n */\nexport function mockVBotEnv({ launchParams, onEvent, resetPostMessage }: {\n /**\n * Launch parameters to mock. They will be saved in the storage, so the SDK functions could\n * retrieve them.\n *\n * Note that this value must have `vbWebAppData` presented in a raw format as long as you will\n * need it when retrieving init data in this format. Otherwise, init data may be broken.\n */\n launchParams?:\n | (Omit<LaunchParamsLike, 'vbWebAppData'> & { vbWebAppData?: string | URLSearchParams })\n | string\n | URLSearchParams;\n /**\n * Function that will be called if a Mini Apps method call was requested by the mini app.\n *\n * It receives a Mini Apps method name along with the passed payload.\n *\n * Note that using the `next` function, in non-web environments it uses the\n * `window.VBotWebviewProxy.postEvent` method.\n *\n * Talking about the web versions of Telegram, the value of `next` is a bit more complex - it\n * will be equal to the value stored in the `postMessageImpl` signal set previously. By default,\n * this value contains a function utilizing the `window.parent.postMessage` method.\n * @param event - event information.\n * @param next - function to call the original method used to call a Mini Apps method.\n */\n onEvent?: (\n event:\n | { [M in MethodName]: { name: M; params: MethodParams<M> } }[MethodName]\n | { name: string; params: unknown },\n next: () => void,\n ) => void;\n /**\n * Removes all previously set enhancements of the `window.parent.postMessage` function set\n * by other `mockVBotEnv` calls.\n * @default false\n */\n resetPostMessage?: boolean;\n} = {}): void {\n if (launchParams) {\n // If launch parameters were passed, save them in the session storage, so\n // the retrieveLaunchParams function would return them.\n const launchParamsQuery =\n typeof launchParams === 'string' || launchParams instanceof URLSearchParams\n ? launchParams.toString()\n : (\n // Here we have to trick serializeLaunchParamsQuery into thinking, it serializes a valid\n // value. We are doing it because we are working with vbWebAppData presented as a\n // string, not an object as serializeLaunchParamsQuery requires.\n serializeLaunchParamsQuery({ ...launchParams, vbWebAppData: undefined })\n // Then, we just append init data.\n + (launchParams.vbWebAppData ? `&vbWebAppData=${encodeURIComponent(launchParams.vbWebAppData.toString())}` : '')\n );\n\n // Remember to check if launch params are valid.\n try {\n parseLaunchParamsQuery(launchParamsQuery);\n } catch (e) {\n throw new InvalidLaunchParamsError(launchParamsQuery, e);\n }\n setStorageValue('launchParams', launchParamsQuery);\n }\n\n // Original postEvent firstly checks if the current environment is iframe.\n // That's why we have a separate branch for this environment here too.\n if (isIframe()) {\n if (!onEvent) {\n return;\n }\n // As long as the postEvent function uses the postMessage method, we should rewire it.\n if (resetPostMessage) {\n postMessageImpl.reset();\n }\n\n const original = postMessageImpl();\n postMessageImpl.set((...args) => {\n const [message] = args;\n const next = () => {\n (original as any)(...args);\n };\n\n // Pass only VBot Mini Apps events to the handler. All other calls should be passed\n // to the original handler (window.parent.postMessage likely).\n try {\n const data = parse(pipeJsonToSchema(miniAppsMessage()), message);\n onEvent({ name: data.eventType, params: data.eventData }, next);\n } catch {\n next();\n }\n });\n return;\n }\n\n // In all other environments, it is enough to define window.VBotWebviewProxy.postEvent.\n const proxy = (window as any).VBotWebviewProxy || {};\n const postEventDefaulted = proxy.postEvent || (() => undefined);\n (window as any).VBotWebviewProxy = {\n ...proxy,\n postEvent(eventType: string, eventData: string) {\n const next = () => {\n postEventDefaulted(eventType, eventData);\n };\n onEvent\n ? onEvent({\n name: eventType,\n params: eventData ? JSON.parse(eventData) : undefined,\n }, next)\n : next();\n },\n };\n\n logger().log('Environment was mocked by the mockVBotEnv function');\n}\n","type CaptureSameReqFn = (payload: { req_id: string }) => boolean;\n\n/**\n * Returns a function which can be used in `request` function `capture` property to capture\n * the event with the same request identifier.\n * @param reqId - request identifier.\n */\nexport function captureSameReq(reqId: string): CaptureSameReqFn {\n return ({ req_id }) => req_id === reqId;\n}\n","import { Version } from '@vbotma/types';\n\nimport {\n MethodName,\n MethodNameWithVersionedParams,\n MethodVersionedParams,\n} from '@/methods/types/index.js';\n\nconst releases = {\n '6.0': [\n 'iframe_ready',\n 'iframe_will_reload',\n 'web_app_close',\n 'web_app_data_send',\n 'web_app_expand',\n 'web_app_open_link',\n 'web_app_ready',\n 'web_app_request_theme',\n 'web_app_request_viewport',\n 'web_app_setup_main_button',\n 'web_app_setup_closing_behavior',\n ],\n 6.1: [\n 'web_app_open_tg_link',\n 'web_app_open_invoice',\n 'web_app_setup_back_button',\n 'web_app_set_background_color',\n 'web_app_set_header_color',\n 'web_app_trigger_haptic_feedback',\n ],\n 6.2: ['web_app_open_popup'],\n 6.4: [\n 'web_app_close_scan_qr_popup',\n 'web_app_open_scan_qr_popup',\n 'web_app_read_text_from_clipboard',\n { method: 'web_app_open_link', param: 'try_instant_view' },\n ],\n 6.7: ['web_app_switch_inline_query'],\n 6.9: [\n 'web_app_invoke_custom_method',\n 'web_app_request_write_access',\n 'web_app_request_phone',\n { method: 'web_app_set_header_color', param: 'color' },\n ],\n '6.10': ['web_app_setup_settings_button'],\n 7.2: [\n 'web_app_biometry_get_info',\n 'web_app_biometry_open_settings',\n 'web_app_biometry_request_access',\n 'web_app_biometry_request_auth',\n 'web_app_biometry_update_token',\n ],\n 7.6: [\n { method: 'web_app_open_link', param: 'try_browser' },\n { method: 'web_app_close', param: 'return_back' },\n ],\n 7.7: ['web_app_setup_swipe_behavior'],\n 7.8: ['web_app_share_to_story'],\n '7.10': [\n 'web_app_setup_secondary_button',\n 'web_app_set_bottom_bar_color',\n { method: 'web_app_setup_main_button', param: 'has_shine_effect' },\n ],\n '8.0': [\n 'web_app_request_safe_area',\n 'web_app_request_content_safe_area',\n 'web_app_request_fullscreen',\n 'web_app_exit_fullscreen',\n 'web_app_set_emoji_status',\n 'web_app_add_to_home_screen',\n 'web_app_check_home_screen',\n 'web_app_request_emoji_status_access',\n 'web_app_check_location',\n 'web_app_open_location_settings',\n 'web_app_request_file_download',\n 'web_app_request_location',\n 'web_app_send_prepared_message',\n 'web_app_start_accelerometer',\n 'web_app_start_device_orientation',\n 'web_app_start_gyroscope',\n 'web_app_stop_accelerometer',\n 'web_app_stop_device_orientation',\n 'web_app_stop_gyroscope',\n 'web_app_toggle_orientation_lock',\n ],\n '9.0': [\n 'web_app_device_storage_clear',\n 'web_app_device_storage_get_key',\n 'web_app_device_storage_save_key',\n 'web_app_secure_storage_clear',\n 'web_app_secure_storage_get_key',\n 'web_app_secure_storage_restore_key',\n 'web_app_secure_storage_save_key',\n ],\n 9.1: ['web_app_hide_keyboard'],\n 9.2: [\n 'web_app_send_notification',\n 'web_app_finish_refresh',\n ],\n};\n\n/**\n * @returns Version of the specified method parameter release. Returns `null`\n * if passed method or parameter are unknown.\n * @param method - method name\n * @param param - method parameter\n */\nexport function getReleaseVersion<M extends MethodNameWithVersionedParams>(\n method: M,\n param: MethodVersionedParams<M>,\n): Version | null;\n\n/**\n * @returns Version of the specified method release. Returns `null`\n * if passed method is unknown.\n * @param method - method name.\n */\nexport function getReleaseVersion(method: MethodName): Version | null;\nexport function getReleaseVersion(method: MethodName, param?: string): Version | null {\n const versions = Object.keys(releases) as (`${keyof typeof releases}`)[];\n return versions.find(version => {\n return releases[version].some(item => {\n if (param) {\n return typeof item === 'object'\n && item.method === method\n && item.param === param;\n }\n return item === method;\n });\n }) || null;\n}\n","import type { Version } from '@vbotma/types';\n\nfunction parts(a: Version): number[] {\n return a.split('.').map(Number);\n}\n\n/**\n * @param a - first version.\n * @param b - second version.\n * @returns\n * - `1` if the version \"a\" is greater than \"b\".\n * - `0` the version \"a\" is equal to \"b\".\n * - `-1` the version \"a\" is lower than \"b\".\n */\nexport function compareVersions(a: Version, b: Version): number {\n const aParts = parts(a);\n const bParts = parts(b);\n const len = Math.max(aParts.length, bParts.length);\n\n // Iterate over each part of versions and compare them. In case, part is\n // missing, assume its value is equal to 0.\n for (let i = 0; i < len; i += 1) {\n const aVal = aParts[i] || 0;\n const bVal = bParts[i] || 0;\n\n if (aVal === bVal) {\n continue;\n }\n return aVal > bVal ? 1 : -1;\n }\n return 0;\n}\n","import type { Version } from '@vbotma/types';\n\nimport { getReleaseVersion } from '@/methods/getReleaseVersion.js';\nimport type {\n MethodName,\n MethodNameWithVersionedParams,\n MethodVersionedParams,\n} from '@/methods/types/index.js';\nimport { compareVersions } from '@/utils/compareVersions.js';\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 MethodNameWithVersionedParams>(\n method: M,\n param: MethodVersionedParams<M>,\n inVersion: Version,\n): boolean;\n\n/**\n * Returns true in case, specified method is supported in a 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 const version = inVersion\n ? getReleaseVersion(\n method as MethodNameWithVersionedParams,\n paramOrVersion as MethodVersionedParams<MethodNameWithVersionedParams>,\n )\n : getReleaseVersion(method);\n return version\n ? compareVersions(version, inVersion || paramOrVersion) <= 0\n : false;\n}\n","import type { Version } from '@vbotma/types';\nimport { any, is, looseObject } from 'valibot';\n\nimport { MethodParameterUnsupportedError, MethodUnsupportedError } from '@/errors.js';\nimport { logger } from '@/globals.js';\nimport { type PostEventFn, postEvent } from '@/methods/postEvent.js';\nimport { supports } from '@/methods/supports.js';\nimport type {\n MethodName,\n MethodNameWithVersionedParams,\n MethodVersionedParams,\n} from '@/methods/types/index.js';\n\nexport type OnUnsupportedFn = (\n data: { version: Version } & (\n | { method: MethodName }\n | {\n [M in MethodNameWithVersionedParams]: {\n method: M;\n param: MethodVersionedParams<M>;\n };\n }[MethodNameWithVersionedParams]),\n) => void;\n\nexport type CreatePostEventMode = 'strict' | 'non-strict';\n\n/**\n * Creates a function that checks if the specified method and parameters are supported.\n *\n * If the method or parameters are unsupported, the `onUnsupported` function will be called.\n *\n * If `strict` or `non-strict` value was passed as the second argument, the function\n * will create its own `onUnsupported` function with behavior depending on the value passed.\n *\n * - Passing `strict` will make the function to throw a `MethodParameterUnsupportedError`\n * or a `MethodUnsupportedError` error.\n * - Passing `non-strict` will just warn you about something being unsupported.\n *\n * @param version - VBot Mini Apps version.\n * @param onUnsupportedOrMode - function or strict mode. Default: `strict`\n */\nexport function createPostEvent(\n version: Version,\n onUnsupportedOrMode: OnUnsupportedFn | CreatePostEventMode = 'strict',\n): PostEventFn {\n const onUnsupported: OnUnsupportedFn = typeof onUnsupportedOrMode === 'function'\n ? onUnsupportedOrMode\n : data => {\n const { method, version } = data;\n const error = 'param' in data\n ? new MethodParameterUnsupportedError(method, data.param, version)\n : new MethodUnsupportedError(method, version);\n\n if (onUnsupportedOrMode === 'strict') {\n throw error;\n }\n return logger().forceWarn(error.message);\n };\n\n return ((method: any, params: any) => {\n // Firstly, check if the method is supported.\n if (!supports(method, version)) {\n return onUnsupported({ version, method });\n }\n\n // Method could use parameters, which are supported only in specific versions of Mini Apps.\n // We are validating only those parameters, which are not backward compatible.\n if (\n method === 'web_app_set_header_color'\n && is(looseObject({ color: any() }), params)\n && !supports(method, 'color', version)\n ) {\n return onUnsupported({ version, method, param: 'color' });\n }\n\n return postEvent(method, params);\n }) as PostEventFn;\n}\n","import { BetterPromise } from 'better-promises';\nimport { taskEither as TE, function as fn } from 'fp-ts';\n\nimport { InvokeCustomMethodFailedError } from '@/errors.js';\nimport { captureSameReq } from '@/methods/captureSameReq.js';\nimport type { CustomMethodName, CustomMethodParams } from '@/methods/types/index.js';\n\nimport {\n request2Fp,\n type Request2Error,\n type Request2FpOptions,\n type Request2Options,\n} from './request2.js';\n\nexport type InvokeCustomMethodError = Request2Error | InvokeCustomMethodFailedError;\n\nexport type InvokeCustomMethodOptions = Omit<Request2Options<'custom_method_invoked'>, 'capture'>;\nexport type InvokeCustomMethodFn = typeof invokeCustomMethod;\n\nexport type InvokeCustomMethodFpOptions = Omit<Request2FpOptions<'custom_method_invoked'>, 'capture'>;\nexport type InvokeCustomMethodFpFn = typeof invokeCustomMethodFp;\n\n/**\n * Invokes known custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param requestId - request identifier.\n * @param options - additional options.\n */\nexport function invokeCustomMethodFp<M extends CustomMethodName>(\n method: M,\n params: CustomMethodParams<M>,\n requestId: string,\n options?: InvokeCustomMethodFpOptions,\n): TE.TaskEither<InvokeCustomMethodError, unknown>;\n\n/**\n * Invokes unknown custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param requestId - request identifier.\n * @param options - additional options.\n */\nexport function invokeCustomMethodFp(\n method: string,\n params: object,\n requestId: string,\n options?: InvokeCustomMethodFpOptions,\n): TE.TaskEither<Request2Error, unknown>;\n\nexport function invokeCustomMethodFp(\n method: string,\n params: object,\n requestId: string,\n options?: InvokeCustomMethodFpOptions,\n): TE.TaskEither<InvokeCustomMethodError, unknown> {\n return fn.pipe(\n request2Fp('web_app_invoke_custom_method', 'custom_method_invoked', {\n ...options || {},\n params: { method, params, req_id: requestId },\n capture: captureSameReq(requestId),\n }),\n TE.chain(({ result, error }) => {\n return error\n ? TE.left(new InvokeCustomMethodFailedError(error))\n : TE.right(result);\n }),\n );\n}\n\n/**\n * @see invokeCustomMethodFp\n */\nexport function invokeCustomMethod<M extends CustomMethodName>(\n method: M,\n params: CustomMethodParams<M>,\n requestId: string,\n options?: InvokeCustomMethodOptions,\n): BetterPromise<unknown>;\n\n/**\n * @see invokeCustomMethodFp\n */\nexport function invokeCustomMethod(\n method: string,\n params: object,\n requestId: string,\n options?: InvokeCustomMethodOptions,\n): BetterPromise<unknown>;\n\nexport function invokeCustomMethod(\n method: string,\n params: object,\n requestId: string,\n options?: InvokeCustomMethodOptions,\n): BetterPromise<unknown> {\n return BetterPromise.fn(() => {\n return fn.pipe(\n // @ts-expect-error TypeScript is unable to determine required override.\n invokeCustomMethodFp(method, params, requestId, options),\n TE.match(\n error => {\n throw error;\n },\n result => result,\n ),\n )();\n });\n}\n","import { signal } from '@vbotma/signals';\nimport {\n createCbCollector,\n throwifyAnyEither,\n type If,\n type IsNever,\n BetterTaskEither,\n} from '@vbotma/toolkit';\nimport {\n BetterPromise,\n type BetterPromiseOptions,\n type TimeoutError,\n} from 'better-promises';\nimport { either as E, taskEither as TE, function as fn } from 'fp-ts';\n\nimport { on } from '@/events/emitter.js';\nimport type { EventName, EventPayload } from '@/events/types/index.js';\nimport {\n postEventFp,\n type PostEventError,\n type PostEventFn,\n type PostEventFpFn,\n} from '@/methods/postEvent.js';\nimport type {\n MethodName,\n MethodNameWithOptionalParams,\n MethodNameWithoutParams,\n MethodNameWithRequiredParams,\n MethodParams,\n} from '@/methods/types/index.js';\n\ntype AnyEventName = EventName | EventName[];\n\nexport type RequestError = PostEventError | TimeoutError;\n\n/**\n * @example\n * { event: 'scan_qr_closed' }\n * @example\n * {\n * event: 'popup_closed',\n * payload: { button_id: 'ok' }\n * }\n */\nexport type RequestCaptureFnEventsPayload<E extends EventName[]> =\n E extends (infer U extends EventName)[]\n ? {\n [K in U]: If<\n IsNever<EventPayload<K>>,\n { event: K },\n { event: K; payload: EventPayload<K> }\n >\n }[U]\n : never;\n\nexport type RequestCaptureEventsFn<E extends EventName[]> = (\n payload: RequestCaptureFnEventsPayload<E>,\n) => boolean;\n\nexport type RequestCaptureEventFn<E extends EventName> = If<\n IsNever<EventPayload<E>>,\n () => boolean,\n (payload: EventPayload<E>) => boolean\n>;\n\nexport type RequestCaptureFn<E extends AnyEventName> = E extends EventName[]\n ? RequestCaptureEventsFn<E>\n : E extends EventName\n ? RequestCaptureEventFn<E>\n : never;\n\nexport interface RequestOptions<E extends AnyEventName> extends Omit<RequestFpOptions<E>, 'postEvent'> {\n /**\n * Custom function to call mini apps methods.\n */\n postEvent?: PostEventFn;\n}\n\nexport type RequestResult<E extends AnyEventName> =\n E extends (infer U extends EventName)[]\n ? U extends infer K extends EventName\n ? If<IsNever<EventPayload<K>>, undefined, EventPayload<K>>\n : never\n : E extends EventName\n ? If<IsNever<EventPayload<E>>, undefined, EventPayload<E>>\n : never;\n\nexport interface RequestFpOptions<E extends AnyEventName> extends Pick<\n BetterPromiseOptions,\n 'abortSignal' | 'timeout'\n> {\n /**\n * A function that should return true if the event should be captured.\n * The first compatible request will be captured if this property is omitted.\n */\n capture?: RequestCaptureFn<E>;\n /**\n * A custom function to call mini apps methods.\n */\n postEvent?: PostEventFpFn;\n}\n\nexport type RequestFn = typeof request;\nexport type RequestFpFn = typeof requestFp;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n * @deprecated To be removed in the next major update. Use `request2fp` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function requestFp<\n M extends MethodNameWithRequiredParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options: RequestFpOptions<E> & { params: MethodParams<M> },\n): TE.TaskEither<RequestError | AbortError, RequestResult<E>>;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n * @deprecated To be removed in the next major update. Use `request2fp` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function requestFp<\n M extends MethodNameWithOptionalParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options?: RequestFpOptions<E> & { params?: MethodParams<M> },\n): TE.TaskEither<RequestError | AbortError, RequestResult<E>>;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n * @deprecated To be removed in the next major update. Use `request2fp` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function requestFp<\n M extends MethodNameWithoutParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options?: RequestFpOptions<E>,\n): TE.TaskEither<RequestError | AbortError, RequestResult<E>>;\n\nexport function requestFp<\n M extends MethodName,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options: RequestFpOptions<E> & { params?: MethodParams<M> } = {},\n): TE.TaskEither<RequestError | AbortError, RequestResult<E>> {\n const {\n // If no capture function was passed, we capture the first compatible event.\n capture = () => true,\n postEvent = postEventFp,\n } = options;\n\n const result = signal<undefined | [RequestResult<E>]>();\n const [addCleanup, cleanup] = createCbCollector();\n // Iterate over all the tracked events and add a listener, checking if the event should be\n // captured.\n (Array.isArray(eventOrEvents) ? eventOrEvents : [eventOrEvents]).forEach(event => {\n // Each event listener waits for the event to occur.\n // Then, if the capture function was passed, we should check if the event should\n // be captured. If the function is omitted, we instantly capture the event.\n addCleanup(\n on(event, payload => {\n if (\n Array.isArray(eventOrEvents)\n ? (capture as RequestCaptureEventsFn<EventName[]>)({ event, payload })\n : (capture as RequestCaptureEventFn<EventName>)(payload)\n ) {\n result.set([payload as RequestResult<E>]);\n }\n }),\n );\n });\n const withCleanup = <T>(value: T): T => {\n cleanup();\n return value;\n };\n\n return fn.pipe(\n async () => postEvent(method as any, (options as any).params),\n TE.chainW(() => {\n return BetterTaskEither<AbortError, RequestResult<E>>((resolve, _, context) => {\n // When creating this BetterTaskEither, we could already have a value stored in\n // the result signal. For example, when tracked events were generated via emitEvent in\n // mockVBotEnv.onEvent.\n const data = result();\n if (data) {\n return resolve(data[0]);\n }\n\n const listener = (data: [RequestResult<E>] | undefined) => {\n if (data) {\n resolve(data[0]);\n }\n };\n const unsub = () => {\n result.unsub(listener);\n };\n result.sub(listener);\n context.on('finalized', unsub);\n }, options);\n }),\n TE.mapBoth(withCleanup, withCleanup),\n );\n}\n\n/**\n * @see requestFp\n * @deprecated To be removed in the next major update. Use `request2` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function request<M extends MethodNameWithRequiredParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options: RequestOptions<E> & { params: MethodParams<M> },\n): BetterPromise<RequestResult<E>>;\n\n/**\n * @see requestFp\n * @deprecated To be removed in the next major update. Use `request2` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function request<M extends MethodNameWithOptionalParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: RequestOptions<E> & { params?: MethodParams<M> },\n): BetterPromise<RequestResult<E>>;\n\n/**\n * @see requestFp\n * @deprecated To be removed in the next major update. Use `request2` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function request<M extends MethodNameWithoutParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: RequestOptions<E>,\n): BetterPromise<RequestResult<E>>;\n\nexport function request<M extends MethodName, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: RequestOptions<E> & { params?: MethodParams<M> },\n): BetterPromise<RequestResult<E>> {\n const { postEvent } = options || {};\n\n return throwifyAnyEither(\n // @ts-expect-error TypeScript will not be able to handle our overrides here.\n requestFp(method, eventOrEvents, {\n ...options,\n postEvent: postEvent\n ? (...args: any[]) => {\n try {\n // @ts-expect-error TypeScript will not be able to handle our overrides here.\n postEvent(...args);\n return E.right(undefined);\n } catch (e) {\n return E.left(e);\n }\n }\n : postEventFp,\n }),\n );\n}\n","/**\n * Applies polyfills required for stable work of the package:\n * - `Object.hasOwn` - used by `valibot`\n */\nexport function applyPolyfills(): void {\n if (!Object.hasOwn) {\n Object.hasOwn = function(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n };\n }\n}\n","import { throwifyFpFn } from '@vbotma/toolkit';\nimport { either as E } from 'fp-ts';\n\nexport type DecodeBase64UrlError = DOMException;\n\n/**\n * Decodes a base-64-url ASCII string.\n * @param value - the value to decode.\n * @see Learn more about base64url:\n * https://herongyang.com/Encoding/Base64URL-Encoding-Algorithm.html\n * @see Source:\n * https://developer.mozilla.org/ru/docs/Glossary/Base64#solution_1_–_escaping_the_string_before_encoding_it\n */\nexport function decodeBase64UrlFp(value: string): E.Either<DecodeBase64UrlError, string> {\n return E.tryCatch(() => {\n return decodeURIComponent(\n atob(\n value\n .replace(/-/g, '+')\n .replace(/_/g, '/'),\n )\n .split('')\n .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))\n .join(''),\n );\n }, e => e as DOMException);\n}\n\n/**\n * @see decodeBase64UrlFp\n */\nexport const decodeBase64Url = throwifyFpFn(decodeBase64UrlFp);\n\n/**\n * Creates a base-64-url encoded ASCII string from the passed value.\n * @param value - the value to encode.\n * @see Learn more about base64url:\n * https://herongyang.com/Encoding/Base64URL-Encoding-Algorithm.html\n * @see Source:\n * https://developer.mozilla.org/ru/docs/Glossary/Base64#solution_1_–_escaping_the_string_before_encoding_it\n */\nexport function encodeBase64Url(value: string): string {\n // first we use encodeURIComponent to get percent-encoded UTF-8,\n // then we convert the percent encodings into raw bytes which\n // can be fed into btoa.\n return btoa(\n encodeURIComponent(value).replace(/%([0-9A-F]{2})/g, (_, p1) => {\n return String.fromCharCode(parseInt(`0x${p1}`));\n }),\n )\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n}\n","import { throwifyFpFn, throwifyAnyEither } from '@vbotma/toolkit';\nimport { either as E, function as fn, json as J } from 'fp-ts';\n\nimport { encodeBase64Url, type DecodeBase64UrlError, decodeBase64UrlFp } from '@/base64-url.js';\n\n/**\n * Creates a safe start parameter value. If the value is not a string, the\n * function applies JSON.stringify to it, so make sure you are not passing an\n * object with circular references.\n *\n * @param value - value to create start parameter from.\n * @see Learn more about start parameter:\n * https://docs.vbot-mini-apps.com/platform/start-parameter\n */\nexport function createStartParamFp(value: unknown): E.Either<Error, string> {\n const b64 = encodeBase64Url(typeof value === 'string' ? value : JSON.stringify(value));\n return b64.length > 512\n ? E.left(new Error('Value is too long for start parameter'))\n : E.right(b64);\n}\n\n/**\n * @see createStartParamFp\n */\nexport const createStartParam = throwifyFpFn(createStartParamFp);\n\n/**\n * @see decodeStartParamFp\n */\nexport function decodeStartParam<T>(value: string, parse: (value: string) => T): T;\n/**\n * @see decodeStartParamFp\n */\nexport function decodeStartParam(value: string, as: 'json'): J.Json;\n/**\n * @see decodeStartParamFp\n */\nexport function decodeStartParam(value: string): string;\nexport function decodeStartParam<T>(\n value: string,\n arg2?: 'json' | ((value: string) => T),\n): string | unknown | T {\n return throwifyAnyEither(\n decodeStartParamFp(\n value,\n // @ts-expect-error TypeScript is unable to detect a correct override.\n typeof arg2 === 'function'\n ? (value: string) => E.tryCatch(() => arg2(value), e => e)\n : arg2,\n ),\n );\n}\n\n/**\n * Decodes a start parameter using a custom parser.\n * @param value - a start parameter value.\n * @param parse - a custom value parser.\n */\nexport function decodeStartParamFp<L, R>(\n value: string,\n parse: (value: string) => E.Either<L, R>,\n): E.Either<L | DecodeBase64UrlError, R>;\n/**\n * Decodes a start parameter assuming that the result is a JSON value.\n * @param value - a start parameter value.\n * @param as - result kind.\n */\nexport function decodeStartParamFp(\n value: string,\n as: 'json',\n): E.Either<SyntaxError | DecodeBase64UrlError, J.Json>;\n/**\n * Decodes a start parameter and returns its decoded representation.\n * @param value - a value to decode.\n */\nexport function decodeStartParamFp(value: string): E.Either<DecodeBase64UrlError, string>;\nexport function decodeStartParamFp<L, R>(\n value: string,\n arg2?: 'json' | ((value: string) => E.Either<L, R>),\n): E.Either<DecodeBase64UrlError | SyntaxError | L, R | string | J.Json> {\n return fn.pipe(\n decodeBase64UrlFp(value),\n E.chain<DecodeBase64UrlError | SyntaxError | L, string, R | string | J.Json>(decoded => {\n if (!arg2) {\n return E.right(decoded);\n }\n if (typeof arg2 === 'function') {\n return arg2(decoded);\n }\n return J.parse(decoded) as E.Either<SyntaxError, J.Json>;\n }),\n );\n}\n\n/**\n * @returns True if the passed value is safe to be used to create a start parameter value from it.\n * If true is returned, the value can be safely passed to the `createStartParam` function.\n * @param value - value to check.\n * @see createStartParam\n */\nexport function isSafeToCreateStartParam(value: string): boolean {\n return encodeBase64Url(value).length <= 512;\n}\n"],"names":["hasWebviewProxy","value","is","looseObject","fn","isIframe","MethodUnsupportedError","errorClass","method","version","MethodParameterUnsupportedError","param","LaunchParamsRetrieveError","errorClassWithData","errors","source","error","InvalidLaunchParamsError","launchParams","cause","UnknownEnvError","InvokeCustomMethodFailedError","SESSION_STORAGE_KEY","retrieveLpFromUrl","urlString","retrieveLaunchParamsFp","retrieveRawLaunchParamsFp","E","parseLaunchParamsQueryFp","retrieveLaunchParams","throwifyFpFn","retrieveRawInitDataFp","raw","v","O","retrieveRawInitData","err","retrieve","navigationEntry","getStorageValue","maybeError","setStorageValue","retrieveRawLaunchParams","createEmitter","onFirst","onEmpty","eventToHandlersMap","emitter","mitt","off","event","handler","once","handlersMap","handlers","index","item","prevSize","cleanup","internalHandler","args","emitEvent","eventType","eventData","_debug","signal","_targetOrigin","onEventReceived","logger","debug","computed","setDebug","on","targetOrigin","setTargetOrigin","origin","postMessageImpl","createLogger","resetGlobals","offAll","s","defineFnComposer","obj","propertyName","initialFn","assignedFunctions","property","callAssignedFunctions","unwrappableCallAssignedFunctions","poolSize","defineStaticProperty","defineProxiedProperty","defineMergeableProperty","prop","objKey","objValue","get","set","transformers","string","nullish","optional","unknown","number","boolean","themeParams","windowMessageListener","message","parse","pipeJsonToSchema","miniAppsMessage","schema","data","emit","wnd","path","cursor","receiveEventOwner","receiveEvent","postMessage","postEvent","fpFn","postEventFp","w","request2Fp","eventOrEvents","options","capture","result","addCleanup","createCbCollector","payload","isEventsArray","withCleanup","TE","BetterTaskEither","resolve","_","context","listener","unsub","request2","throwifyAnyEither","e","isVBMA","type","monad","isVBMAFp","BetterPromise","hasProxy","timeout","TimeoutError","mockVBotEnv","onEvent","resetPostMessage","launchParamsQuery","serializeLaunchParamsQuery","parseLaunchParamsQuery","original","next","proxy","postEventDefaulted","captureSameReq","reqId","req_id","releases","getReleaseVersion","parts","a","compareVersions","b","aParts","bParts","len","i","aVal","bVal","supports","paramOrVersion","inVersion","createPostEvent","onUnsupportedOrMode","onUnsupported","params","any","invokeCustomMethodFp","requestId","invokeCustomMethod","requestFp","request","applyPolyfills","decodeBase64UrlFp","c","decodeBase64Url","encodeBase64Url","p1","createStartParamFp","b64","createStartParam","decodeStartParam","arg2","decodeStartParamFp","decoded","J","isSafeToCreateStartParam"],"mappings":";;;;;;;;;;AAOO,SAASA,GAAmBC,GAIjC;AACA,SAAOC;AAAA,IACLC,EAAY,EAAE,kBAAkBA,EAAY,EAAE,WAAWC,EAAA,EAAG,CAAG,GAAG;AAAA,IAClEH;AAAA,EAAA;AAEJ;ACZO,SAASI,KAAoB;AAClC,MAAI;AACF,WAAO,OAAO,SAAS,OAAO;AAAA,EAChC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;ACPO,MAAMC,YAA+C,gBAAAC,EAE1D,0BAA0B,CAACC,GAAQC,MAAY;AAAA,EAC/C,WAAWD,CAAM,yCAAyCC,CAAO;AACnE,CAAC,GAAE;AACH;AAEO,MAAMC,YAAwD,gBAAAH,EAEnE,mCAAmC,CAACC,GAAQG,GAAOF,MAAY;AAAA,EAC/D,cAAcE,CAAK,SAASH,CAAM,gDAAgDC,CAAO;AAC3F,CAAC,GAAE;AACH;AAEO,MAAMG,YAAkD,gBAAAC;AAAA,EAI7D;AAAA,EACA,CAAAC,OAAW,EAAE,QAAAA;EACb,CAAAA,MAAU;AAAA,IACR;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,GAAGA,EAAO,IAAI,CAAC,EAAE,QAAAC,GAAQ,OAAAC,QAChB,WAAWD,CAAM,MAAMC,aAAiB,QAAQA,EAAM,UAAU,OAAOA,CAAK,CAAC,EACrF;AAAA,IAAA,EACD,KAAK;AAAA,CAAI;AAAA,EAAA;AAEf,GAAE;AACF;AAEO,MAAMC,YAA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ACvDyD;AAAA,IAAA;AAAA,EACN;AAEJ;AAyBO,SAASC,GACdxM,GACAuM,GACuE;AACvE,SAAOpM,EAAG;AAAA,IACR2L,GAAkB9L,CAAK;AAAA,IACvB0B,EAAE,MAA2E,CAAA+K,MACtEF,IAGD,OAAOA,KAAS,aACXA,EAAKE,CAAO,IAEdC,GAAE,MAAMD,CAAO,IALb/K,EAAE,MAAM+K,CAAO,CAMzB;AAAA,EAAA;AAEL;AAQO,SAASE,GAAyB3M,GAAwB;AAC/D,SAAOiM,GAAgBjM,CAAK,EAAE,UAAU;AAC1C;"}
1
+ {"version":3,"file":"index.js","sources":["../src/env/hasWebviewProxy.ts","../src/env/isIframe.ts","../src/errors.ts","../src/launch-params.ts","../src/events/createEmitter.ts","../src/events/emitEvent.ts","../src/globals.ts","../src/obj-prop-helpers.ts","../src/events/emitter.ts","../src/methods/postMessage.ts","../src/methods/postEvent.ts","../src/utils/request2.ts","../src/env/isVBMA.ts","../src/env/mockVBotEnv.ts","../src/methods/captureSameReq.ts","../src/methods/getReleaseVersion.ts","../src/utils/compareVersions.ts","../src/methods/supports.ts","../src/methods/createPostEvent.ts","../src/utils/invokeCustomMethod.ts","../src/utils/request.ts","../src/applyPolyfills.ts","../src/base64-url.ts","../src/start-param.ts"],"sourcesContent":["import { looseObject, function as fn, is } from 'valibot';\n\n/**\n * Returns true in case, passed value contains path `VBotWebviewProxy.postEvent` property and\n * `postEvent` is a function.\n * @param value - value to check.\n */\nexport function hasWebviewProxy<T>(value: T): value is T & {\n VBotWebviewProxy: {\n postEvent: (...args: unknown[]) => unknown;\n };\n} {\n return is(\n looseObject({ VBotWebviewProxy: looseObject({ postEvent: fn() }) }),\n value,\n );\n}\n","/**\n * @see https://stackoverflow.com/a/326076\n * @returns True, if current environment is iframe.\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch {\n return true;\n }\n}\n","import type { Version } from '@vbotma/types';\nimport { errorClass, errorClassWithData } from 'error-kid';\n\nexport class MethodUnsupportedError extends /* @__PURE__ */ errorClass<\n [method: string, version: Version]\n>('MethodUnsupportedError', (method, version) => [\n `Method \"${method}\" is unsupported in Mini Apps version ${version}`,\n]) {\n}\n\nexport class MethodParameterUnsupportedError extends /* @__PURE__ */ errorClass<\n [method: string, param: string, version: Version]\n>('MethodParameterUnsupportedError', (method, param, version) => [\n `Parameter \"${param}\" of \"${method}\" method is unsupported in Mini Apps version ${version}`,\n]) {\n}\n\nexport class LaunchParamsRetrieveError extends /* @__PURE__ */ errorClassWithData<\n { errors: { source: string; error: unknown }[] },\n [{ source: string; error: unknown }[]]\n>(\n 'LaunchParamsRetrieveError',\n errors => ({ errors }),\n errors => [\n [\n 'Unable to retrieve launch parameters from any known source. Perhaps, you have opened your app outside Telegram?',\n '📖 Refer to docs for more information:',\n 'https://docs.vbot-mini-apps.com/packages/tma-js-bridge/environment',\n '',\n 'Collected errors:',\n ...errors.map(({ source, error }) => {\n return `Source: ${source} / ${error instanceof Error ? error.message : String(error)}`;\n }),\n ].join('\\n'),\n ],\n) {\n}\n\nexport class InvalidLaunchParamsError extends /* @__PURE__ */ errorClass<\n [launchParams: string, cause: unknown]\n>('InvalidLaunchParamsError', (launchParams, cause) => [\n `Invalid value for launch params: ${launchParams}`,\n { cause },\n]) {\n}\n\nexport class UnknownEnvError extends /* @__PURE__ */ errorClass('UnknownEnvError') {\n}\n\nexport class InvokeCustomMethodFailedError extends /* @__PURE__ */ errorClass<[error: string]>(\n 'InvokeCustomMethodError',\n error => [`Server returned error: ${error}`],\n) {\n}\n","import { throwifyFpFn, getStorageValue, setStorageValue } from '@vbotma/toolkit';\nimport {\n parseLaunchParamsQueryFp,\n type LaunchParamsGenType,\n type ParseLaunchParamsQueryError,\n} from '@vbotma/transformers';\nimport { either as E, function as fn, option as O } from 'fp-ts';\n\nimport { LaunchParamsRetrieveError } from '@/errors.js';\n\nconst SESSION_STORAGE_KEY = 'launchParams';\n\nexport type RetrieveRawInitDataError = RetrieveRawLaunchParamsError;\nexport type RetrieveRawLaunchParamsError = LaunchParamsRetrieveError;\nexport type RetrieveLaunchParamsError = RetrieveRawLaunchParamsError | ParseLaunchParamsQueryError;\nexport type RetrieveLaunchParamsResult = LaunchParamsGenType;\n\n/**\n * @param urlString - URL to extract launch parameters from.\n * @returns Launch parameters from the specified URL.\n * @throws Error if function was unable to extract launch parameters from the\n * passed URL.\n */\nfunction retrieveLpFromUrl(urlString: string): string {\n return urlString\n // Replace everything before this first hashtag or question sign.\n .replace(/^[^?#]*[?#]/, '')\n // Replace all hashtags and question signs to make it look like some search\n // params.\n .replace(/[?#]/g, '&');\n}\n\n/**\n * @returns Launch parameters from any known source.\n */\nexport function retrieveLaunchParamsFp(): E.Either<\n RetrieveLaunchParamsError,\n RetrieveLaunchParamsResult\n> {\n return fn.pipe(\n retrieveRawLaunchParamsFp(),\n E.chainW(parseLaunchParamsQueryFp),\n );\n}\n\n/**\n * @see retrieveLaunchParamsFp\n */\nexport const retrieveLaunchParams: () => RetrieveLaunchParamsResult =\n throwifyFpFn(retrieveLaunchParamsFp);\n\n/**\n * @returns Raw init data from any known source.\n */\nexport function retrieveRawInitDataFp(): E.Either<RetrieveRawInitDataError, O.Option<string>> {\n return fn.pipe(\n retrieveRawLaunchParamsFp(),\n E.map(raw => {\n const v = new URLSearchParams(raw).get('vbWebAppData');\n return v ? O.some(v) : O.none;\n }),\n );\n}\n\n/**\n * @see retrieveRawInitDataFp\n */\nexport function retrieveRawInitData(): string | undefined {\n return fn.pipe(\n retrieveRawInitDataFp(),\n E.fold(err => {\n throw err;\n }, v => v),\n O.match(() => undefined, v => v),\n );\n}\n\n/**\n * @returns Launch parameters in a raw format from any known source.\n */\nexport function retrieveRawLaunchParamsFp(): E.Either<RetrieveRawLaunchParamsError, string> {\n const errors: { source: string; error: unknown }[] = [];\n\n for (const [retrieve, source] of [\n // Try to retrieve launch parameters from the current location. This method\n // can return nothing in case, location was changed, and then the page was\n // reloaded.\n [() => retrieveLpFromUrl(window.location.href), 'window.location.href'],\n // Then, try using the lower level API - window.performance.\n [() => {\n const navigationEntry = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined;\n return navigationEntry && retrieveLpFromUrl(navigationEntry.name);\n }, 'performance navigation entries'],\n // Finally, try using the session storage.\n [() => getStorageValue<string>(SESSION_STORAGE_KEY), 'local storage'],\n ] as const) {\n const v = retrieve();\n if (!v) {\n errors.push({ source, error: new Error('Source is empty') });\n continue;\n }\n const maybeError = fn.pipe(\n parseLaunchParamsQueryFp(v),\n E.foldW(err => err, () => true as const),\n );\n if (typeof maybeError !== 'boolean') {\n errors.push({ source, error: maybeError });\n continue;\n }\n setStorageValue(SESSION_STORAGE_KEY, v);\n return E.right(v);\n }\n return E.left(new LaunchParamsRetrieveError(errors));\n}\n\n/**\n * @see retrieveRawLaunchParamsFp\n */\nexport const retrieveRawLaunchParams = throwifyFpFn(retrieveRawLaunchParamsFp);\n","import type { If, IsNever, IsUndefined, Or } from '@vbotma/toolkit';\nimport mitt, {\n type Emitter,\n type EventHandlerMap,\n type EventType,\n type Handler,\n} from 'mitt';\n\nexport type WildcardHandler<E> = Handler<{\n [K in keyof E]: {\n name: K;\n payload: If<Or<IsNever<E[K]>, IsUndefined<E[K]>>, never, E[K]>;\n };\n}[keyof E]>;\n\nexport interface OnFn<E> {\n /**\n * Adds a new listener for the specified event.\n * @param type - event name.\n * @param handler - event listener.\n * @param once - should this listener be called only once.\n * @returns Function to remove bound event listener.\n */\n <K extends keyof E>(type: K, handler: Handler<E[K]>, once?: boolean): VoidFunction;\n /**\n * Adds a listener to the wildcard event.\n * @param type - event name.\n * @param handler - event listener.\n * @param once - should this listener be called only once.\n * @returns Function to remove bound event listener.\n */\n (type: '*', handler: WildcardHandler<E>, once?: boolean): VoidFunction;\n}\n\nexport interface OffFn<E> {\n /**\n * Removes a listener from the specified event.\n * @param type - event to listen.\n * @param handler - event listener to remove.\n * @param once - had this listener to be called only once.\n */\n <K extends keyof E>(type: K, handler: Handler<E[K]>, once?: boolean): void;\n /**\n * Removes a listener from the wildcard event.\n * @param type - event to stop listening.\n * @param handler - event listener to remove.\n * @param once - should this listener be called only once.\n */\n (type: '*', handler: WildcardHandler<E>, once?: boolean): void;\n}\n\nexport interface EmitFn<E> {\n <K extends keyof E>(type: K, event: E[K]): void;\n <K extends keyof E>(type: undefined extends E[K] ? K : never): void;\n}\n\n/**\n * Creates a new enhanced event emitter.\n * @param onFirst - a function to call every time when the events map appeared to be empty during\n * the event listener creation.\n * @param onEmpty - a function to call every tume when the events map became empty.\n */\nexport function createEmitter<E extends object>(\n onFirst: VoidFunction,\n onEmpty: VoidFunction,\n): {\n on: OnFn<E>;\n off: OffFn<E>;\n emit: EmitFn<E>;\n clear: VoidFunction;\n} {\n // To understand the event handlers concept here, let's tell the underlying idea.\n //\n // We use a Map, where key is an event name, and the value is a Map we call HandlersMap.\n //\n // The HandlersMap is a Map, where the key is an event handler, added by the developer.\n // The corresponding value is a list of tuples, with an internally generated function and a\n // boolean value responsible for determining if the handler must be called only once. So, you\n // can imagine the following map as:\n //\n // HandlersMap {\n // { developer_handler }: Array<[ internally_created_handler, once ]>;\n // }\n //\n // The value for the key represents an array of tuples, as long as a single handler may be added\n // many times, and for each addition we add a new tuple entry.\n //\n // The handler may also be added to be called only once. Trying to remove such kind of handler\n // using a different value of the \"once\" argument will lead to nothing. The developer must\n // specify the same argument value to avoid confusions.\n //\n // Here is the final EventToHandlersMap definition:\n //\n // EventToHandlersMap {\n // { event_name }: HandlersMap {\n // { developer_handler }: Array<[ internally_created_handler, once ]>;\n // }\n // }\n type HandlersMap = Map<\n (...args: any) => void,\n [handler: (...args: any) => void, once: boolean][]\n >;\n\n const eventToHandlersMap = new Map<keyof E | '*', HandlersMap>();\n\n const emitter = (mitt as any as {\n <E extends Record<EventType, unknown>>(all?: EventHandlerMap<E>): Emitter<E>;\n })<E & Record<string | symbol, unknown>>();\n\n const off: OffFn<E> = (\n event: keyof E | '*',\n handler: (...args: any) => void,\n once = false,\n ) => {\n const handlersMap: HandlersMap = eventToHandlersMap.get(event) || new Map();\n eventToHandlersMap.set(event, handlersMap);\n\n const handlers = handlersMap.get(handler) || [];\n handlersMap.set(handler, handlers);\n\n const index = handlers.findIndex(item => item[1] === once);\n if (index >= 0) {\n // Remove the related handler.\n emitter.off(event, handlers[index][0]);\n\n // Remove the handler from the cache array.\n handlers.splice(index, 1);\n\n // If after removal, there are no handlers left, we should remove the entry from the cache.\n if (!handlers.length) {\n handlersMap.delete(handler);\n if (!handlersMap.size) {\n const prevSize = eventToHandlersMap.size;\n eventToHandlersMap.delete(event);\n prevSize && !eventToHandlersMap.size && onEmpty();\n }\n }\n }\n };\n\n return {\n on(event: keyof E | '*', handler: (...args: any[]) => any, once?: boolean) {\n // The events' map became non-empty. Call the onFirst callback.\n !eventToHandlersMap.size && onFirst();\n\n const cleanup = () => {\n off(event as any, handler, once);\n };\n\n const internalHandler = (...args: any[]) => {\n once && cleanup();\n if (event === '*') {\n handler({ name: args[0], payload: args[1] });\n } else {\n handler(...args);\n }\n };\n\n emitter.on(event, internalHandler);\n\n // Add this handler to the cache, so we could remove it using the passed listener.\n const handlersMap: HandlersMap = eventToHandlersMap.get(event) || new Map();\n eventToHandlersMap.set(event, handlersMap);\n\n const handlers = handlersMap.get(handler) || [];\n handlersMap.set(handler, handlers);\n handlers.push([internalHandler, once || false]);\n\n return cleanup;\n },\n off,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n emit: emitter.emit,\n clear() {\n const prevSize = eventToHandlersMap.size;\n emitter.all.clear();\n eventToHandlersMap.clear();\n prevSize && onEmpty();\n },\n };\n}\n","import type { EventPayload, EventWithoutPayload, EventWithPayload } from '@/events/types/index.js';\n\n/**\n * Emits an event without payload sent from the Telegram native application like it was sent in\n * a default web environment between two iframes.\n *\n * It dispatches a new MessageEvent and expects it to be handled via\n * the `window.addEventListener('message', ...)` call, as a developer would do it to handle\n * messages sent from the parent iframe.\n * @param eventType - event name.\n */\nexport function emitEvent<E extends EventWithoutPayload>(eventType: E): void;\n\n/**\n * Emits an event with payload sent from the Telegram native application like it was sent in\n * a default web environment between two iframes.\n *\n * It dispatches a new MessageEvent and expects it to be handled via\n * the `window.addEventListener('message', ...)` call, as a developer would do it to handle\n * messages sent from the parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nexport function emitEvent<E extends EventWithPayload>(\n eventType: E,\n eventData: EventPayload<E>,\n): void;\n\n/**\n * Emits an unknown event sent from the Telegram native application like it was sent in a default\n * web environment between two iframes.\n *\n * It dispatches a new MessageEvent and expects it to be handled via\n * the `window.addEventListener('message', ...)` call, as a developer would do it to handle\n * messages sent from the parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nexport function emitEvent<E extends string>(\n eventType: E,\n eventData: E extends EventWithoutPayload\n ? never\n : E extends EventWithPayload\n ? EventPayload<E>\n : unknown,\n): void;\n\n/**\n * Emits an event sent from the Telegram native application like it was sent in a default web\n * environment between two iframes.\n *\n * It dispatches a new MessageEvent and expects it to be handled via\n * the `window.addEventListener('message', ...)` call, as a developer would do it to handle\n * messages sent from the parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nexport function emitEvent(eventType: string, eventData?: unknown): void {\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType, eventData }),\n // We specify this kind of source here in order to allow the package's \"on\" function to\n // capture it. The reason is this function always checks the event source and relies on\n // it to be the parent window.\n source: window.parent,\n }));\n}\n","import { signal, computed } from '@vbotma/signals';\nimport { createLogger, type Logger } from '@vbotma/toolkit';\n\nimport { off, offAll, on } from '@/events/emitter.js';\nimport type { SubscribeListener } from '@/events/types/index.js';\nimport type { PostMessage } from '@/methods/postMessage.js';\n\n/**\n * @internal\n */\nconst _debug = signal(false);\n/**\n * @internal\n */\nconst _targetOrigin = signal('https://web.telegram.org');\n\nconst onEventReceived: SubscribeListener = event => {\n logger().log('Event received:', event);\n};\n\n/**\n * The current debug mode state.\n *\n * To update the value, use the `setDebug` function.\n * @see setDebug\n */\nexport const debug = computed(_debug);\n\n/**\n * Sets the package debug mode.\n *\n * Enabling debug mode leads to printing additional messages in the console related to the\n * processes inside the package.\n * @param value - enable debug mode.\n */\nexport function setDebug(value: boolean): void {\n if (value !== _debug()) {\n _debug.set(value);\n (value ? on : off)('*', onEventReceived);\n }\n}\n\n/**\n * The current target origin used by the `postEvent` method.\n *\n * You don't need to override this value until you know what you are doing.\n * To update the value, use the `setTargetOrigin` function.\n * @default 'https://web.telegram.org'\n * @see setTargetOrigin\n */\nexport const targetOrigin = computed(_targetOrigin);\n\n/**\n * Sets a new target origin that is being used when calling the `postEvent` function in Telegram\n * web versions.\n *\n * You don't need to override this value until you know what you are doing.\n * @param origin - allowed target origin value.\n * @see _targetOrigin\n */\nexport function setTargetOrigin(origin: string) {\n _targetOrigin.set(origin);\n logger().log('New target origin set', origin);\n}\n\n/**\n * Signal containing a custom implementation of the method to post a message to the parent\n * window. We usually use it to send a message in web versions of Telegram.\n *\n * @default A function behaving like the `window.parent.postMessage` method.\n */\nexport const postMessageImpl = signal<PostMessage>((...args) => {\n window.parent.postMessage(...args as unknown as Parameters<PostMessage>);\n});\n\n/**\n * The package logger. You can override this value in order to use your own implementation.\n */\nexport const logger = signal<Logger>(createLogger('Bridge', {\n bgColor: '#9147ff',\n textColor: 'white',\n shouldLog: debug,\n}));\n\n/**\n * Resets the package global values. Normally, you don't use this function in your application.\n * We are using it only for test purposes.\n */\nexport function resetGlobals() {\n offAll();\n [postMessageImpl, _targetOrigin, targetOrigin, _debug, debug, logger].forEach(s => {\n s.unsubAll();\n 'reset' in s && s.reset();\n });\n}\n","/**\n * Defines a property, that is a functions compose. Trying to set a value in this property\n * will lead to adding it to a function's pool. The property value will always be equal to a\n * function, calling all collected functions in the pool.\n *\n * Returned function performs a cleanup. It does one of the following:\n * 1. Removes the property if no functions were to the pool added other than the initial one.\n * 2. Sets the value equal to the first added function to the pool after the initial one if\n * the only one additional function was added at all. In other words, if the pool length is equal\n * to 2, the second item will be selected as the property value.\n * 3. Leaves the value equal to a function calling all pool functions, but removes the initially\n * added one.\n * @param obj - object.\n * @param propertyName - object property.\n * @param initialFn - an initial function to set.\n */\nexport function defineFnComposer(\n obj: any,\n propertyName: string,\n initialFn: (...args: any) => any,\n): void {\n const assignedFunctions: any[] = [initialFn];\n\n const property = obj[propertyName];\n if (typeof property === 'function') {\n assignedFunctions.push(property);\n }\n\n const callAssignedFunctions = (...args: any) => {\n assignedFunctions.forEach(fn => fn(...args));\n };\n\n // Wrap the callPool function and add \"unwrap\" method to it.\n const unwrappableCallAssignedFunctions = Object.assign((...args: any) => {\n callAssignedFunctions(...args);\n }, {\n // Unwraps the composer.\n unwrap() {\n const { length: poolSize } = assignedFunctions;\n if (poolSize === 1) {\n // Only the initial handler is in the pool. In this case we just remove the property.\n delete obj[propertyName];\n return;\n }\n if (poolSize === 2) {\n // Only one additional handler was added. We set it as a value for the property.\n defineStaticProperty(obj, propertyName, assignedFunctions[1]);\n return;\n }\n // Many additional handlers were added. In this case we remove the initially added function\n // from the pool and leave the property value almost as is - only \"unwrap\" method will be\n // removed.\n assignedFunctions.unshift(1);\n defineStaticProperty(obj, propertyName, callAssignedFunctions);\n },\n });\n\n // This property should now always return our special function. Trying to set it to another\n // function should lead to just adding it to the pool of called functions.\n defineProxiedProperty(\n obj,\n propertyName,\n () => unwrappableCallAssignedFunctions,\n value => assignedFunctions.push(value),\n );\n}\n\n/**\n * Wires the specified property in the object preventing it from being overwritten. Instead, it\n * enhances the previous value by merging the current one with the passed one.\n * @param obj - object.\n * @param prop - object property to rewire.\n */\nexport function defineMergeableProperty(obj: any, prop: string): void {\n const value = obj[prop];\n defineProxiedProperty(obj, prop, () => value, v => {\n Object.entries(v).forEach(([objKey, objValue]) => {\n value[objKey] = objValue;\n });\n });\n}\n\n/**\n * Defines an enumerable and configurable property with a getter and setter.\n * @param obj - object.\n * @param prop - object property name.\n * @param get - getter to use.\n * @param set - setter to use.\n */\nexport function defineProxiedProperty(\n obj: any,\n prop: string,\n get: () => unknown,\n set: (v: any) => void,\n) {\n Object.defineProperty(obj, prop, {\n enumerable: true,\n configurable: true,\n get,\n set,\n });\n}\n\n/**\n * Defines an enumerable, configurable and writable property with the initial value.\n * @param obj - object.\n * @param prop - object property name.\n * @param value - value to set.\n */\nexport function defineStaticProperty(obj: any, prop: string, value: any): void {\n Object.defineProperty(obj, prop, {\n enumerable: true,\n configurable: true,\n writable: true,\n value,\n });\n}\n","import { miniAppsMessage, pipeJsonToSchema, themeParams } from '@vbotma/transformers';\nimport {\n boolean,\n looseObject,\n nullish,\n number,\n optional,\n parse,\n string,\n unknown,\n type BaseSchema,\n} from 'valibot';\n\nimport { createEmitter } from '@/events/createEmitter.js';\nimport { emitEvent } from '@/events/emitEvent.js';\nimport type { EventName, EventPayload, Events } from '@/events/types/index.js';\nimport { logger } from '@/globals.js';\nimport { defineFnComposer, defineMergeableProperty } from '@/obj-prop-helpers.js';\n\n/**\n * Transformers for problematic Mini Apps events.\n */\nconst transformers = {\n clipboard_text_received: looseObject({\n req_id: string(),\n data: nullish(string()),\n }),\n custom_method_invoked: looseObject({\n req_id: string(),\n result: optional(unknown()),\n error: optional(string()),\n }),\n popup_closed: nullish(\n looseObject({ button_id: nullish(string(), () => undefined) }),\n {},\n ),\n viewport_changed: nullish(\n looseObject({\n height: number(),\n width: nullish(number(), () => window.innerWidth),\n is_state_stable: boolean(),\n is_expanded: boolean(),\n }),\n // TODO: At the moment, macOS has a bug with the invalid event payload - it is always equal to\n // null. Leaving this default value until the bug is fixed.\n () => ({\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n }),\n ),\n theme_changed: looseObject({\n theme_params: themeParams(),\n }),\n} as const satisfies { [E in EventName]?: BaseSchema<unknown, EventPayload<E>, any> };\n\nfunction windowMessageListener(event: MessageEvent): void {\n // Ignore non-parent window messages.\n if (event.source !== window.parent) {\n return;\n }\n\n // Parse incoming event data.\n let message: { eventType: string; eventData?: unknown };\n try {\n message = parse(pipeJsonToSchema(miniAppsMessage()), event.data);\n } catch {\n // We ignore incorrect messages as they could be generated by any other code.\n return;\n }\n\n const { eventType, eventData } = message;\n const schema = transformers[eventType as keyof typeof transformers];\n\n let data: unknown;\n try {\n data = schema ? parse(schema, eventData) : eventData;\n } catch (cause) {\n return logger().forceError(\n [\n `An error occurred processing the \"${eventType}\" event from the VBot application.`,\n 'Please, file an issue here:',\n 'https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose',\n ].join('\\n'),\n message,\n cause,\n );\n }\n emit(eventType as any, data);\n}\n\nexport const {\n on,\n off,\n emit,\n clear: offAll,\n} = createEmitter<Events>(\n () => {\n const wnd = window as any;\n\n // Define all functions responsible for receiving an event from the VBot client.\n // All these \"ports\" should narrow the communication way to a single specific one - the way\n // accepted by the web version of Telegram between iframes.\n //\n // Here we consider 2 cases:\n // 1. When the Telegram SDK is already connected. In this case the Telegram SDK already\n // installed its own ports, and we should rewire them. The cleanup function should also work\n // properly in this context, removing @vbotma/bridge handler only, not\n // the Telegram SDK one.\n // 2. When the Telegram SDK is not connected, but probably will be. We know, that\n // the Telegram SDK is going to overwrite our own handlers. Due to this reason, we should\n // protect them from being overwritten, but still support handlers defined by the Telegram SDK.\n\n // TelegramGameProxy.receiveEvent\n !wnd.TelegramGameProxy && (wnd.TelegramGameProxy = {});\n defineFnComposer(wnd.TelegramGameProxy, 'receiveEvent', emitEvent);\n defineMergeableProperty(wnd, 'TelegramGameProxy');\n\n // VBot.WebView.receiveEvent\n !wnd.VBot && (wnd.VBot = {});\n !wnd.VBot.WebView && (wnd.VBot.WebView = {});\n defineFnComposer(wnd.VBot.WebView, 'receiveEvent', emitEvent);\n defineMergeableProperty(wnd.VBot, 'WebView');\n\n // TelegramGameProxy_receiveEvent\n defineFnComposer(wnd, 'TelegramGameProxy_receiveEvent', emitEvent);\n\n // Add a listener handling events sent from the Telegram web application and also events\n // generated by the local emitEvent function.\n // This handler should emit a new event using the library event emitter.\n window.addEventListener('message', windowMessageListener);\n },\n () => {\n [\n ['TelegramGameProxy_receiveEvent'],\n ['TelegramGameProxy', 'receiveEvent'],\n ['VBot', 'WebView', 'receiveEvent'],\n ].forEach(path => {\n const wnd = window as any;\n\n // A tuple, where the first value is the receiveEvent function owner, and the second\n // value is the receiveEvent itself.\n let cursor: [obj: any, receieveEvent: any] = [undefined, wnd];\n for (const item of path) {\n cursor = [cursor[1], cursor[1][item]];\n if (!cursor[1]) {\n return;\n }\n }\n const [receiveEventOwner, receiveEvent] = cursor;\n if ('unwrap' in receiveEvent) {\n receiveEvent.unwrap();\n if (\n receiveEventOwner\n && receiveEventOwner !== wnd\n && !Object.keys(receiveEventOwner).length\n ) {\n delete wnd[path[0]];\n }\n }\n });\n window.removeEventListener('message', windowMessageListener);\n },\n);\n","import { postMessageImpl } from '@/globals.js';\n\nexport type PostMessage = typeof window.parent.postMessage;\n\n/**\n * Posts a message to the parent window. We usually use it to send a message in web versions of\n * Telegram.\n * @param args - `window.parent.postMessage` arguments.\n */\nexport const postMessage: PostMessage = (...args) => {\n return postMessageImpl()(...args as unknown as Parameters<PostMessage>);\n};\n","import { either as E, function as fpFn } from 'fp-ts';\nimport { function as fn, is, looseObject } from 'valibot';\n\nimport { hasWebviewProxy } from '@/env/hasWebviewProxy.js';\nimport { isIframe } from '@/env/isIframe.js';\nimport { UnknownEnvError } from '@/errors.js';\nimport { logger, targetOrigin } from '@/globals.js';\nimport type {\n MethodName,\n MethodNameWithOptionalParams,\n MethodNameWithoutParams,\n MethodNameWithRequiredParams,\n MethodParams,\n} from '@/methods/types/index.js';\n\nimport { postMessage } from './postMessage.js';\n\nexport type PostEventError = UnknownEnvError;\nexport type PostEventFn = typeof postEvent;\nexport type PostEventFpFn = typeof postEventFp;\n\n/**\n * @see postEventFp\n */\nexport function postEvent<Method extends MethodNameWithRequiredParams>(\n method: Method,\n params: MethodParams<Method>,\n): void;\n/**\n * @see postEventFp\n */\nexport function postEvent(method: MethodNameWithoutParams): void;\n/**\n * @see postEventFp\n */\nexport function postEvent<Method extends MethodNameWithOptionalParams>(\n method: Method,\n params?: MethodParams<Method>,\n): void;\n\nexport function postEvent(\n eventType: MethodName,\n eventData?: MethodParams<MethodName>,\n): void {\n fpFn.pipe(\n postEventFp(\n // @ts-expect-error It's ok, TS can't determine a specific override.\n eventType,\n eventData,\n ),\n E.mapLeft(err => {\n throw err;\n }),\n );\n}\n\n/**\n * Calls Mini Apps methods requiring parameters.\n * @param method - method name.\n * @param params - options along with params.\n */\nexport function postEventFp<Method extends MethodNameWithRequiredParams>(\n method: Method,\n params: MethodParams<Method>,\n): E.Either<PostEventError, void>;\n\n/**\n * Calls Mini Apps methods accepting no parameters at all.\n * @param method - method name.\n */\nexport function postEventFp(method: MethodNameWithoutParams): E.Either<PostEventError, void>;\n\n/**\n * Calls Mini Apps methods accepting optional parameters.\n * @param method - method name.\n * @param params - options along with params.\n */\nexport function postEventFp<Method extends MethodNameWithOptionalParams>(\n method: Method,\n params?: MethodParams<Method>,\n): E.Either<PostEventError, void>;\n\nexport function postEventFp(\n eventType: MethodName,\n eventData?: MethodParams<MethodName>,\n): E.Either<PostEventError, void> {\n logger().log('Posting event:', eventData ? { eventType, eventData } : { eventType });\n\n const w = window;\n const message = JSON.stringify({ eventType, eventData });\n\n // Telegram Web.\n if (isIframe()) {\n postMessage(message, targetOrigin());\n return E.right(undefined);\n }\n\n // Telegram for iOS, macOS, Android and Telegram Desktop.\n if (hasWebviewProxy(w)) {\n w.VBotWebviewProxy.postEvent(eventType, JSON.stringify(eventData));\n return E.right(undefined);\n }\n\n // Telegram for Windows Phone or Android.\n if (is(looseObject({ external: looseObject({ notify: fn() }) }), w)) {\n w.external.notify(message);\n return E.right(undefined);\n }\n\n // Otherwise, the current environment is unknown, and we are not able to send event.\n return E.left(new UnknownEnvError());\n}\n","import { signal } from '@vbotma/signals';\nimport {\n BetterTaskEither,\n type If,\n type IsNever,\n createCbCollector,\n throwifyAnyEither,\n} from '@vbotma/toolkit';\nimport { BetterPromise } from 'better-promises';\nimport { either as E, taskEither as TE, function as fn } from 'fp-ts';\n\nimport { on } from '@/events/emitter.js';\nimport type { EventName, EventPayload } from '@/events/types/index.js';\nimport { postEventFp } from '@/methods/postEvent.js';\nimport type {\n MethodName,\n MethodNameWithOptionalParams,\n MethodNameWithRequiredParams,\n MethodNameWithoutParams,\n MethodParams,\n} from '@/methods/types/index.js';\n\nimport type {\n RequestCaptureEventFn,\n RequestCaptureEventsFn,\n RequestCaptureFn,\n RequestError,\n RequestFpOptions,\n RequestOptions,\n RequestCaptureFnEventsPayload,\n} from './request.js';\n\ntype AnyEventName = EventName | EventName[];\n\nexport type Request2Error = RequestError;\nexport type Request2CaptureEventsFn<E extends EventName[]> = RequestCaptureEventsFn<E>;\nexport type Request2CaptureEventFn<E extends EventName> = RequestCaptureEventFn<E>;\nexport type Request2CaptureFn<E extends AnyEventName> = RequestCaptureFn<E>;\nexport type Request2Options<E extends AnyEventName> = RequestOptions<E>;\nexport type Request2FpOptions<E extends AnyEventName> = RequestFpOptions<E>;\nexport type Request2CaptureFnEventsPayload<E extends EventName[]> =\n RequestCaptureFnEventsPayload<E>;\nexport type Request2Result<E extends AnyEventName> =\n E extends (infer U extends EventName)[]\n ? U extends infer K extends EventName\n ? { event: K; payload: If<IsNever<EventPayload<K>>, undefined, EventPayload<K>> }\n : never\n : E extends EventName\n ? If<IsNever<EventPayload<E>>, undefined, EventPayload<E>>\n : never;\n\nexport type Request2Fn = typeof request2;\nexport type Request2FpFn = typeof request2Fp;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n */\nexport function request2Fp<\n M extends MethodNameWithRequiredParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options: Request2FpOptions<E> & { params: MethodParams<M> },\n): TE.TaskEither<Request2Error | AbortError, Request2Result<E>>;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n */\nexport function request2Fp<\n M extends MethodNameWithOptionalParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options?: Request2FpOptions<E> & { params?: MethodParams<M> },\n): TE.TaskEither<Request2Error | AbortError, Request2Result<E>>;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n */\nexport function request2Fp<\n M extends MethodNameWithoutParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options?: Request2FpOptions<E>,\n): TE.TaskEither<Request2Error | AbortError, Request2Result<E>>;\n\nexport function request2Fp<\n M extends MethodName,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options: Request2FpOptions<E> & { params?: MethodParams<M> } = {},\n): TE.TaskEither<Request2Error | AbortError, Request2Result<E>> {\n const {\n // If no capture function was passed, we capture the first compatible event.\n capture = () => true,\n postEvent = postEventFp,\n } = options;\n\n // TODO: Maybe we want to rewrite it using a simple BetterPromise.\n\n const result = signal<undefined | [Request2Result<E>]>();\n const [addCleanup, cleanup] = createCbCollector();\n // Iterate over all the tracked events and add a listener, checking if the event should be\n // captured.\n (Array.isArray(eventOrEvents) ? eventOrEvents : [eventOrEvents]).forEach(event => {\n // Each event listener waits for the event to occur.\n // Then, if the capture function was passed, we should check if the event should\n // be captured. If the function is omitted, we instantly capture the event.\n addCleanup(\n on(event, payload => {\n const isEventsArray = Array.isArray(eventOrEvents);\n if (\n isEventsArray\n ? (capture as Request2CaptureEventsFn<EventName[]>)({ event, payload })\n : (capture as Request2CaptureEventFn<EventName>)(payload)\n ) {\n result.set([\n (isEventsArray ? { event, payload } : payload) as Request2Result<E>,\n ]);\n }\n }),\n );\n });\n const withCleanup = <T>(value: T): T => {\n cleanup();\n return value;\n };\n\n return fn.pipe(\n async () => postEvent(method as any, (options as any).params),\n TE.chainW(() => {\n return BetterTaskEither<AbortError, Request2Result<E>>((resolve, _, context) => {\n // When creating this BetterTaskEither, we could already have a value stored in\n // the result signal. For example, when tracked events were generated via emitEvent in\n // mockVBotEnv.onEvent.\n const data = result();\n if (data) {\n return resolve(data[0]);\n }\n\n const listener = (data: [Request2Result<E>] | undefined) => {\n if (data) {\n resolve(data[0]);\n }\n };\n const unsub = () => {\n result.unsub(listener);\n };\n result.sub(listener);\n context.on('finalized', unsub);\n }, options);\n }),\n TE.mapBoth(withCleanup, withCleanup),\n );\n}\n\n/**\n * @see request2Fp\n */\nexport function request2<M extends MethodNameWithRequiredParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options: Request2Options<E> & { params: MethodParams<M> },\n): BetterPromise<Request2Result<E>>;\n\n/**\n * @see request2Fp\n */\nexport function request2<M extends MethodNameWithOptionalParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: Request2Options<E> & { params?: MethodParams<M> },\n): BetterPromise<Request2Result<E>>;\n\n/**\n * @see request2Fp\n */\nexport function request2<M extends MethodNameWithoutParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: Request2Options<E>,\n): BetterPromise<Request2Result<E>>;\n\nexport function request2<M extends MethodName, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: Request2Options<E> & { params?: MethodParams<M> },\n): BetterPromise<Request2Result<E>> {\n const { postEvent } = options || {};\n\n return throwifyAnyEither(\n // @ts-expect-error TypeScript will not be able to handle our overrides here.\n request2Fp(method, eventOrEvents, {\n ...options,\n postEvent: postEvent\n ? (...args: any[]) => {\n try {\n // @ts-expect-error TypeScript will not be able to handle our overrides here.\n postEvent(...args);\n return E.right(undefined);\n } catch (e) {\n return E.left(e);\n }\n }\n : postEventFp,\n }),\n );\n}\n","import { throwifyAnyEither } from '@vbotma/toolkit';\nimport {\n BetterPromise,\n type BetterPromiseOptions,\n TimeoutError,\n} from 'better-promises';\nimport { either as E, taskEither as TE, function as fn } from 'fp-ts';\n\nimport { hasWebviewProxy } from '@/env/hasWebviewProxy.js';\nimport { UnknownEnvError } from '@/errors.js';\nimport { retrieveRawLaunchParamsFp } from '@/launch-params.js';\nimport { type Request2Error, request2Fp } from '@/utils/request2.js';\n\nexport type isVBMAError = Exclude<Request2Error, TimeoutError>;\n\n/**\n * @see isVBMAFp\n */\nexport function isVBMA(): boolean;\n/**\n * @see isVBMAFp\n */\nexport function isVBMA(type: 'complete', options?: BetterPromiseOptions): BetterPromise<boolean>;\nexport function isVBMA(\n type?: 'complete',\n options?: BetterPromiseOptions,\n): boolean | BetterPromise<boolean> {\n const monad = isVBMAFp(\n // @ts-expect-error TS doesn't get what override we are going to use.\n type,\n options,\n );\n return typeof monad === 'function'\n ? BetterPromise.fn(() => throwifyAnyEither(monad as TE.TaskEither<any, boolean>))\n : monad;\n}\n\n/**\n * Returns true if the current environment is VBot Mini Apps.\n *\n * It uses the `retrieveLaunchParams` function to determine if the environment\n * contains launch parameters. In case it does, true will be returned.\n *\n * In case you need stricter checks, use async override of this function.\n */\nexport function isVBMAFp(): boolean;\n/**\n * Returns promise with true if the current environment is VBot Mini Apps.\n *\n * First of all, it checks if the current environment contains traits specific\n * to the Mini Apps environment. Then, it attempts to call a Mini Apps method\n * and waits for a response to be received.\n *\n * In case you need less strict checks, use sync override of this function.\n */\nexport function isVBMAFp(\n type: 'complete',\n options?: BetterPromiseOptions,\n): TE.TaskEither<isVBMAError, boolean>;\nexport function isVBMAFp(\n type?: 'complete',\n options?: BetterPromiseOptions,\n): boolean | TE.TaskEither<isVBMAError, boolean> {\n const hasProxy = hasWebviewProxy(window);\n if (!type) {\n return hasProxy || fn.pipe(retrieveRawLaunchParamsFp(), E.match(() => false, () => true));\n }\n if (hasProxy) {\n return TE.right(true);\n }\n const { timeout = 100 } = options || {};\n\n return fn.pipe(\n request2Fp('web_app_request_theme', 'theme_changed', { ...options, timeout }),\n TE.match(\n error => (\n TimeoutError.is(error) || UnknownEnvError.is(error)\n ? E.right(false)\n : E.left(error)\n ),\n () => E.right(true),\n ),\n );\n}\n","import { setStorageValue } from '@vbotma/toolkit';\nimport {\n miniAppsMessage,\n parseLaunchParamsQuery,\n pipeJsonToSchema,\n serializeLaunchParamsQuery,\n type LaunchParamsLike,\n} from '@vbotma/transformers';\nimport { parse } from 'valibot';\n\nimport { isIframe } from '@/env/isIframe.js';\nimport { InvalidLaunchParamsError } from '@/errors.js';\nimport { logger, postMessageImpl } from '@/globals.js';\nimport type { MethodName, MethodParams } from '@/methods/types/index.js';\n\n/**\n * Mocks the environment and imitates VBot Mini Apps behavior.\n *\n * We usually use this function in the following cases:\n * 1. We are developing an application outside the VBot environment and would like to imitate\n * the VBot client in order to re-create the same communication behavior.\n * 2. We would like to intercept some VBot Mini Apps methods' calls in order to enhance them\n * or write a custom behavior. It is extremely useful in some VBot clients improperly handling\n * Mini Apps methods' calls and not even responding.\n *\n * Note that calling this function in Telegram web clients, the `postMessageImplementation` signal\n * value will be updated with a new one, enhancing previously set signal value to allow wrapping\n * the original `window.parent.postMessage` function. In other words, calling `mockVBotEnv`\n * function N times, you will effectively wrap previously set implementation N times, so be\n * careful calling this function several times during a single lifecycle of the app. In case you\n * would like to avoid such kind of behavior, use the `resetPostMessage` option.\n */\nexport function mockVBotEnv({ launchParams, onEvent, resetPostMessage }: {\n /**\n * Launch parameters to mock. They will be saved in the storage, so the SDK functions could\n * retrieve them.\n *\n * Note that this value must have `vbWebAppData` presented in a raw format as long as you will\n * need it when retrieving init data in this format. Otherwise, init data may be broken.\n */\n launchParams?:\n | (Omit<LaunchParamsLike, 'vbWebAppData'> & { vbWebAppData?: string | URLSearchParams })\n | string\n | URLSearchParams;\n /**\n * Function that will be called if a Mini Apps method call was requested by the mini app.\n *\n * It receives a Mini Apps method name along with the passed payload.\n *\n * Note that using the `next` function, in non-web environments it uses the\n * `window.VBotWebviewProxy.postEvent` method.\n *\n * Talking about the web versions of Telegram, the value of `next` is a bit more complex - it\n * will be equal to the value stored in the `postMessageImpl` signal set previously. By default,\n * this value contains a function utilizing the `window.parent.postMessage` method.\n * @param event - event information.\n * @param next - function to call the original method used to call a Mini Apps method.\n */\n onEvent?: (\n event:\n | { [M in MethodName]: { name: M; params: MethodParams<M> } }[MethodName]\n | { name: string; params: unknown },\n next: () => void,\n ) => void;\n /**\n * Removes all previously set enhancements of the `window.parent.postMessage` function set\n * by other `mockVBotEnv` calls.\n * @default false\n */\n resetPostMessage?: boolean;\n} = {}): void {\n if (launchParams) {\n // If launch parameters were passed, save them in the session storage, so\n // the retrieveLaunchParams function would return them.\n const launchParamsQuery =\n typeof launchParams === 'string' || launchParams instanceof URLSearchParams\n ? launchParams.toString()\n : (\n // Here we have to trick serializeLaunchParamsQuery into thinking, it serializes a valid\n // value. We are doing it because we are working with vbWebAppData presented as a\n // string, not an object as serializeLaunchParamsQuery requires.\n serializeLaunchParamsQuery({ ...launchParams, vbWebAppData: undefined })\n // Then, we just append init data.\n + (launchParams.vbWebAppData ? `&vbWebAppData=${encodeURIComponent(launchParams.vbWebAppData.toString())}` : '')\n );\n\n // Remember to check if launch params are valid.\n try {\n parseLaunchParamsQuery(launchParamsQuery);\n } catch (e) {\n throw new InvalidLaunchParamsError(launchParamsQuery, e);\n }\n setStorageValue('launchParams', launchParamsQuery);\n }\n\n // Original postEvent firstly checks if the current environment is iframe.\n // That's why we have a separate branch for this environment here too.\n if (isIframe()) {\n if (!onEvent) {\n return;\n }\n // As long as the postEvent function uses the postMessage method, we should rewire it.\n if (resetPostMessage) {\n postMessageImpl.reset();\n }\n\n const original = postMessageImpl();\n postMessageImpl.set((...args) => {\n const [message] = args;\n const next = () => {\n (original as any)(...args);\n };\n\n // Pass only VBot Mini Apps events to the handler. All other calls should be passed\n // to the original handler (window.parent.postMessage likely).\n try {\n const data = parse(pipeJsonToSchema(miniAppsMessage()), message);\n onEvent({ name: data.eventType, params: data.eventData }, next);\n } catch {\n next();\n }\n });\n return;\n }\n\n // In all other environments, it is enough to define window.VBotWebviewProxy.postEvent.\n const proxy = (window as any).VBotWebviewProxy || {};\n const postEventDefaulted = proxy.postEvent || (() => undefined);\n (window as any).VBotWebviewProxy = {\n ...proxy,\n postEvent(eventType: string, eventData: string) {\n const next = () => {\n postEventDefaulted(eventType, eventData);\n };\n onEvent\n ? onEvent({\n name: eventType,\n params: eventData ? JSON.parse(eventData) : undefined,\n }, next)\n : next();\n },\n };\n\n logger().log('Environment was mocked by the mockVBotEnv function');\n}\n","type CaptureSameReqFn = (payload: { req_id: string }) => boolean;\n\n/**\n * Returns a function which can be used in `request` function `capture` property to capture\n * the event with the same request identifier.\n * @param reqId - request identifier.\n */\nexport function captureSameReq(reqId: string): CaptureSameReqFn {\n return ({ req_id }) => req_id === reqId;\n}\n","import { Version } from '@vbotma/types';\n\nimport {\n MethodName,\n MethodNameWithVersionedParams,\n MethodVersionedParams,\n} from '@/methods/types/index.js';\n\nconst releases = {\n '6.0': [\n 'iframe_ready',\n 'iframe_will_reload',\n 'web_app_close',\n 'web_app_data_send',\n 'web_app_expand',\n 'web_app_open_link',\n 'web_app_ready',\n 'web_app_request_theme',\n 'web_app_request_viewport',\n 'web_app_setup_main_button',\n 'web_app_setup_closing_behavior',\n ],\n 6.1: [\n 'web_app_open_tg_link',\n 'web_app_open_invoice',\n 'web_app_setup_back_button',\n 'web_app_set_background_color',\n 'web_app_set_header_color',\n 'web_app_trigger_haptic_feedback',\n ],\n 6.2: ['web_app_open_popup'],\n 6.4: [\n 'web_app_close_scan_qr_popup',\n 'web_app_open_scan_qr_popup',\n 'web_app_read_text_from_clipboard',\n { method: 'web_app_open_link', param: 'try_instant_view' },\n ],\n 6.7: ['web_app_switch_inline_query'],\n 6.9: [\n 'web_app_invoke_custom_method',\n 'web_app_request_write_access',\n 'web_app_request_phone',\n { method: 'web_app_set_header_color', param: 'color' },\n ],\n '6.10': ['web_app_setup_settings_button'],\n 7.2: [\n 'web_app_biometry_get_info',\n 'web_app_biometry_open_settings',\n 'web_app_biometry_request_access',\n 'web_app_biometry_request_auth',\n 'web_app_biometry_update_token',\n ],\n 7.6: [\n { method: 'web_app_open_link', param: 'try_browser' },\n { method: 'web_app_close', param: 'return_back' },\n ],\n 7.7: ['web_app_setup_swipe_behavior'],\n 7.8: ['web_app_share_to_story'],\n '7.10': [\n 'web_app_setup_secondary_button',\n 'web_app_set_bottom_bar_color',\n { method: 'web_app_setup_main_button', param: 'has_shine_effect' },\n ],\n '8.0': [\n 'web_app_request_safe_area',\n 'web_app_request_content_safe_area',\n 'web_app_request_fullscreen',\n 'web_app_exit_fullscreen',\n 'web_app_set_emoji_status',\n 'web_app_add_to_home_screen',\n 'web_app_check_home_screen',\n 'web_app_request_emoji_status_access',\n 'web_app_check_location',\n 'web_app_open_location_settings',\n 'web_app_request_file_download',\n 'web_app_request_location',\n 'web_app_send_prepared_message',\n 'web_app_start_accelerometer',\n 'web_app_start_device_orientation',\n 'web_app_start_gyroscope',\n 'web_app_stop_accelerometer',\n 'web_app_stop_device_orientation',\n 'web_app_stop_gyroscope',\n 'web_app_toggle_orientation_lock',\n ],\n '9.0': [\n 'web_app_device_storage_clear',\n 'web_app_device_storage_get_key',\n 'web_app_device_storage_save_key',\n 'web_app_secure_storage_clear',\n 'web_app_secure_storage_get_key',\n 'web_app_secure_storage_restore_key',\n 'web_app_secure_storage_save_key',\n ],\n 9.1: ['web_app_hide_keyboard'],\n 9.2: [\n 'web_app_send_notification',\n 'web_app_finish_refresh',\n ],\n};\n\n/**\n * @returns Version of the specified method parameter release. Returns `null`\n * if passed method or parameter are unknown.\n * @param method - method name\n * @param param - method parameter\n */\nexport function getReleaseVersion<M extends MethodNameWithVersionedParams>(\n method: M,\n param: MethodVersionedParams<M>,\n): Version | null;\n\n/**\n * @returns Version of the specified method release. Returns `null`\n * if passed method is unknown.\n * @param method - method name.\n */\nexport function getReleaseVersion(method: MethodName): Version | null;\nexport function getReleaseVersion(method: MethodName, param?: string): Version | null {\n const versions = Object.keys(releases) as (`${keyof typeof releases}`)[];\n return versions.find(version => {\n return releases[version].some(item => {\n if (param) {\n return typeof item === 'object'\n && item.method === method\n && item.param === param;\n }\n return item === method;\n });\n }) || null;\n}\n","import type { Version } from '@vbotma/types';\n\nfunction parts(a: Version): number[] {\n return a.split('.').map(Number);\n}\n\n/**\n * @param a - first version.\n * @param b - second version.\n * @returns\n * - `1` if the version \"a\" is greater than \"b\".\n * - `0` the version \"a\" is equal to \"b\".\n * - `-1` the version \"a\" is lower than \"b\".\n */\nexport function compareVersions(a: Version, b: Version): number {\n const aParts = parts(a);\n const bParts = parts(b);\n const len = Math.max(aParts.length, bParts.length);\n\n // Iterate over each part of versions and compare them. In case, part is\n // missing, assume its value is equal to 0.\n for (let i = 0; i < len; i += 1) {\n const aVal = aParts[i] || 0;\n const bVal = bParts[i] || 0;\n\n if (aVal === bVal) {\n continue;\n }\n return aVal > bVal ? 1 : -1;\n }\n return 0;\n}\n","import type { Version } from '@vbotma/types';\n\nimport { getReleaseVersion } from '@/methods/getReleaseVersion.js';\nimport type {\n MethodName,\n MethodNameWithVersionedParams,\n MethodVersionedParams,\n} from '@/methods/types/index.js';\nimport { compareVersions } from '@/utils/compareVersions.js';\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 MethodNameWithVersionedParams>(\n method: M,\n param: MethodVersionedParams<M>,\n inVersion: Version,\n): boolean;\n\n/**\n * Returns true in case, specified method is supported in a 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 const version = inVersion\n ? getReleaseVersion(\n method as MethodNameWithVersionedParams,\n paramOrVersion as MethodVersionedParams<MethodNameWithVersionedParams>,\n )\n : getReleaseVersion(method);\n return version\n ? compareVersions(version, inVersion || paramOrVersion) <= 0\n : false;\n}\n","import type { Version } from '@vbotma/types';\nimport { any, is, looseObject } from 'valibot';\n\nimport { MethodParameterUnsupportedError, MethodUnsupportedError } from '@/errors.js';\nimport { logger } from '@/globals.js';\nimport { type PostEventFn, postEvent } from '@/methods/postEvent.js';\nimport { supports } from '@/methods/supports.js';\nimport type {\n MethodName,\n MethodNameWithVersionedParams,\n MethodVersionedParams,\n} from '@/methods/types/index.js';\n\nexport type OnUnsupportedFn = (\n data: { version: Version } & (\n | { method: MethodName }\n | {\n [M in MethodNameWithVersionedParams]: {\n method: M;\n param: MethodVersionedParams<M>;\n };\n }[MethodNameWithVersionedParams]),\n) => void;\n\nexport type CreatePostEventMode = 'strict' | 'non-strict';\n\n/**\n * Creates a function that checks if the specified method and parameters are supported.\n *\n * If the method or parameters are unsupported, the `onUnsupported` function will be called.\n *\n * If `strict` or `non-strict` value was passed as the second argument, the function\n * will create its own `onUnsupported` function with behavior depending on the value passed.\n *\n * - Passing `strict` will make the function to throw a `MethodParameterUnsupportedError`\n * or a `MethodUnsupportedError` error.\n * - Passing `non-strict` will just warn you about something being unsupported.\n *\n * @param version - VBot Mini Apps version.\n * @param onUnsupportedOrMode - function or strict mode. Default: `strict`\n */\nexport function createPostEvent(\n version: Version,\n onUnsupportedOrMode: OnUnsupportedFn | CreatePostEventMode = 'strict',\n): PostEventFn {\n const onUnsupported: OnUnsupportedFn = typeof onUnsupportedOrMode === 'function'\n ? onUnsupportedOrMode\n : data => {\n const { method, version } = data;\n const error = 'param' in data\n ? new MethodParameterUnsupportedError(method, data.param, version)\n : new MethodUnsupportedError(method, version);\n\n if (onUnsupportedOrMode === 'strict') {\n throw error;\n }\n return logger().forceWarn(error.message);\n };\n\n return ((method: any, params: any) => {\n // Firstly, check if the method is supported.\n if (!supports(method, version)) {\n return onUnsupported({ version, method });\n }\n\n // Method could use parameters, which are supported only in specific versions of Mini Apps.\n // We are validating only those parameters, which are not backward compatible.\n if (\n method === 'web_app_set_header_color'\n && is(looseObject({ color: any() }), params)\n && !supports(method, 'color', version)\n ) {\n return onUnsupported({ version, method, param: 'color' });\n }\n\n return postEvent(method, params);\n }) as PostEventFn;\n}\n","import { BetterPromise } from 'better-promises';\nimport { taskEither as TE, function as fn } from 'fp-ts';\n\nimport { InvokeCustomMethodFailedError } from '@/errors.js';\nimport { captureSameReq } from '@/methods/captureSameReq.js';\nimport type { CustomMethodName, CustomMethodParams } from '@/methods/types/index.js';\n\nimport {\n request2Fp,\n type Request2Error,\n type Request2FpOptions,\n type Request2Options,\n} from './request2.js';\n\nexport type InvokeCustomMethodError = Request2Error | InvokeCustomMethodFailedError;\n\nexport type InvokeCustomMethodOptions = Omit<Request2Options<'custom_method_invoked'>, 'capture'>;\nexport type InvokeCustomMethodFn = typeof invokeCustomMethod;\n\nexport type InvokeCustomMethodFpOptions = Omit<Request2FpOptions<'custom_method_invoked'>, 'capture'>;\nexport type InvokeCustomMethodFpFn = typeof invokeCustomMethodFp;\n\n/**\n * Invokes known custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param requestId - request identifier.\n * @param options - additional options.\n */\nexport function invokeCustomMethodFp<M extends CustomMethodName>(\n method: M,\n params: CustomMethodParams<M>,\n requestId: string,\n options?: InvokeCustomMethodFpOptions,\n): TE.TaskEither<InvokeCustomMethodError, unknown>;\n\n/**\n * Invokes unknown custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param requestId - request identifier.\n * @param options - additional options.\n */\nexport function invokeCustomMethodFp(\n method: string,\n params: object,\n requestId: string,\n options?: InvokeCustomMethodFpOptions,\n): TE.TaskEither<Request2Error, unknown>;\n\nexport function invokeCustomMethodFp(\n method: string,\n params: object,\n requestId: string,\n options?: InvokeCustomMethodFpOptions,\n): TE.TaskEither<InvokeCustomMethodError, unknown> {\n return fn.pipe(\n request2Fp('web_app_invoke_custom_method', 'custom_method_invoked', {\n ...options || {},\n params: { method, params, req_id: requestId },\n capture: captureSameReq(requestId),\n }),\n TE.chain(({ result, error }) => {\n return error\n ? TE.left(new InvokeCustomMethodFailedError(error))\n : TE.right(result);\n }),\n );\n}\n\n/**\n * @see invokeCustomMethodFp\n */\nexport function invokeCustomMethod<M extends CustomMethodName>(\n method: M,\n params: CustomMethodParams<M>,\n requestId: string,\n options?: InvokeCustomMethodOptions,\n): BetterPromise<unknown>;\n\n/**\n * @see invokeCustomMethodFp\n */\nexport function invokeCustomMethod(\n method: string,\n params: object,\n requestId: string,\n options?: InvokeCustomMethodOptions,\n): BetterPromise<unknown>;\n\nexport function invokeCustomMethod(\n method: string,\n params: object,\n requestId: string,\n options?: InvokeCustomMethodOptions,\n): BetterPromise<unknown> {\n return BetterPromise.fn(() => {\n return fn.pipe(\n // @ts-expect-error TypeScript is unable to determine required override.\n invokeCustomMethodFp(method, params, requestId, options),\n TE.match(\n error => {\n throw error;\n },\n result => result,\n ),\n )();\n });\n}\n","import { signal } from '@vbotma/signals';\nimport {\n createCbCollector,\n throwifyAnyEither,\n type If,\n type IsNever,\n BetterTaskEither,\n} from '@vbotma/toolkit';\nimport {\n BetterPromise,\n type BetterPromiseOptions,\n type TimeoutError,\n} from 'better-promises';\nimport { either as E, taskEither as TE, function as fn } from 'fp-ts';\n\nimport { on } from '@/events/emitter.js';\nimport type { EventName, EventPayload } from '@/events/types/index.js';\nimport {\n postEventFp,\n type PostEventError,\n type PostEventFn,\n type PostEventFpFn,\n} from '@/methods/postEvent.js';\nimport type {\n MethodName,\n MethodNameWithOptionalParams,\n MethodNameWithoutParams,\n MethodNameWithRequiredParams,\n MethodParams,\n} from '@/methods/types/index.js';\n\ntype AnyEventName = EventName | EventName[];\n\nexport type RequestError = PostEventError | TimeoutError;\n\n/**\n * @example\n * { event: 'scan_qr_closed' }\n * @example\n * {\n * event: 'popup_closed',\n * payload: { button_id: 'ok' }\n * }\n */\nexport type RequestCaptureFnEventsPayload<E extends EventName[]> =\n E extends (infer U extends EventName)[]\n ? {\n [K in U]: If<\n IsNever<EventPayload<K>>,\n { event: K },\n { event: K; payload: EventPayload<K> }\n >\n }[U]\n : never;\n\nexport type RequestCaptureEventsFn<E extends EventName[]> = (\n payload: RequestCaptureFnEventsPayload<E>,\n) => boolean;\n\nexport type RequestCaptureEventFn<E extends EventName> = If<\n IsNever<EventPayload<E>>,\n () => boolean,\n (payload: EventPayload<E>) => boolean\n>;\n\nexport type RequestCaptureFn<E extends AnyEventName> = E extends EventName[]\n ? RequestCaptureEventsFn<E>\n : E extends EventName\n ? RequestCaptureEventFn<E>\n : never;\n\nexport interface RequestOptions<E extends AnyEventName> extends Omit<RequestFpOptions<E>, 'postEvent'> {\n /**\n * Custom function to call mini apps methods.\n */\n postEvent?: PostEventFn;\n}\n\nexport type RequestResult<E extends AnyEventName> =\n E extends (infer U extends EventName)[]\n ? U extends infer K extends EventName\n ? If<IsNever<EventPayload<K>>, undefined, EventPayload<K>>\n : never\n : E extends EventName\n ? If<IsNever<EventPayload<E>>, undefined, EventPayload<E>>\n : never;\n\nexport interface RequestFpOptions<E extends AnyEventName> extends Pick<\n BetterPromiseOptions,\n 'abortSignal' | 'timeout'\n> {\n /**\n * A function that should return true if the event should be captured.\n * The first compatible request will be captured if this property is omitted.\n */\n capture?: RequestCaptureFn<E>;\n /**\n * A custom function to call mini apps methods.\n */\n postEvent?: PostEventFpFn;\n}\n\nexport type RequestFn = typeof request;\nexport type RequestFpFn = typeof requestFp;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n * @deprecated To be removed in the next major update. Use `request2fp` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function requestFp<\n M extends MethodNameWithRequiredParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options: RequestFpOptions<E> & { params: MethodParams<M> },\n): TE.TaskEither<RequestError | AbortError, RequestResult<E>>;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n * @deprecated To be removed in the next major update. Use `request2fp` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function requestFp<\n M extends MethodNameWithOptionalParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options?: RequestFpOptions<E> & { params?: MethodParams<M> },\n): TE.TaskEither<RequestError | AbortError, RequestResult<E>>;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n * @deprecated To be removed in the next major update. Use `request2fp` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function requestFp<\n M extends MethodNameWithoutParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options?: RequestFpOptions<E>,\n): TE.TaskEither<RequestError | AbortError, RequestResult<E>>;\n\nexport function requestFp<\n M extends MethodName,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options: RequestFpOptions<E> & { params?: MethodParams<M> } = {},\n): TE.TaskEither<RequestError | AbortError, RequestResult<E>> {\n const {\n // If no capture function was passed, we capture the first compatible event.\n capture = () => true,\n postEvent = postEventFp,\n } = options;\n\n const result = signal<undefined | [RequestResult<E>]>();\n const [addCleanup, cleanup] = createCbCollector();\n // Iterate over all the tracked events and add a listener, checking if the event should be\n // captured.\n (Array.isArray(eventOrEvents) ? eventOrEvents : [eventOrEvents]).forEach(event => {\n // Each event listener waits for the event to occur.\n // Then, if the capture function was passed, we should check if the event should\n // be captured. If the function is omitted, we instantly capture the event.\n addCleanup(\n on(event, payload => {\n if (\n Array.isArray(eventOrEvents)\n ? (capture as RequestCaptureEventsFn<EventName[]>)({ event, payload })\n : (capture as RequestCaptureEventFn<EventName>)(payload)\n ) {\n result.set([payload as RequestResult<E>]);\n }\n }),\n );\n });\n const withCleanup = <T>(value: T): T => {\n cleanup();\n return value;\n };\n\n return fn.pipe(\n async () => postEvent(method as any, (options as any).params),\n TE.chainW(() => {\n return BetterTaskEither<AbortError, RequestResult<E>>((resolve, _, context) => {\n // When creating this BetterTaskEither, we could already have a value stored in\n // the result signal. For example, when tracked events were generated via emitEvent in\n // mockVBotEnv.onEvent.\n const data = result();\n if (data) {\n return resolve(data[0]);\n }\n\n const listener = (data: [RequestResult<E>] | undefined) => {\n if (data) {\n resolve(data[0]);\n }\n };\n const unsub = () => {\n result.unsub(listener);\n };\n result.sub(listener);\n context.on('finalized', unsub);\n }, options);\n }),\n TE.mapBoth(withCleanup, withCleanup),\n );\n}\n\n/**\n * @see requestFp\n * @deprecated To be removed in the next major update. Use `request2` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function request<M extends MethodNameWithRequiredParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options: RequestOptions<E> & { params: MethodParams<M> },\n): BetterPromise<RequestResult<E>>;\n\n/**\n * @see requestFp\n * @deprecated To be removed in the next major update. Use `request2` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function request<M extends MethodNameWithOptionalParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: RequestOptions<E> & { params?: MethodParams<M> },\n): BetterPromise<RequestResult<E>>;\n\n/**\n * @see requestFp\n * @deprecated To be removed in the next major update. Use `request2` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function request<M extends MethodNameWithoutParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: RequestOptions<E>,\n): BetterPromise<RequestResult<E>>;\n\nexport function request<M extends MethodName, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: RequestOptions<E> & { params?: MethodParams<M> },\n): BetterPromise<RequestResult<E>> {\n const { postEvent } = options || {};\n\n return throwifyAnyEither(\n // @ts-expect-error TypeScript will not be able to handle our overrides here.\n requestFp(method, eventOrEvents, {\n ...options,\n postEvent: postEvent\n ? (...args: any[]) => {\n try {\n // @ts-expect-error TypeScript will not be able to handle our overrides here.\n postEvent(...args);\n return E.right(undefined);\n } catch (e) {\n return E.left(e);\n }\n }\n : postEventFp,\n }),\n );\n}\n","/**\n * Applies polyfills required for stable work of the package:\n * - `Object.hasOwn` - used by `valibot`\n */\nexport function applyPolyfills(): void {\n if (!Object.hasOwn) {\n Object.hasOwn = function(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n };\n }\n}\n","import { throwifyFpFn } from '@vbotma/toolkit';\nimport { either as E } from 'fp-ts';\n\nexport type DecodeBase64UrlError = DOMException;\n\n/**\n * Decodes a base-64-url ASCII string.\n * @param value - the value to decode.\n * @see Learn more about base64url:\n * https://herongyang.com/Encoding/Base64URL-Encoding-Algorithm.html\n * @see Source:\n * https://developer.mozilla.org/ru/docs/Glossary/Base64#solution_1_–_escaping_the_string_before_encoding_it\n */\nexport function decodeBase64UrlFp(value: string): E.Either<DecodeBase64UrlError, string> {\n return E.tryCatch(() => {\n return decodeURIComponent(\n atob(\n value\n .replace(/-/g, '+')\n .replace(/_/g, '/'),\n )\n .split('')\n .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))\n .join(''),\n );\n }, e => e as DOMException);\n}\n\n/**\n * @see decodeBase64UrlFp\n */\nexport const decodeBase64Url = throwifyFpFn(decodeBase64UrlFp);\n\n/**\n * Creates a base-64-url encoded ASCII string from the passed value.\n * @param value - the value to encode.\n * @see Learn more about base64url:\n * https://herongyang.com/Encoding/Base64URL-Encoding-Algorithm.html\n * @see Source:\n * https://developer.mozilla.org/ru/docs/Glossary/Base64#solution_1_–_escaping_the_string_before_encoding_it\n */\nexport function encodeBase64Url(value: string): string {\n // first we use encodeURIComponent to get percent-encoded UTF-8,\n // then we convert the percent encodings into raw bytes which\n // can be fed into btoa.\n return btoa(\n encodeURIComponent(value).replace(/%([0-9A-F]{2})/g, (_, p1) => {\n return String.fromCharCode(parseInt(`0x${p1}`));\n }),\n )\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n}\n","import { throwifyFpFn, throwifyAnyEither } from '@vbotma/toolkit';\nimport { either as E, function as fn, json as J } from 'fp-ts';\n\nimport { encodeBase64Url, type DecodeBase64UrlError, decodeBase64UrlFp } from '@/base64-url.js';\n\n/**\n * Creates a safe start parameter value. If the value is not a string, the\n * function applies JSON.stringify to it, so make sure you are not passing an\n * object with circular references.\n *\n * @param value - value to create start parameter from.\n * @see Learn more about start parameter:\n * https://docs.vbot-mini-apps.com/platform/start-parameter\n */\nexport function createStartParamFp(value: unknown): E.Either<Error, string> {\n const b64 = encodeBase64Url(typeof value === 'string' ? value : JSON.stringify(value));\n return b64.length > 512\n ? E.left(new Error('Value is too long for start parameter'))\n : E.right(b64);\n}\n\n/**\n * @see createStartParamFp\n */\nexport const createStartParam = throwifyFpFn(createStartParamFp);\n\n/**\n * @see decodeStartParamFp\n */\nexport function decodeStartParam<T>(value: string, parse: (value: string) => T): T;\n/**\n * @see decodeStartParamFp\n */\nexport function decodeStartParam(value: string, as: 'json'): J.Json;\n/**\n * @see decodeStartParamFp\n */\nexport function decodeStartParam(value: string): string;\nexport function decodeStartParam<T>(\n value: string,\n arg2?: 'json' | ((value: string) => T),\n): string | unknown | T {\n return throwifyAnyEither(\n decodeStartParamFp(\n value,\n // @ts-expect-error TypeScript is unable to detect a correct override.\n typeof arg2 === 'function'\n ? (value: string) => E.tryCatch(() => arg2(value), e => e)\n : arg2,\n ),\n );\n}\n\n/**\n * Decodes a start parameter using a custom parser.\n * @param value - a start parameter value.\n * @param parse - a custom value parser.\n */\nexport function decodeStartParamFp<L, R>(\n value: string,\n parse: (value: string) => E.Either<L, R>,\n): E.Either<L | DecodeBase64UrlError, R>;\n/**\n * Decodes a start parameter assuming that the result is a JSON value.\n * @param value - a start parameter value.\n * @param as - result kind.\n */\nexport function decodeStartParamFp(\n value: string,\n as: 'json',\n): E.Either<SyntaxError | DecodeBase64UrlError, J.Json>;\n/**\n * Decodes a start parameter and returns its decoded representation.\n * @param value - a value to decode.\n */\nexport function decodeStartParamFp(value: string): E.Either<DecodeBase64UrlError, string>;\nexport function decodeStartParamFp<L, R>(\n value: string,\n arg2?: 'json' | ((value: string) => E.Either<L, R>),\n): E.Either<DecodeBase64UrlError | SyntaxError | L, R | string | J.Json> {\n return fn.pipe(\n decodeBase64UrlFp(value),\n E.chain<DecodeBase64UrlError | SyntaxError | L, string, R | string | J.Json>(decoded => {\n if (!arg2) {\n return E.right(decoded);\n }\n if (typeof arg2 === 'function') {\n return arg2(decoded);\n }\n return J.parse(decoded) as E.Either<SyntaxError, J.Json>;\n }),\n );\n}\n\n/**\n * @returns True if the passed value is safe to be used to create a start parameter value from it.\n * If true is returned, the value can be safely passed to the `createStartParam` function.\n * @param value - value to check.\n * @see createStartParam\n */\nexport function isSafeToCreateStartParam(value: string): boolean {\n return encodeBase64Url(value).length <= 512;\n}\n"],"names":["hasWebviewProxy","value","is","looseObject","fn","isIframe","MethodUnsupportedError","errorClass","method","version","MethodParameterUnsupportedError","param","LaunchParamsRetrieveError","errorClassWithData","errors","source","error","InvalidLaunchParamsError","launchParams","cause","UnknownEnvError","InvokeCustomMethodFailedError","SESSION_STORAGE_KEY","retrieveLpFromUrl","urlString","retrieveLaunchParamsFp","retrieveRawLaunchParamsFp","E","parseLaunchParamsQueryFp","retrieveLaunchParams","throwifyFpFn","retrieveRawInitDataFp","raw","v","O","retrieveRawInitData","err","retrieve","navigationEntry","getStorageValue","maybeError","setStorageValue","retrieveRawLaunchParams","createEmitter","onFirst","onEmpty","eventToHandlersMap","emitter","mitt","off","event","handler","once","handlersMap","handlers","index","item","prevSize","cleanup","internalHandler","args","emitEvent","eventType","eventData","_debug","signal","_targetOrigin","onEventReceived","logger","debug","computed","setDebug","on","targetOrigin","setTargetOrigin","origin","postMessageImpl","createLogger","resetGlobals","offAll","s","defineFnComposer","obj","propertyName","initialFn","assignedFunctions","property","callAssignedFunctions","unwrappableCallAssignedFunctions","poolSize","defineStaticProperty","defineProxiedProperty","defineMergeableProperty","prop","objKey","objValue","get","set","transformers","string","nullish","optional","unknown","number","boolean","themeParams","windowMessageListener","message","parse","pipeJsonToSchema","miniAppsMessage","schema","data","emit","wnd","path","cursor","receiveEventOwner","receiveEvent","postMessage","postEvent","fpFn","postEventFp","w","request2Fp","eventOrEvents","options","capture","result","addCleanup","createCbCollector","payload","isEventsArray","withCleanup","TE","BetterTaskEither","resolve","_","context","listener","unsub","request2","throwifyAnyEither","e","isVBMA","type","monad","isVBMAFp","BetterPromise","hasProxy","timeout","TimeoutError","mockVBotEnv","onEvent","resetPostMessage","launchParamsQuery","serializeLaunchParamsQuery","parseLaunchParamsQuery","original","next","proxy","postEventDefaulted","captureSameReq","reqId","req_id","releases","getReleaseVersion","parts","a","compareVersions","b","aParts","bParts","len","i","aVal","bVal","supports","paramOrVersion","inVersion","createPostEvent","onUnsupportedOrMode","onUnsupported","params","any","invokeCustomMethodFp","requestId","invokeCustomMethod","requestFp","request","applyPolyfills","decodeBase64UrlFp","c","decodeBase64Url","encodeBase64Url","p1","createStartParamFp","b64","createStartParam","decodeStartParam","arg2","decodeStartParamFp","decoded","J","isSafeToCreateStartParam"],"mappings":";;;;;;;;;;AAOO,SAASA,GAAmBC,GAIjC;AACA,SAAOC;AAAA,IACLC,EAAY,EAAE,kBAAkBA,EAAY,EAAE,WAAWC,EAAA,EAAG,CAAG,GAAG;AAAA,IAClEH;AAAA,EAAA;AAEJ;ACZO,SAASI,KAAoB;AAClC,MAAI;AACF,WAAO,OAAO,SAAS,OAAO;AAAA,EAChC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;ACPO,MAAMC,YAA+C,gBAAAC,EAE1D,0BAA0B,CAACC,GAAQC,MAAY;AAAA,EAC/C,WAAWD,CAAM,yCAAyCC,CAAO;AACnE,CAAC,GAAE;AACH;AAEO,MAAMC,YAAwD,gBAAAH,EAEnE,mCAAmC,CAACC,GAAQG,GAAOF,MAAY;AAAA,EAC/D,cAAcE,CAAK,SAASH,CAAM,gDAAgDC,CAAO;AAC3F,CAAC,GAAE;AACH;AAEO,MAAMG,YAAkD,gBAAAC;AAAA,EAI7D;AAAA,EACA,CAAAC,OAAW,EAAE,QAAAA;EACb,CAAAA,MAAU;AAAA,IACR;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,M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AAmBxK,EAAasK,EAAkB;AAcxD,SAASG,GACdtM,GACAuM,GACsB;AACtB,SAAO1D;AAAA,IACL2D;AAAA,MACExM;AAAA;AAAA,MAEA,OAAOuM,KAAS,aACZ,CAACvM,MAAkB0B,EAAE,SAAS,MAAM6K,EAAKvM,CAAK,GAAG,CAAA8I,MAAKA,CAAC,IACvDyD;AAAA,IAAA;AAAA,EACN;AAEJ;AAyBO,SAASC,GACdxM,GACAuM,GACuE;AACvE,SAAOpM,EAAG;AAAA,IACR2L,GAAkB9L,CAAK;AAAA,IACvB0B,EAAE,MAA2E,CAAA+K,MACtEF,IAGD,OAAOA,KAAS,aACXA,EAAKE,CAAO,IAEdC,GAAE,MAAMD,CAAO,IALb/K,EAAE,MAAM+K,CAAO,CAMzB;AAAA,EAAA;AAEL;AAQO,SAASE,GAAyB3M,GAAwB;AAC/D,SAAOiM,GAAgBjM,CAAK,EAAE,UAAU;AAC1C;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vbotma/bridge",
3
- "version": "2.2.4",
3
+ "version": "2.2.6",
4
4
  "description": "TypeScript package to provide communication layer between Mini App and VBot application.",
5
5
  "keywords": [
6
6
  "vbot-mini-apps",
@@ -30,14 +30,14 @@
30
30
  "fp-ts": "^2.16.11",
31
31
  "mitt": "^3.0.1",
32
32
  "valibot": "^1.1.0",
33
- "@vbotma/transformers": "^1.1.3",
34
- "@vbotma/signals": "^1.0.1",
35
33
  "@vbotma/toolkit": "^1.0.4",
36
- "@vbotma/types": "^1.0.2"
34
+ "@vbotma/signals": "^1.0.1",
35
+ "@vbotma/types": "^1.0.2",
36
+ "@vbotma/transformers": "^1.1.3"
37
37
  },
38
38
  "devDependencies": {
39
- "tsconfig": "0.0.2",
40
- "test-utils": "0.0.1"
39
+ "test-utils": "0.0.1",
40
+ "tsconfig": "0.0.2"
41
41
  },
42
42
  "publishConfig": {
43
43
  "access": "public"