@pushler/vue 1.0.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.
@@ -0,0 +1,876 @@
1
+ /*!
2
+ * @pushler/vue v1.0.0
3
+ * (c) 2026 Pushler.ru
4
+ * @license MIT
5
+ */
6
+ (function (global, factory) {
7
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vue')) :
8
+ typeof define === 'function' && define.amd ? define(['exports', 'vue'], factory) :
9
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.PushlerVue = {}, global.Vue));
10
+ })(this, (function (exports, vue) { 'use strict';
11
+
12
+ /**
13
+ * Состояния подключения
14
+ */
15
+ const ConnectionStates = {
16
+ CONNECTING: 'connecting',
17
+ CONNECTED: 'connected',
18
+ DISCONNECTED: 'disconnected',
19
+ RECONNECTING: 'reconnecting',
20
+ FAILED: 'failed'
21
+ };
22
+
23
+ /**
24
+ * Типы каналов
25
+ */
26
+ const ChannelTypes = {
27
+ PUBLIC: 'public',
28
+ PRIVATE: 'private',
29
+ PRESENCE: 'presence'
30
+ };
31
+
32
+ /**
33
+ * Vue composable для работы с Pushler WebSocket
34
+ *
35
+ * @param {Object} options - Опции подключения
36
+ * @param {string} options.appKey - Ключ приложения
37
+ * @param {string} options.wsUrl - URL WebSocket сервера
38
+ * @param {string} options.authEndpoint - Эндпоинт авторизации для приватных каналов
39
+ * @param {boolean} options.autoConnect - Автоматическое подключение (по умолчанию false)
40
+ * @param {number} options.reconnectDelay - Задержка переподключения в мс (по умолчанию 1000)
41
+ * @param {number} options.maxReconnectAttempts - Максимум попыток переподключения (по умолчанию 5)
42
+ * @returns {Object} Реактивный объект с методами и состоянием
43
+ */
44
+ function usePushler(options = {}) {
45
+ // Реактивное состояние
46
+ const connectionState = vue.ref(ConnectionStates.DISCONNECTED);
47
+ const socketId = vue.ref(null);
48
+ const error = vue.ref(null);
49
+ const reconnectAttempts = vue.ref(0);
50
+
51
+ // Каналы
52
+ const channels = vue.reactive(new Map());
53
+ const channelAliases = vue.reactive(new Map());
54
+
55
+ // Внутренние переменные
56
+ let socket = null;
57
+ let reconnectTimer = null;
58
+ const eventListeners = new Map();
59
+
60
+ // Конфигурация
61
+ const config = {
62
+ appKey: options.appKey || '',
63
+ wsUrl: options.wsUrl || 'ws://localhost:8081/app',
64
+ authEndpoint: options.authEndpoint || '/pushler/auth',
65
+ autoConnect: options.autoConnect || false,
66
+ reconnectDelay: options.reconnectDelay || 1000,
67
+ maxReconnectAttempts: options.maxReconnectAttempts || 5,
68
+ };
69
+
70
+ // Вычисляемые свойства
71
+ const isConnected = vue.computed(() => connectionState.value === ConnectionStates.CONNECTED);
72
+ const isConnecting = vue.computed(() => connectionState.value === ConnectionStates.CONNECTING);
73
+ const isReconnecting = vue.computed(() => connectionState.value === ConnectionStates.RECONNECTING);
74
+
75
+ /**
76
+ * Форматирование имени канала с префиксом appKey
77
+ */
78
+ function formatChannelName(channelName) {
79
+ if (channelName.startsWith(config.appKey + ':')) {
80
+ return channelName;
81
+ }
82
+ return `${config.appKey}:${channelName}`;
83
+ }
84
+
85
+ /**
86
+ * Извлечение оригинального имени канала
87
+ */
88
+ function extractChannelName(fullChannelName) {
89
+ const prefix = config.appKey + ':';
90
+ if (fullChannelName.startsWith(prefix)) {
91
+ return fullChannelName.substring(prefix.length);
92
+ }
93
+ return fullChannelName;
94
+ }
95
+
96
+ /**
97
+ * Определение типа канала
98
+ */
99
+ function getChannelType(channelName) {
100
+ const baseName = extractChannelName(channelName);
101
+ if (baseName.startsWith('private-')) return ChannelTypes.PRIVATE;
102
+ if (baseName.startsWith('presence-')) return ChannelTypes.PRESENCE;
103
+ return ChannelTypes.PUBLIC;
104
+ }
105
+
106
+ /**
107
+ * Подключение к WebSocket серверу
108
+ */
109
+ function connect(connectOptions = {}) {
110
+ // Обновляем конфигурацию если переданы новые параметры
111
+ if (connectOptions.appKey) config.appKey = connectOptions.appKey;
112
+ if (connectOptions.wsUrl) config.wsUrl = connectOptions.wsUrl;
113
+ if (connectOptions.authEndpoint) config.authEndpoint = connectOptions.authEndpoint;
114
+
115
+ if (connectionState.value === ConnectionStates.CONNECTED ||
116
+ connectionState.value === ConnectionStates.CONNECTING) {
117
+ return;
118
+ }
119
+
120
+ connectionState.value = ConnectionStates.CONNECTING;
121
+ error.value = null;
122
+
123
+ try {
124
+ // Формируем URL с ключом приложения
125
+ const wsUrl = config.wsUrl.endsWith('/')
126
+ ? `${config.wsUrl}${config.appKey}`
127
+ : `${config.wsUrl}/${config.appKey}`;
128
+
129
+ console.log('[Pushler Vue] Connecting to:', wsUrl);
130
+ socket = new WebSocket(wsUrl);
131
+ setupSocketHandlers();
132
+ } catch (err) {
133
+ console.error('[Pushler Vue] Connection error:', err);
134
+ connectionState.value = ConnectionStates.FAILED;
135
+ error.value = err.message;
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Настройка обработчиков WebSocket
141
+ */
142
+ function setupSocketHandlers() {
143
+ socket.onopen = () => {
144
+ console.log('[Pushler Vue] WebSocket opened, waiting for connection_established...');
145
+ };
146
+
147
+ socket.onmessage = (event) => {
148
+ handleMessage(event);
149
+ };
150
+
151
+ socket.onclose = (event) => {
152
+ console.log('[Pushler Vue] WebSocket closed:', event.code, event.reason);
153
+ connectionState.value = ConnectionStates.DISCONNECTED;
154
+ socketId.value = null;
155
+
156
+ // Автопереподключение
157
+ if (event.code !== 1000 && reconnectAttempts.value < config.maxReconnectAttempts) {
158
+ scheduleReconnect();
159
+ }
160
+ };
161
+
162
+ socket.onerror = (err) => {
163
+ console.error('[Pushler Vue] WebSocket error:', err);
164
+ connectionState.value = ConnectionStates.FAILED;
165
+ error.value = 'Connection failed';
166
+ };
167
+ }
168
+
169
+ /**
170
+ * Обработка входящих сообщений
171
+ */
172
+ function handleMessage(event) {
173
+ try {
174
+ // Поддержка нескольких сообщений в одном event
175
+ const messages = event.data.trim().split('\n').filter(line => line.trim());
176
+
177
+ for (const msgData of messages) {
178
+ processMessage(JSON.parse(msgData));
179
+ }
180
+ } catch (err) {
181
+ console.error('[Pushler Vue] Error parsing message:', err);
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Обработка отдельного сообщения
187
+ */
188
+ function processMessage(message) {
189
+ switch (message.event) {
190
+ case 'pushler:connection_established':
191
+ handleConnectionEstablished(message.data);
192
+ break;
193
+ case 'pushler:subscription_succeeded':
194
+ handleSubscriptionSucceeded(message);
195
+ break;
196
+ case 'pushler:auth_success':
197
+ handleAuthSuccess(message);
198
+ break;
199
+ case 'pushler:auth_error':
200
+ handleAuthError(message);
201
+ break;
202
+ default:
203
+ handleChannelMessage(message);
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Обработка установления соединения
209
+ */
210
+ function handleConnectionEstablished(data) {
211
+ socketId.value = data.socket_id;
212
+ connectionState.value = ConnectionStates.CONNECTED;
213
+ reconnectAttempts.value = 0;
214
+
215
+ console.log('[Pushler Vue] Connected with socket ID:', socketId.value);
216
+
217
+ // Переподписка на все каналы
218
+ resubscribeAllChannels();
219
+
220
+ emit('connected', { socketId: socketId.value });
221
+ }
222
+
223
+ /**
224
+ * Переподписка на все каналы
225
+ */
226
+ function resubscribeAllChannels() {
227
+ for (const [name, channel] of channels.entries()) {
228
+ channel.subscribed = false;
229
+ performChannelSubscription(channel);
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Обработка успешной подписки
235
+ */
236
+ function handleSubscriptionSucceeded(message) {
237
+ const channel = channels.get(message.channel);
238
+ if (channel) {
239
+ channel.subscribed = true;
240
+ channel.emit('subscribed', message.data || {});
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Обработка успешной авторизации
246
+ */
247
+ function handleAuthSuccess(message) {
248
+ const channel = channels.get(message.data.channel);
249
+ if (channel) {
250
+ channel.subscribed = true;
251
+ channel.emit('subscribed', message.data);
252
+ }
253
+ emit('auth_success', message.data);
254
+ }
255
+
256
+ /**
257
+ * Обработка ошибки авторизации
258
+ */
259
+ function handleAuthError(message) {
260
+ error.value = message.data.error;
261
+ emit('auth_error', message.data);
262
+ }
263
+
264
+ /**
265
+ * Обработка сообщения канала
266
+ */
267
+ function handleChannelMessage(message) {
268
+ const { channel: channelName, event, data } = message;
269
+ const channel = channels.get(channelName);
270
+
271
+ if (channel) {
272
+ channel.emit(event, data);
273
+ }
274
+
275
+ emit('message', {
276
+ channel: extractChannelName(channelName),
277
+ event,
278
+ data
279
+ });
280
+ }
281
+
282
+ /**
283
+ * Планирование переподключения
284
+ */
285
+ function scheduleReconnect() {
286
+ if (reconnectTimer) {
287
+ clearTimeout(reconnectTimer);
288
+ }
289
+
290
+ reconnectAttempts.value++;
291
+ connectionState.value = ConnectionStates.RECONNECTING;
292
+
293
+ const delay = config.reconnectDelay * reconnectAttempts.value;
294
+ console.log(`[Pushler Vue] Reconnecting in ${delay}ms (attempt ${reconnectAttempts.value}/${config.maxReconnectAttempts})`);
295
+
296
+ reconnectTimer = setTimeout(() => {
297
+ connect();
298
+ }, delay);
299
+ }
300
+
301
+ /**
302
+ * Отключение от сервера
303
+ */
304
+ function disconnect() {
305
+ if (reconnectTimer) {
306
+ clearTimeout(reconnectTimer);
307
+ reconnectTimer = null;
308
+ }
309
+
310
+ if (socket) {
311
+ socket.close(1000, 'User disconnect');
312
+ socket = null;
313
+ }
314
+
315
+ connectionState.value = ConnectionStates.DISCONNECTED;
316
+ socketId.value = null;
317
+ channels.clear();
318
+ channelAliases.clear();
319
+ reconnectAttempts.value = 0;
320
+
321
+ emit('disconnected');
322
+ }
323
+
324
+ /**
325
+ * Отправка сообщения через WebSocket
326
+ */
327
+ function sendMessage(message) {
328
+ if (socket && socket.readyState === WebSocket.OPEN) {
329
+ socket.send(JSON.stringify(message));
330
+ }
331
+ }
332
+
333
+ /**
334
+ * Подписка на канал
335
+ * @param {string} channelName - Имя канала
336
+ * @param {Object} options - Опции (signature для приватных, user для presence)
337
+ * @returns {Object} Реактивный объект канала
338
+ */
339
+ function subscribe(channelName, subscribeOptions = {}) {
340
+ const fullChannelName = formatChannelName(channelName);
341
+
342
+ if (channels.has(fullChannelName)) {
343
+ return channels.get(fullChannelName);
344
+ }
345
+
346
+ // Создаем реактивный канал
347
+ const channel = vue.reactive({
348
+ name: fullChannelName,
349
+ originalName: channelName,
350
+ type: getChannelType(channelName),
351
+ subscribed: false,
352
+ options: subscribeOptions,
353
+ listeners: new Map(),
354
+
355
+ // Методы канала
356
+ on(event, callback) {
357
+ if (!this.listeners.has(event)) {
358
+ this.listeners.set(event, []);
359
+ }
360
+ this.listeners.get(event).push(callback);
361
+ return this;
362
+ },
363
+
364
+ off(event, callback) {
365
+ if (this.listeners.has(event)) {
366
+ const list = this.listeners.get(event);
367
+ const idx = list.indexOf(callback);
368
+ if (idx > -1) list.splice(idx, 1);
369
+ }
370
+ return this;
371
+ },
372
+
373
+ emit(event, data) {
374
+ if (this.listeners.has(event)) {
375
+ this.listeners.get(event).forEach(cb => {
376
+ try {
377
+ cb(data);
378
+ } catch (err) {
379
+ console.error('[Pushler Vue] Channel event error:', err);
380
+ }
381
+ });
382
+ }
383
+ },
384
+
385
+ unsubscribe() {
386
+ unsubscribe(channelName);
387
+ }
388
+ });
389
+
390
+ channels.set(fullChannelName, channel);
391
+ channelAliases.set(channelName, fullChannelName);
392
+
393
+ // Подписываемся если уже подключены
394
+ if (connectionState.value === ConnectionStates.CONNECTED) {
395
+ performChannelSubscription(channel);
396
+ }
397
+
398
+ return channel;
399
+ }
400
+
401
+ /**
402
+ * Выполнение подписки на канал
403
+ */
404
+ async function performChannelSubscription(channel) {
405
+ if (connectionState.value !== ConnectionStates.CONNECTED) {
406
+ return;
407
+ }
408
+
409
+ const channelType = channel.type;
410
+
411
+ // Публичные каналы
412
+ if (channelType === ChannelTypes.PUBLIC) {
413
+ sendMessage({
414
+ event: 'pushler:subscribe',
415
+ data: {
416
+ channel: channel.name,
417
+ app_key: config.appKey
418
+ }
419
+ });
420
+ return;
421
+ }
422
+
423
+ // Приватные и presence каналы требуют авторизации
424
+ try {
425
+ const authData = await getAuthData(channel);
426
+ sendMessage({
427
+ event: 'pushler:auth',
428
+ data: authData
429
+ });
430
+ } catch (err) {
431
+ console.error('[Pushler Vue] Auth error:', err);
432
+ error.value = err.message;
433
+ }
434
+ }
435
+
436
+ /**
437
+ * Получение данных авторизации для приватных/presence каналов
438
+ *
439
+ * Для приватных каналов подпись ДОЛЖНА быть получена с вашего бэкенда,
440
+ * либо передана в options.signature при подписке.
441
+ *
442
+ * НИКОГДА не храните секретный ключ в клиентском коде!
443
+ */
444
+ async function getAuthData(channel) {
445
+ if (!socketId.value) {
446
+ throw new Error('Socket ID not available');
447
+ }
448
+
449
+ const authData = {
450
+ app_key: config.appKey,
451
+ channel: channel.name,
452
+ socket_id: socketId.value
453
+ };
454
+
455
+ // Если подпись уже предоставлена в options
456
+ if (channel.options.signature) {
457
+ authData.signature = channel.options.signature;
458
+ } else {
459
+ // Запрашиваем подпись с бэкенда
460
+ authData.signature = await fetchSignature(channel);
461
+ }
462
+
463
+ // Данные пользователя для presence каналов
464
+ if (channel.type === ChannelTypes.PRESENCE && channel.options.user) {
465
+ authData.user = channel.options.user;
466
+ }
467
+
468
+ return authData;
469
+ }
470
+
471
+ /**
472
+ * Запрос подписи с бэкенда
473
+ *
474
+ * Ваш бэкенд должен:
475
+ * 1. Проверить авторизацию пользователя
476
+ * 2. Сгенерировать HMAC-SHA256 подпись с секретным ключом
477
+ * 3. Вернуть подпись клиенту
478
+ */
479
+ async function fetchSignature(channel) {
480
+ const response = await fetch(config.authEndpoint, {
481
+ method: 'POST',
482
+ headers: { 'Content-Type': 'application/json' },
483
+ credentials: 'include', // Включаем куки для авторизации
484
+ body: JSON.stringify({
485
+ channel_name: channel.name,
486
+ socket_id: socketId.value,
487
+ app_key: config.appKey,
488
+ user_data: channel.options.user
489
+ })
490
+ });
491
+
492
+ if (!response.ok) {
493
+ const err = await response.json().catch(() => ({ error: 'Auth request failed' }));
494
+ throw new Error(err.error || 'Failed to get signature');
495
+ }
496
+
497
+ const data = await response.json();
498
+ return data.signature;
499
+ }
500
+
501
+ /**
502
+ * Отписка от канала
503
+ */
504
+ function unsubscribe(channelName) {
505
+ const fullChannelName = channelAliases.get(channelName) || formatChannelName(channelName);
506
+ const channel = channels.get(fullChannelName);
507
+
508
+ if (channel) {
509
+ if (channel.subscribed && connectionState.value === ConnectionStates.CONNECTED) {
510
+ sendMessage({
511
+ event: 'pushler:unsubscribe',
512
+ data: { channel: fullChannelName }
513
+ });
514
+ }
515
+
516
+ channels.delete(fullChannelName);
517
+ channelAliases.delete(channelName);
518
+ }
519
+ }
520
+
521
+ /**
522
+ * Получение канала по имени
523
+ */
524
+ function channel(channelName) {
525
+ const fullChannelName = channelAliases.get(channelName) || formatChannelName(channelName);
526
+ return channels.get(fullChannelName);
527
+ }
528
+
529
+ /**
530
+ * Получение списка каналов
531
+ */
532
+ function getChannels() {
533
+ return Array.from(channels.values()).map(ch => ({
534
+ name: ch.originalName,
535
+ fullName: ch.name,
536
+ type: ch.type,
537
+ subscribed: ch.subscribed
538
+ }));
539
+ }
540
+
541
+ /**
542
+ * Подписка на глобальное событие
543
+ */
544
+ function on(event, callback) {
545
+ if (!eventListeners.has(event)) {
546
+ eventListeners.set(event, []);
547
+ }
548
+ eventListeners.get(event).push(callback);
549
+ }
550
+
551
+ /**
552
+ * Отписка от глобального события
553
+ */
554
+ function off(event, callback) {
555
+ if (eventListeners.has(event)) {
556
+ const list = eventListeners.get(event);
557
+ const idx = list.indexOf(callback);
558
+ if (idx > -1) list.splice(idx, 1);
559
+ }
560
+ }
561
+
562
+ /**
563
+ * Вызов глобального события
564
+ */
565
+ function emit(event, data) {
566
+ if (eventListeners.has(event)) {
567
+ eventListeners.get(event).forEach(cb => {
568
+ try {
569
+ cb(data);
570
+ } catch (err) {
571
+ console.error('[Pushler Vue] Event error:', err);
572
+ }
573
+ });
574
+ }
575
+ }
576
+
577
+ // Автоматическое отключение при размонтировании компонента
578
+ vue.onUnmounted(() => {
579
+ disconnect();
580
+ });
581
+
582
+ // Автоподключение если указано
583
+ if (config.autoConnect && config.appKey) {
584
+ connect();
585
+ }
586
+
587
+ return {
588
+ // Состояние (readonly для защиты от внешних изменений)
589
+ connectionState: vue.readonly(connectionState),
590
+ socketId: vue.readonly(socketId),
591
+ error: vue.readonly(error),
592
+ reconnectAttempts: vue.readonly(reconnectAttempts),
593
+
594
+ // Вычисляемые свойства
595
+ isConnected,
596
+ isConnecting,
597
+ isReconnecting,
598
+
599
+ // Методы
600
+ connect,
601
+ disconnect,
602
+ subscribe,
603
+ unsubscribe,
604
+ channel,
605
+ getChannels,
606
+ on,
607
+ off,
608
+
609
+ // Утилиты
610
+ formatChannelName,
611
+ extractChannelName,
612
+ getChannelType,
613
+
614
+ // Константы
615
+ ConnectionStates,
616
+ ChannelTypes,
617
+ };
618
+ }
619
+
620
+ /**
621
+ * Vue composable для работы с отдельным каналом Pushler
622
+ *
623
+ * Можно использовать автономно или совместно с usePushler
624
+ *
625
+ * @param {Object} pushler - Инстанс usePushler
626
+ * @param {string} channelName - Имя канала
627
+ * @param {Object} options - Опции канала
628
+ * @returns {Object} Реактивный объект канала с событиями
629
+ */
630
+ function usePushlerChannel(pushler, channelName, options = {}) {
631
+ const channel = vue.ref(null);
632
+ const isSubscribed = vue.ref(false);
633
+ const lastEvent = vue.ref(null);
634
+ const events = vue.reactive([]);
635
+ const eventHandlers = new Map();
636
+
637
+ /**
638
+ * Максимальное количество событий в буфере
639
+ */
640
+ const maxEvents = options.maxEvents || 100;
641
+
642
+ /**
643
+ * Подписка на канал
644
+ */
645
+ function subscribe() {
646
+ if (!pushler || !channelName) return;
647
+
648
+ channel.value = pushler.subscribe(channelName, options);
649
+
650
+ // Отслеживаем статус подписки
651
+ channel.value.on('subscribed', () => {
652
+ isSubscribed.value = true;
653
+ });
654
+
655
+ return channel.value;
656
+ }
657
+
658
+ /**
659
+ * Отписка от канала
660
+ */
661
+ function unsubscribe() {
662
+ if (pushler && channelName) {
663
+ pushler.unsubscribe(channelName);
664
+ channel.value = null;
665
+ isSubscribed.value = false;
666
+ }
667
+ }
668
+
669
+ /**
670
+ * Подписка на событие канала
671
+ * @param {string} eventName - Имя события
672
+ * @param {Function} callback - Обработчик
673
+ */
674
+ function on(eventName, callback) {
675
+ if (!channel.value) {
676
+ subscribe();
677
+ }
678
+
679
+ const handler = (data) => {
680
+ // Сохраняем последнее событие
681
+ lastEvent.value = {
682
+ event: eventName,
683
+ data,
684
+ timestamp: new Date()
685
+ };
686
+
687
+ // Добавляем в буфер событий
688
+ events.unshift(lastEvent.value);
689
+ if (events.length > maxEvents) {
690
+ events.pop();
691
+ }
692
+
693
+ // Вызываем пользовательский обработчик
694
+ callback(data);
695
+ };
696
+
697
+ eventHandlers.set(eventName, handler);
698
+ channel.value.on(eventName, handler);
699
+
700
+ return () => off(eventName);
701
+ }
702
+
703
+ /**
704
+ * Отписка от события канала
705
+ */
706
+ function off(eventName) {
707
+ if (channel.value && eventHandlers.has(eventName)) {
708
+ channel.value.off(eventName, eventHandlers.get(eventName));
709
+ eventHandlers.delete(eventName);
710
+ }
711
+ }
712
+
713
+ /**
714
+ * Очистка буфера событий
715
+ */
716
+ function clearEvents() {
717
+ events.length = 0;
718
+ lastEvent.value = null;
719
+ }
720
+
721
+ // Автоматическая подписка если указано
722
+ if (options.autoSubscribe !== false && pushler?.isConnected?.value) {
723
+ subscribe();
724
+ }
725
+
726
+ // Подписываемся при подключении
727
+ if (pushler) {
728
+ vue.watch(() => pushler.isConnected.value, (connected) => {
729
+ if (connected && options.autoSubscribe !== false && !channel.value) {
730
+ subscribe();
731
+ }
732
+ });
733
+ }
734
+
735
+ // Автоматическая отписка при размонтировании
736
+ vue.onUnmounted(() => {
737
+ unsubscribe();
738
+ });
739
+
740
+ return {
741
+ channel,
742
+ isSubscribed,
743
+ lastEvent,
744
+ events,
745
+
746
+ subscribe,
747
+ unsubscribe,
748
+ on,
749
+ off,
750
+ clearEvents,
751
+ };
752
+ }
753
+
754
+ /**
755
+ * Символ для инъекции Pushler
756
+ */
757
+ const PushlerKey = Symbol('pushler');
758
+
759
+ /**
760
+ * Vue Plugin для глобальной инициализации Pushler
761
+ *
762
+ * Использование:
763
+ *
764
+ * ```js
765
+ * import { createApp } from 'vue';
766
+ * import { PushlerPlugin } from '@pushler/vue';
767
+ *
768
+ * const app = createApp(App);
769
+ * app.use(PushlerPlugin, {
770
+ * appKey: 'your-app-key',
771
+ * wsUrl: 'wss://ws.pushler.ru/app',
772
+ * autoConnect: true
773
+ * });
774
+ * ```
775
+ *
776
+ * Затем в компонентах:
777
+ *
778
+ * ```js
779
+ * import { inject } from 'vue';
780
+ * import { PushlerKey } from '@pushler/vue';
781
+ *
782
+ * const pushler = inject(PushlerKey);
783
+ * ```
784
+ */
785
+ const PushlerPlugin = {
786
+ install(app, options = {}) {
787
+ // Создаем глобальный инстанс Pushler
788
+ const pushler = usePushler(options);
789
+
790
+ // Предоставляем через provide/inject
791
+ app.provide(PushlerKey, pushler);
792
+
793
+ // Также добавляем как глобальное свойство (для Options API)
794
+ app.config.globalProperties.$pushler = pushler;
795
+
796
+ // Экспортируем константы
797
+ app.config.globalProperties.$PushlerConnectionStates = ConnectionStates;
798
+ app.config.globalProperties.$PushlerChannelTypes = ChannelTypes;
799
+ }
800
+ };
801
+
802
+ /**
803
+ * Хелпер для получения инстанса Pushler в setup()
804
+ */
805
+ function usePushlerInstance() {
806
+ const pushler = inject(PushlerKey);
807
+ if (!pushler) {
808
+ throw new Error(
809
+ '[Pushler Vue] No Pushler instance found. ' +
810
+ 'Make sure to install PushlerPlugin or provide a Pushler instance.'
811
+ );
812
+ }
813
+ return pushler;
814
+ }
815
+
816
+ /**
817
+ * Pushler Vue SDK
818
+ *
819
+ * Реактивный Vue.js SDK для работы с Pushler.ru WebSocket сервером
820
+ *
821
+ * @example Базовое использование
822
+ * ```vue
823
+ * <script setup>
824
+ * import { usePushler } from '@pushler/vue';
825
+ *
826
+ * const pushler = usePushler({
827
+ * appKey: 'your-app-key',
828
+ * wsUrl: 'wss://ws.pushler.ru/app'
829
+ * });
830
+ *
831
+ * // Подключение
832
+ * pushler.connect();
833
+ *
834
+ * // Подписка на канал
835
+ * const channel = pushler.subscribe('my-channel');
836
+ * channel.on('message', (data) => {
837
+ * console.log('Received:', data);
838
+ * });
839
+ * </script>
840
+ *
841
+ * <template>
842
+ * <div>
843
+ * <p>Status: {{ pushler.connectionState }}</p>
844
+ * <p>Socket ID: {{ pushler.socketId }}</p>
845
+ * </div>
846
+ * </template>
847
+ * ```
848
+ *
849
+ * @example С Vue Plugin
850
+ * ```js
851
+ * // main.js
852
+ * import { createApp } from 'vue';
853
+ * import { PushlerPlugin } from '@pushler/vue';
854
+ *
855
+ * const app = createApp(App);
856
+ * app.use(PushlerPlugin, {
857
+ * appKey: 'your-app-key',
858
+ * wsUrl: 'wss://ws.pushler.ru/app',
859
+ * autoConnect: true
860
+ * });
861
+ * ```
862
+ */
863
+
864
+ exports.ChannelTypes = ChannelTypes;
865
+ exports.ConnectionStates = ConnectionStates;
866
+ exports.PushlerKey = PushlerKey;
867
+ exports.PushlerPlugin = PushlerPlugin;
868
+ exports.default = usePushler;
869
+ exports.usePushler = usePushler;
870
+ exports.usePushlerChannel = usePushlerChannel;
871
+ exports.usePushlerInstance = usePushlerInstance;
872
+
873
+ Object.defineProperty(exports, '__esModule', { value: true });
874
+
875
+ }));
876
+ //# sourceMappingURL=pushler-vue.umd.js.map