nuxt-miniapp-telegram-max 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +246 -2
- package/dist/module.d.mts +41 -0
- package/dist/module.json +12 -0
- package/dist/module.mjs +99 -0
- package/dist/runtime/client/adapters/max.d.ts +2 -0
- package/dist/runtime/client/adapters/max.js +62 -0
- package/dist/runtime/client/adapters/shared.d.ts +14 -0
- package/dist/runtime/client/adapters/shared.js +48 -0
- package/dist/runtime/client/adapters/telegram.d.ts +2 -0
- package/dist/runtime/client/adapters/telegram.js +85 -0
- package/dist/runtime/client/adapters/web.d.ts +6 -0
- package/dist/runtime/client/adapters/web.js +35 -0
- package/dist/runtime/client/backButton.d.ts +18 -0
- package/dist/runtime/client/backButton.js +37 -0
- package/dist/runtime/client/launch.d.ts +47 -0
- package/dist/runtime/client/launch.js +115 -0
- package/dist/runtime/client/sdk.d.ts +20 -0
- package/dist/runtime/client/sdk.js +62 -0
- package/dist/runtime/client/state.d.ts +19 -0
- package/dist/runtime/client/state.js +30 -0
- package/dist/runtime/client/storage.d.ts +9 -0
- package/dist/runtime/client/storage.js +20 -0
- package/dist/runtime/composables/useMiniApp.d.ts +109 -0
- package/dist/runtime/composables/useMiniApp.js +37 -0
- package/dist/runtime/composables/useMiniAppBackButton.d.ts +12 -0
- package/dist/runtime/composables/useMiniAppBackButton.js +24 -0
- package/dist/runtime/composables/useMiniAppClosingConfirmation.d.ts +8 -0
- package/dist/runtime/composables/useMiniAppClosingConfirmation.js +19 -0
- package/dist/runtime/composables/useMiniAppHaptics.d.ts +8 -0
- package/dist/runtime/composables/useMiniAppHaptics.js +11 -0
- package/dist/runtime/plugin.client.d.ts +3 -0
- package/dist/runtime/plugin.client.js +73 -0
- package/dist/runtime/server/tsconfig.json +3 -0
- package/dist/runtime/server/utils/initData.d.ts +21 -0
- package/dist/runtime/server/utils/initData.js +21 -0
- package/dist/runtime/shared/initData.d.ts +20 -0
- package/dist/runtime/shared/initData.js +53 -0
- package/dist/runtime/shared/validate.d.ts +28 -0
- package/dist/runtime/shared/validate.js +41 -0
- package/dist/runtime/types.d.ts +238 -0
- package/dist/runtime/types.js +0 -0
- package/dist/types.d.mts +9 -0
- package/package.json +75 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Timofey
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,247 @@
|
|
|
1
|
-
#
|
|
1
|
+
# nuxt-miniapp-telegram-max
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Один Nuxt-проект — мини-приложение сразу в **Telegram** и в **MAX**, и обычный сайт
|
|
4
|
+
в придачу. Один API для обоих мессенджеров, безопасный для SSR, и проверка
|
|
5
|
+
initData на сервере.
|
|
6
|
+
|
|
7
|
+
*English below.*
|
|
8
|
+
|
|
9
|
+
## Зачем
|
|
10
|
+
|
|
11
|
+
Бот нужен в двух мессенджерах, а мини-приложения у них разные: свои скрипты
|
|
12
|
+
(`telegram-web-app.js` и `max-web-app.js`), свои глобальные объекты, параметры
|
|
13
|
+
запуска, модель ответов (колбэки у Telegram, промисы у MAX) и набор возможностей.
|
|
14
|
+
Писать приложение дважды не хочется, а условия «если Telegram, иначе если MAX»
|
|
15
|
+
расползаются по всему коду.
|
|
16
|
+
|
|
17
|
+
Модуль даёт один `useMiniApp()`, который одинаково работает в Telegram, в MAX и в
|
|
18
|
+
браузере. Чего у клиента нет — не падает, а честно отвечает `null` или
|
|
19
|
+
`'unsupported'`, и приложение показывает своё.
|
|
20
|
+
|
|
21
|
+
## Что решено за вас
|
|
22
|
+
|
|
23
|
+
То, на что натыкаешься в продакшене, а не в документации:
|
|
24
|
+
|
|
25
|
+
- **Мигание при SSR.** Сервер всегда рисует сайт. Ещё до первой отрисовки на
|
|
26
|
+
`<html>` встаёт класс `mini-app-telegram` или `mini-app-max` — разметка «только
|
|
27
|
+
для мессенджера» показывается без мигания и без ошибок гидрации.
|
|
28
|
+
- **Обрезанная initData.** Telegram на Android и десктопе отдаёт в
|
|
29
|
+
`tgWebApp.initData` огрызок вида `query_id`; модуль берёт данные из хеша запуска.
|
|
30
|
+
- **Поздний хеш на iOS.** Telegram на iOS иногда ставит параметры запуска уже после
|
|
31
|
+
загрузки страницы — модуль их дожидается.
|
|
32
|
+
- **Перезагрузка внутри приложения.** Роутер стирает хеш при первой навигации; после
|
|
33
|
+
F5 на внутренней странице мессенджер и initData не теряются.
|
|
34
|
+
- **Start-параметр один раз.** `?startapp=…` срабатывает один раз за запуск —
|
|
35
|
+
перезагрузка не уводит человека обратно на страницу ссылки.
|
|
36
|
+
- **Кнопка «Назад» как стек.** Модалка поверх страницы забирает кнопку и
|
|
37
|
+
возвращает при закрытии — без «назад», выкидывающего из приложения.
|
|
38
|
+
- **SDK не пришёл.** Нет сети или недоступен CDN — приложение работает как сайт, а
|
|
39
|
+
initData всё равно подписывает запросы.
|
|
40
|
+
- **MAX в браузере** отклоняет промис на каждое касание с вибрацией — модуль это
|
|
41
|
+
глушит, в трекер ошибок не летит.
|
|
42
|
+
- **Проверка подписи на сервере** для обоих мессенджеров: схема у MAX та же, что у
|
|
43
|
+
Telegram. Web Crypto — Node, Bun, Deno, edge.
|
|
44
|
+
|
|
45
|
+
Это тонкий слой над официальными скриптами, а не своя реализация их протоколов.
|
|
46
|
+
Только Telegram и все его возможности — смотрите
|
|
47
|
+
[tma.js](https://github.com/Telegram-Mini-Apps/tma.js).
|
|
48
|
+
|
|
49
|
+
## Быстрый старт
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
npx nuxt module add nuxt-miniapp-telegram-max
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Больше ничего не нужно: откройте приложение кнопкой меню бота или ссылкой
|
|
56
|
+
`startapp` — в Telegram и в MAX.
|
|
57
|
+
|
|
58
|
+
```vue
|
|
59
|
+
<template>
|
|
60
|
+
<!-- Только после гидрации: сервер рисует сайт. -->
|
|
61
|
+
<ClientOnly>
|
|
62
|
+
<p v-if="miniApp.launch.value?.user">
|
|
63
|
+
Привет, {{ miniApp.launch.value.user.first_name }}
|
|
64
|
+
</p>
|
|
65
|
+
</ClientOnly>
|
|
66
|
+
<button @click="remove">Удалить</button>
|
|
67
|
+
</template>
|
|
68
|
+
|
|
69
|
+
<script setup lang="ts">
|
|
70
|
+
const miniApp = useMiniApp()
|
|
71
|
+
const haptics = useMiniAppHaptics()
|
|
72
|
+
|
|
73
|
+
async function remove() {
|
|
74
|
+
// Родной диалог там, где он есть; null — нарисуйте свой.
|
|
75
|
+
const confirmed = await (miniApp.sdk.showConfirm('Удалить?') ?? myDialog('Удалить?'))
|
|
76
|
+
if (confirmed) haptics.notification('success')
|
|
77
|
+
}
|
|
78
|
+
</script>
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
// server/api/me.get.ts — токены: NUXT_MINI_APPS_TELEGRAM_BOT_TOKEN, NUXT_MINI_APPS_MAX_BOT_TOKEN
|
|
83
|
+
export default defineEventHandler(async (event) => {
|
|
84
|
+
const { client, data } = await requireMiniAppInitData(event)
|
|
85
|
+
return { client, userId: data.user?.id }
|
|
86
|
+
})
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
// Клиент: подпись запроса тем же заголовком, что читает сервер.
|
|
91
|
+
await $fetch('/api/me', { headers: useMiniApp().initDataHeaders() })
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Полный справочник — ниже, по-английски.
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## English
|
|
99
|
+
|
|
100
|
+
One Nuxt project as a mini app in both **Telegram** and **MAX**, and the plain
|
|
101
|
+
website too. One SSR-safe API for both messengers, plus init data validation on
|
|
102
|
+
the server.
|
|
103
|
+
|
|
104
|
+
It is a thin layer over the official scripts
|
|
105
|
+
([telegram-web-app.js](https://core.telegram.org/bots/webapps),
|
|
106
|
+
[max-web-app.js](https://dev.max.ru/docs/webapps/bridge)): it loads the
|
|
107
|
+
messenger's script only inside that messenger and works around what real
|
|
108
|
+
clients do — init data cut short on Android and desktop, the launch hash set
|
|
109
|
+
late on iOS, the hash dropped by the router, reloads deep inside the app, MAX
|
|
110
|
+
rejecting a promise on every haptic tap in a browser, an SDK that never comes.
|
|
111
|
+
For a Telegram-only app with every feature of the platform, see
|
|
112
|
+
[tma.js](https://github.com/Telegram-Mini-Apps/tma.js).
|
|
113
|
+
|
|
114
|
+
### Setup
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
npx nuxt module add nuxt-miniapp-telegram-max
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Server-rendered markup
|
|
121
|
+
|
|
122
|
+
The server cannot know the client, so it always renders the website. Don't put
|
|
123
|
+
`client`, `launch` or `colorScheme` into server-rendered markup — Vue would
|
|
124
|
+
report a hydration mismatch. Instead:
|
|
125
|
+
|
|
126
|
+
```css
|
|
127
|
+
/* Shown before the first paint, no mismatch. */
|
|
128
|
+
html:not(.mini-app-telegram):not(.mini-app-max) .in-messenger { display: none; }
|
|
129
|
+
html.mini-app-max .not-in-max { display: none; }
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
or wrap it in `<ClientOnly>`, or read the state in `onMounted`. Code — plugins,
|
|
133
|
+
middleware, handlers — reads it anywhere.
|
|
134
|
+
|
|
135
|
+
### `useMiniApp()`
|
|
136
|
+
|
|
137
|
+
| | |
|
|
138
|
+
| --- | --- |
|
|
139
|
+
| `client` | `Ref<'telegram' \| 'max' \| 'web'>` — where the app runs. On the server: `'web'`. |
|
|
140
|
+
| `isMiniApp` | `ComputedRef<boolean>` |
|
|
141
|
+
| `colorScheme` | `Ref<'light' \| 'dark'>` — Telegram's theme; the system scheme in MAX and on the website. |
|
|
142
|
+
| `initData` | `Ref<string>` — raw init data for your API. |
|
|
143
|
+
| `launch` | `Ref<MiniAppInitData \| null>` — parsed: `user`, `startParam`, `chat`, `authDate`… Not verified: trust what your server checked. |
|
|
144
|
+
| `startParam` | `Ref<string \| null>` — the start parameter to act on. Set once per launch, so a reload doesn't send the user back to the link's page. |
|
|
145
|
+
| `sdkMissing` | `Ref<boolean>` — opened in a messenger whose SDK did not load (no network). The app runs as the website. |
|
|
146
|
+
| `sdk` | The client's SDK: `openLink`, `openInternalLink`, `close`, `showPopup`, `showConfirm`, `downloadFile`, `setClosingConfirmation`, `setVerticalSwipes`… Narrow by `sdk.client` for `sdk.raw` and client-only methods. |
|
|
147
|
+
| `initDataHeaders()` | `{ 'X-Telegram-Init-Data': … }` or `{ 'X-Max-Init-Data': … }` for `$fetch`. |
|
|
148
|
+
| `ready()` | Hides the messenger's loader. Called for you unless `autoReady: false`. |
|
|
149
|
+
|
|
150
|
+
`useMiniApp()` reads module state, not the Nuxt instance: call it anywhere —
|
|
151
|
+
in setup, in route middleware, in a handler after `await`. The module's plugin
|
|
152
|
+
runs before your plugins and before the first navigation, so they all see the
|
|
153
|
+
final state.
|
|
154
|
+
|
|
155
|
+
### Composables
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
// The messenger's back button while mounted. Layers stack: a modal takes the
|
|
159
|
+
// button over the page and gives it back on close.
|
|
160
|
+
useMiniAppBackButton(() => router.back())
|
|
161
|
+
useMiniAppBackButton(close, { enabled: isOpen })
|
|
162
|
+
|
|
163
|
+
// Ask before closing while true; stays on while any component asks.
|
|
164
|
+
useMiniAppClosingConfirmation(hasUnsavedChanges)
|
|
165
|
+
|
|
166
|
+
// Does nothing on the website.
|
|
167
|
+
useMiniAppHaptics().impact('light')
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### Start parameter
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
// middleware/start-param.global.ts
|
|
174
|
+
export default defineNuxtRouteMiddleware((to) => {
|
|
175
|
+
const param = useMiniApp().startParam.value
|
|
176
|
+
if (to.path === '/' && param?.startsWith('event_')) {
|
|
177
|
+
return navigateTo(`/events/${param.slice(6)}`)
|
|
178
|
+
}
|
|
179
|
+
})
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
Set `autoReady: false` and call `useMiniApp().ready()` after such a redirect,
|
|
183
|
+
so the messenger reveals the app on the target page, not on the home page.
|
|
184
|
+
|
|
185
|
+
### Server
|
|
186
|
+
|
|
187
|
+
`requireMiniAppInitData(event)` reads the header `initDataHeaders()` sends,
|
|
188
|
+
checks the signature and `auth_date` (a day by default: `{ maxAge }`), and
|
|
189
|
+
answers 401 with `data.reason` — `missing`, `malformed`, `signature`,
|
|
190
|
+
`expired`. Init data with a repeated key is refused as `malformed`.
|
|
191
|
+
`validateInitData(raw, botToken)` and `parseInitData(raw)` are there for
|
|
192
|
+
anything else.
|
|
193
|
+
|
|
194
|
+
### Options
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
export default defineNuxtConfig({
|
|
198
|
+
miniApps: {
|
|
199
|
+
telegram: { sdkUrl: 'https://telegram.org/js/telegram-web-app.js' },
|
|
200
|
+
max: { sdkUrl: 'https://st.max.ru/js/max-web-app.js' },
|
|
201
|
+
sdkTimeout: 5000,
|
|
202
|
+
earlyDetect: true,
|
|
203
|
+
autoReady: true,
|
|
204
|
+
cleanLaunchHash: true,
|
|
205
|
+
expand: false,
|
|
206
|
+
verticalSwipes: true,
|
|
207
|
+
colorSchemeAttribute: '',
|
|
208
|
+
initDataHeaders: { telegram: 'X-Telegram-Init-Data', max: 'X-Max-Init-Data' },
|
|
209
|
+
},
|
|
210
|
+
})
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
| Option | |
|
|
214
|
+
| --- | --- |
|
|
215
|
+
| `telegram.sdkUrl` | Serve your own copy where telegram.org is slow to reach (Telegram's webview ignores the device's proxy). |
|
|
216
|
+
| `sdkTimeout` | Inside a messenger the app waits for its SDK before hydrating — up to this long when the network is bad. The website never waits. |
|
|
217
|
+
| `earlyDetect` | The inline `<head>` script behind the `mini-app-*` classes. Turn off under a CSP without inline scripts; the plugin still detects the client. |
|
|
218
|
+
| `autoReady` | Call the messenger's `ready()` once the app is hydrated. |
|
|
219
|
+
| `cleanLaunchHash` | Remove `#tgWebAppData=…` from the address bar and the route once mounted. Until then it is in `location`: analytics that send the first page view earlier should drop the hash. |
|
|
220
|
+
| `expand` | Open Telegram mini apps at full height. |
|
|
221
|
+
| `verticalSwipes` | `false` stops swipe-down-to-close — for pages with their own vertical gestures. |
|
|
222
|
+
| `colorSchemeAttribute` | E.g. `'data-color-scheme'`: the scheme as an attribute on `<html>`, restored before the first paint in a mini app. Build-time. |
|
|
223
|
+
|
|
224
|
+
Telegram's script sets its theme as CSS variables (`--tg-theme-bg-color`…)
|
|
225
|
+
itself. MAX's has no theme at all — no `colorScheme`, no `themeParams`, no theme
|
|
226
|
+
event — the module follows `prefers-color-scheme` there.
|
|
227
|
+
|
|
228
|
+
### Storage
|
|
229
|
+
|
|
230
|
+
sessionStorage keeps the launch hash and init data for the tab, so a reload
|
|
231
|
+
inside the app still signs requests; init data is a credential your server
|
|
232
|
+
accepts for `maxAge`, the same as Telegram's own SDK keeps it. localStorage
|
|
233
|
+
keeps only the last color scheme. The module makes no network requests besides
|
|
234
|
+
loading the messenger's script.
|
|
235
|
+
|
|
236
|
+
### Development
|
|
237
|
+
|
|
238
|
+
```bash
|
|
239
|
+
pnpm install
|
|
240
|
+
pnpm dev # playground
|
|
241
|
+
pnpm test # unit + end-to-end (Chromium: pnpm exec playwright-core install chromium)
|
|
242
|
+
pnpm lint
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
## License
|
|
246
|
+
|
|
247
|
+
[MIT](./LICENSE)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import * as _nuxt_schema from '@nuxt/schema';
|
|
2
|
+
export * from '../dist/runtime/types.js';
|
|
3
|
+
export { InitDataFailure, InitDataValidation, ValidateInitDataOptions } from '../dist/runtime/shared/validate.js';
|
|
4
|
+
export { MiniAppRequest, RequireMiniAppInitDataOptions } from '../dist/runtime/server/utils/initData.js';
|
|
5
|
+
|
|
6
|
+
interface ModuleOptions {
|
|
7
|
+
telegram: {
|
|
8
|
+
/** telegram-web-app.js. Point it at your own copy where telegram.org is slow to reach. */
|
|
9
|
+
sdkUrl: string;
|
|
10
|
+
};
|
|
11
|
+
max: {
|
|
12
|
+
sdkUrl: string;
|
|
13
|
+
};
|
|
14
|
+
/** How long to wait for the SDK script, ms. */
|
|
15
|
+
sdkTimeout: number;
|
|
16
|
+
/**
|
|
17
|
+
* An inline script in <head> marks <html> with `mini-app-telegram` /
|
|
18
|
+
* `mini-app-max` before the first paint and keeps the launch hash. Turn off
|
|
19
|
+
* under a CSP without inline scripts — detection then happens in the plugin.
|
|
20
|
+
*/
|
|
21
|
+
earlyDetect: boolean;
|
|
22
|
+
/** Call the messenger's `ready()` once the app is hydrated. Turn off to call `useMiniApp().ready()` yourself. */
|
|
23
|
+
autoReady: boolean;
|
|
24
|
+
/** Remove launch parameters from the address bar once read. */
|
|
25
|
+
cleanLaunchHash: boolean;
|
|
26
|
+
/** Open Telegram mini apps at full height. */
|
|
27
|
+
expand: boolean;
|
|
28
|
+
/** Swipe down closes the app. Turn off when the page has its own vertical gestures. */
|
|
29
|
+
verticalSwipes: boolean;
|
|
30
|
+
/** Set the color scheme as this attribute on <html> (e.g. `data-color-scheme`); empty to leave <html> alone. */
|
|
31
|
+
colorSchemeAttribute: string;
|
|
32
|
+
/** Header names for init data, shared by `useMiniApp().initDataHeaders()` and `requireMiniAppInitData()`. */
|
|
33
|
+
initDataHeaders: {
|
|
34
|
+
telegram: string;
|
|
35
|
+
max: string;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
|
|
39
|
+
|
|
40
|
+
export { _default as default };
|
|
41
|
+
export type { ModuleOptions };
|
package/dist/module.json
ADDED
package/dist/module.mjs
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { defineNuxtModule, createResolver, addPlugin, addImports, addServerImports } from '@nuxt/kit';
|
|
2
|
+
import { defu } from 'defu';
|
|
3
|
+
|
|
4
|
+
const STORAGE_PREFIX = "nuxt-miniapp:";
|
|
5
|
+
function earlyDetect(options) {
|
|
6
|
+
try {
|
|
7
|
+
const root = document.documentElement;
|
|
8
|
+
const capture = () => {
|
|
9
|
+
const hash = location.hash.slice(1);
|
|
10
|
+
const client2 = /(?:^|&)tgWebApp(?:Data|Platform)=/.test(hash) ? "telegram" : /(?:^|&)WebAppData=/.test(hash) ? "max" : null;
|
|
11
|
+
if (client2) {
|
|
12
|
+
sessionStorage.setItem(`${options.prefix}client`, client2);
|
|
13
|
+
sessionStorage.setItem(`${options.prefix}launch-hash`, hash);
|
|
14
|
+
}
|
|
15
|
+
return client2 || sessionStorage.getItem(`${options.prefix}client`);
|
|
16
|
+
};
|
|
17
|
+
const client = capture();
|
|
18
|
+
if (client !== "telegram" && client !== "max") {
|
|
19
|
+
addEventListener("hashchange", () => {
|
|
20
|
+
const late = capture();
|
|
21
|
+
if (late === "telegram" || late === "max") root.classList.add(options.classPrefix + late);
|
|
22
|
+
});
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
root.classList.add(options.classPrefix + client);
|
|
26
|
+
if (options.attribute) {
|
|
27
|
+
const scheme = localStorage.getItem(`${options.prefix}color-scheme`);
|
|
28
|
+
if (scheme === "light" || scheme === "dark") root.setAttribute(options.attribute, scheme);
|
|
29
|
+
}
|
|
30
|
+
} catch {
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const CLASS_PREFIX = "mini-app-";
|
|
36
|
+
const module$1 = defineNuxtModule({
|
|
37
|
+
meta: {
|
|
38
|
+
name: "nuxt-miniapp-telegram-max",
|
|
39
|
+
configKey: "miniApps",
|
|
40
|
+
compatibility: { nuxt: ">=4.0.0" }
|
|
41
|
+
},
|
|
42
|
+
defaults: {
|
|
43
|
+
telegram: { sdkUrl: "https://telegram.org/js/telegram-web-app.js" },
|
|
44
|
+
max: { sdkUrl: "https://st.max.ru/js/max-web-app.js" },
|
|
45
|
+
sdkTimeout: 5e3,
|
|
46
|
+
earlyDetect: true,
|
|
47
|
+
autoReady: true,
|
|
48
|
+
cleanLaunchHash: true,
|
|
49
|
+
expand: false,
|
|
50
|
+
verticalSwipes: true,
|
|
51
|
+
colorSchemeAttribute: "",
|
|
52
|
+
initDataHeaders: {
|
|
53
|
+
telegram: "X-Telegram-Init-Data",
|
|
54
|
+
max: "X-Max-Init-Data"
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
setup(options, nuxt) {
|
|
58
|
+
const resolver = createResolver(import.meta.url);
|
|
59
|
+
nuxt.options.runtimeConfig.public.miniApps = defu(nuxt.options.runtimeConfig.public.miniApps, {
|
|
60
|
+
telegram: options.telegram,
|
|
61
|
+
max: options.max,
|
|
62
|
+
sdkTimeout: options.sdkTimeout,
|
|
63
|
+
autoReady: options.autoReady,
|
|
64
|
+
cleanLaunchHash: options.cleanLaunchHash,
|
|
65
|
+
expand: options.expand,
|
|
66
|
+
verticalSwipes: options.verticalSwipes,
|
|
67
|
+
colorSchemeAttribute: options.colorSchemeAttribute,
|
|
68
|
+
initDataHeaders: options.initDataHeaders
|
|
69
|
+
});
|
|
70
|
+
nuxt.options.runtimeConfig.miniApps = defu(nuxt.options.runtimeConfig.miniApps, {
|
|
71
|
+
telegramBotToken: "",
|
|
72
|
+
maxBotToken: ""
|
|
73
|
+
});
|
|
74
|
+
if (options.earlyDetect) {
|
|
75
|
+
const early = {
|
|
76
|
+
prefix: STORAGE_PREFIX,
|
|
77
|
+
classPrefix: CLASS_PREFIX,
|
|
78
|
+
attribute: options.colorSchemeAttribute
|
|
79
|
+
};
|
|
80
|
+
nuxt.options.app.head.script ||= [];
|
|
81
|
+
nuxt.options.app.head.script.push({
|
|
82
|
+
key: "nuxt-miniapp-telegram-max",
|
|
83
|
+
innerHTML: `(${earlyDetect.toString()})(${JSON.stringify(early)})`,
|
|
84
|
+
tagPriority: "critical"
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
addPlugin({ src: resolver.resolve("./runtime/plugin.client"), mode: "client" });
|
|
88
|
+
addImports(["useMiniApp", "useMiniAppBackButton", "useMiniAppHaptics", "useMiniAppClosingConfirmation"].map((name) => ({
|
|
89
|
+
name,
|
|
90
|
+
from: resolver.resolve(`./runtime/composables/${name}`)
|
|
91
|
+
})));
|
|
92
|
+
addServerImports(["validateInitData", "requireMiniAppInitData", "parseInitData"].map((name) => ({
|
|
93
|
+
name,
|
|
94
|
+
from: resolver.resolve("./runtime/server/utils/initData")
|
|
95
|
+
})));
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
export { module$1 as default };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { createBackButtonStack } from "../backButton.js";
|
|
2
|
+
import { callSdkSafely } from "../sdk.js";
|
|
3
|
+
import { isLinkOf, mediaColorScheme, onMediaColorSchemeChange } from "./shared.js";
|
|
4
|
+
const MAX_LINK_HOSTS = ["max.ru"];
|
|
5
|
+
export function createMaxSdk(max, platformFallback) {
|
|
6
|
+
const backButton = createBackButtonStack(max.BackButton);
|
|
7
|
+
const haptics = {
|
|
8
|
+
supported: !!max.HapticFeedback,
|
|
9
|
+
impact: (style) => callSdkSafely(() => max.HapticFeedback?.impactOccurred?.(style)),
|
|
10
|
+
notification: (type) => callSdkSafely(() => max.HapticFeedback?.notificationOccurred?.(type)),
|
|
11
|
+
selection: () => callSdkSafely(() => max.HapticFeedback?.selectionChanged?.())
|
|
12
|
+
};
|
|
13
|
+
async function settle(call, map) {
|
|
14
|
+
try {
|
|
15
|
+
const result = call();
|
|
16
|
+
return result ? map((await result)?.status) : "unsupported";
|
|
17
|
+
} catch {
|
|
18
|
+
return "unsupported";
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return {
|
|
22
|
+
client: "max",
|
|
23
|
+
raw: max,
|
|
24
|
+
platform: max.platform || platformFallback || "unknown",
|
|
25
|
+
// No theme in MAX's SDK: the webview follows the system scheme.
|
|
26
|
+
get colorScheme() {
|
|
27
|
+
return mediaColorScheme();
|
|
28
|
+
},
|
|
29
|
+
onColorSchemeChange: onMediaColorSchemeChange,
|
|
30
|
+
ready: () => callSdkSafely(() => max.ready?.()),
|
|
31
|
+
close: () => callSdkSafely(() => max.close?.()),
|
|
32
|
+
// MAX's SDK has no expand.
|
|
33
|
+
expand: () => {
|
|
34
|
+
},
|
|
35
|
+
setVerticalSwipes: (enabled) => callSdkSafely(() => enabled ? max.enableVerticalSwipes?.() : max.disableVerticalSwipes?.()),
|
|
36
|
+
setClosingConfirmation: (enabled) => callSdkSafely(() => enabled ? max.enableClosingConfirmation?.() : max.disableClosingConfirmation?.()),
|
|
37
|
+
openLink: (url) => callSdkSafely(() => max.openLink?.(url)),
|
|
38
|
+
openInternalLink(url) {
|
|
39
|
+
if (isLinkOf(url, MAX_LINK_HOSTS) && typeof max.openMaxLink === "function") {
|
|
40
|
+
callSdkSafely(() => max.openMaxLink?.(url));
|
|
41
|
+
} else {
|
|
42
|
+
callSdkSafely(() => max.openLink?.(url));
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
haptics,
|
|
46
|
+
pushBackButton: (handler) => backButton.push(handler),
|
|
47
|
+
// MAX has no native popups.
|
|
48
|
+
showPopup: () => null,
|
|
49
|
+
showConfirm: () => null,
|
|
50
|
+
downloadFile: (url, fileName) => settle(
|
|
51
|
+
() => max.downloadFile?.(url, fileName),
|
|
52
|
+
(status) => status === "cancelled" ? "cancelled" : "downloading"
|
|
53
|
+
),
|
|
54
|
+
canSharePreparedMessage: () => typeof max.shareMaxContent === "function",
|
|
55
|
+
sharePreparedMessage: (message) => settle(
|
|
56
|
+
() => max.shareMaxContent?.({ mid: message.mid, chatType: message.chatType }),
|
|
57
|
+
(status) => status === "cancelled" ? "cancelled" : "shared"
|
|
58
|
+
),
|
|
59
|
+
canRequestWriteAccess: () => false,
|
|
60
|
+
requestWriteAccess: () => Promise.resolve(false)
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ColorScheme } from '../../types.js';
|
|
2
|
+
/** Whether `url` is an https link to one of `hosts`. */
|
|
3
|
+
export declare function isLinkOf(url: string, hosts: readonly string[]): boolean;
|
|
4
|
+
/** A native call that answers through a callback; null when the method throws right away. */
|
|
5
|
+
export declare function callWithCallback<T>(call: (resolve: (value: T) => void) => void): Promise<T> | null;
|
|
6
|
+
/** The system color scheme: what MAX (it has no theme in its SDK) and the website go by. */
|
|
7
|
+
export declare function mediaColorScheme(): ColorScheme;
|
|
8
|
+
export declare function onMediaColorSchemeChange(callback: (scheme: ColorScheme) => void): () => void;
|
|
9
|
+
/**
|
|
10
|
+
* Opens a new tab, falling back to this one when a popup blocker refuses.
|
|
11
|
+
* Only web, mail and phone links: a `javascript:` URL would run in the page,
|
|
12
|
+
* the way the messengers' own `openLink` never lets it.
|
|
13
|
+
*/
|
|
14
|
+
export declare function openInNewTab(url: string): void;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export function isLinkOf(url, hosts) {
|
|
2
|
+
try {
|
|
3
|
+
const { protocol, hostname } = new URL(url);
|
|
4
|
+
return protocol === "https:" && hosts.includes(hostname);
|
|
5
|
+
} catch {
|
|
6
|
+
return false;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export function callWithCallback(call) {
|
|
10
|
+
let resolve;
|
|
11
|
+
const promise = new Promise((settle) => {
|
|
12
|
+
resolve = settle;
|
|
13
|
+
});
|
|
14
|
+
try {
|
|
15
|
+
call(resolve);
|
|
16
|
+
return promise;
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const DARK_QUERY = "(prefers-color-scheme: dark)";
|
|
22
|
+
export function mediaColorScheme() {
|
|
23
|
+
return window.matchMedia?.(DARK_QUERY).matches ? "dark" : "light";
|
|
24
|
+
}
|
|
25
|
+
export function onMediaColorSchemeChange(callback) {
|
|
26
|
+
const query = window.matchMedia?.(DARK_QUERY);
|
|
27
|
+
if (!query) return () => {
|
|
28
|
+
};
|
|
29
|
+
const listener = () => callback(mediaColorScheme());
|
|
30
|
+
query.addEventListener("change", listener);
|
|
31
|
+
return () => query.removeEventListener("change", listener);
|
|
32
|
+
}
|
|
33
|
+
const OPENABLE_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:", "mailto:", "tel:"]);
|
|
34
|
+
export function openInNewTab(url) {
|
|
35
|
+
let protocol;
|
|
36
|
+
try {
|
|
37
|
+
protocol = new URL(url, window.location.href).protocol;
|
|
38
|
+
} catch {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (!OPENABLE_PROTOCOLS.has(protocol)) return;
|
|
42
|
+
const opened = window.open(url, "_blank");
|
|
43
|
+
if (opened) {
|
|
44
|
+
opened.opener = null;
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
window.location.href = url;
|
|
48
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { createBackButtonStack } from "../backButton.js";
|
|
2
|
+
import { callSdkSafely, waitForSdkStatus } from "../sdk.js";
|
|
3
|
+
import { callWithCallback, isLinkOf } from "./shared.js";
|
|
4
|
+
const TELEGRAM_LINK_HOSTS = ["t.me", "telegram.me"];
|
|
5
|
+
export function createTelegramSdk(tg, platformFallback) {
|
|
6
|
+
const backButton = createBackButtonStack(tg.BackButton);
|
|
7
|
+
const colorScheme = () => tg.colorScheme === "dark" ? "dark" : "light";
|
|
8
|
+
const haptics = {
|
|
9
|
+
supported: !!tg.HapticFeedback,
|
|
10
|
+
impact: (style) => callSdkSafely(() => tg.HapticFeedback?.impactOccurred?.(style)),
|
|
11
|
+
notification: (type) => callSdkSafely(() => tg.HapticFeedback?.notificationOccurred?.(type)),
|
|
12
|
+
selection: () => callSdkSafely(() => tg.HapticFeedback?.selectionChanged?.())
|
|
13
|
+
};
|
|
14
|
+
return {
|
|
15
|
+
client: "telegram",
|
|
16
|
+
raw: tg,
|
|
17
|
+
platform: tg.platform || platformFallback || "unknown",
|
|
18
|
+
get colorScheme() {
|
|
19
|
+
return colorScheme();
|
|
20
|
+
},
|
|
21
|
+
onColorSchemeChange(callback) {
|
|
22
|
+
const listener = () => callback(colorScheme());
|
|
23
|
+
callSdkSafely(() => tg.onEvent?.("themeChanged", listener));
|
|
24
|
+
return () => callSdkSafely(() => tg.offEvent?.("themeChanged", listener));
|
|
25
|
+
},
|
|
26
|
+
ready: () => callSdkSafely(() => tg.ready?.()),
|
|
27
|
+
close: () => callSdkSafely(() => tg.close?.()),
|
|
28
|
+
expand: () => callSdkSafely(() => tg.expand?.()),
|
|
29
|
+
setVerticalSwipes: (enabled) => callSdkSafely(() => enabled ? tg.enableVerticalSwipes?.() : tg.disableVerticalSwipes?.()),
|
|
30
|
+
setClosingConfirmation: (enabled) => callSdkSafely(() => enabled ? tg.enableClosingConfirmation?.() : tg.disableClosingConfirmation?.()),
|
|
31
|
+
openLink: (url) => callSdkSafely(() => tg.openLink?.(url)),
|
|
32
|
+
openInternalLink(url) {
|
|
33
|
+
if (isLinkOf(url, TELEGRAM_LINK_HOSTS) && typeof tg.openTelegramLink === "function") {
|
|
34
|
+
callSdkSafely(() => tg.openTelegramLink?.(url));
|
|
35
|
+
} else {
|
|
36
|
+
callSdkSafely(() => tg.openLink?.(url));
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
haptics,
|
|
40
|
+
pushBackButton: (handler) => backButton.push(handler),
|
|
41
|
+
showPopup(params) {
|
|
42
|
+
const showPopup = tg.showPopup;
|
|
43
|
+
if (typeof showPopup !== "function") return null;
|
|
44
|
+
return callWithCallback((resolve) => showPopup.call(
|
|
45
|
+
tg,
|
|
46
|
+
{ ...params, buttons: params.buttons ?? [{ type: "ok" }] },
|
|
47
|
+
(buttonId) => resolve(buttonId || "ok")
|
|
48
|
+
));
|
|
49
|
+
},
|
|
50
|
+
showConfirm(message) {
|
|
51
|
+
const showConfirm = tg.showConfirm;
|
|
52
|
+
if (typeof showConfirm !== "function") return null;
|
|
53
|
+
return callWithCallback((resolve) => showConfirm.call(tg, message, (confirmed) => resolve(confirmed)));
|
|
54
|
+
},
|
|
55
|
+
async downloadFile(url, fileName) {
|
|
56
|
+
const downloadFile = tg.downloadFile;
|
|
57
|
+
if (typeof downloadFile !== "function") return "unsupported";
|
|
58
|
+
try {
|
|
59
|
+
return await waitForSdkStatus("cancelled", (settle) => {
|
|
60
|
+
downloadFile.call(tg, { url, file_name: fileName }, (accepted) => settle(accepted ? "downloading" : "cancelled"));
|
|
61
|
+
});
|
|
62
|
+
} catch {
|
|
63
|
+
return "unsupported";
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
canSharePreparedMessage: () => typeof tg.shareMessage === "function",
|
|
67
|
+
async sharePreparedMessage(messageId) {
|
|
68
|
+
const shareMessage = tg.shareMessage;
|
|
69
|
+
if (typeof shareMessage !== "function") return "unsupported";
|
|
70
|
+
try {
|
|
71
|
+
return await waitForSdkStatus("cancelled", (settle) => {
|
|
72
|
+
shareMessage.call(tg, messageId, (sent) => settle(sent ? "shared" : "cancelled"));
|
|
73
|
+
});
|
|
74
|
+
} catch {
|
|
75
|
+
return "unsupported";
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
canRequestWriteAccess: () => typeof tg.requestWriteAccess === "function",
|
|
79
|
+
requestWriteAccess() {
|
|
80
|
+
const requestWriteAccess = tg.requestWriteAccess;
|
|
81
|
+
if (typeof requestWriteAccess !== "function") return Promise.resolve(false);
|
|
82
|
+
return callWithCallback((resolve) => requestWriteAccess.call(tg, (granted) => resolve(granted))) ?? Promise.resolve(false);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
}
|