@wuisdk/plugin-wss 0.1.11 → 0.1.13

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.d.ts CHANGED
@@ -1,28 +1,6 @@
1
1
  import "@wuisdk/plugin-auth";
2
2
  import { WuiContext, WuiPlugin } from "@wuisdk/core";
3
- //#region src/types.d.ts
4
- declare module '@wuisdk/core' {
5
- interface WuiPluginMap {
6
- readonly wss: IWssService;
7
- }
8
- }
9
- declare module '@wuisdk/core' {
10
- interface WuiEventMap {
11
- 'wss:connected': void;
12
- 'wss:disconnected': void;
13
- }
14
- }
15
- interface WssPluginOptions {
16
- worker: new () => Worker;
17
- endpoint?: string;
18
- }
19
- interface IWssService {
20
- readonly wsuuid: string;
21
- post(packet: WSPacket): void;
22
- direct(target: string, payload: unknown): void;
23
- publish(topic: WSTopic, payload: unknown): void;
24
- subscribe<T>(topic: WSTopic, callback: (data: T) => void, signal?: AbortSignal): () => void;
25
- }
3
+ //#region src/ws.types.d.ts
26
4
  interface WSParams {
27
5
  url: string;
28
6
  app: string;
@@ -30,35 +8,89 @@ interface WSParams {
30
8
  ver: string;
31
9
  rel: string;
32
10
  }
33
- type WSTopic = 'SRV_TIME' | 'SRV_LOGS' | 'SRV_STATUS' | 'CLT_ONLINE' | 'CLT_STATUS';
34
- interface WSPacket<T = unknown> {
35
- head: string;
36
- data?: T;
11
+ export declare const WSMsgType: {
12
+ readonly Subscribe: "SUBSCRIBE";
13
+ readonly Unsubscribe: "UNSUBSCRIBE";
14
+ readonly Publish: "PUBLISH";
15
+ readonly Direct: "DIRECT";
16
+ readonly Event: "EVENT";
17
+ readonly Ack: "ACK";
18
+ readonly Error: "ERROR";
19
+ readonly Ping: "PING";
20
+ readonly Pong: "PONG";
21
+ readonly Connect: "CONNECT";
22
+ readonly Disconnect: "DISCONNECT";
23
+ readonly Verify: "VERIFY";
24
+ readonly Expired: "EXPIRED";
25
+ };
26
+ export type WSMsgType = (typeof WSMsgType)[keyof typeof WSMsgType];
27
+ type WSTopic = 'server.time' | 'server.logs' | 'server.status' | 'client.online' | 'client.status';
28
+ interface WSMeta {
29
+ timestamp?: number;
30
+ requestId?: string;
31
+ publisherId?: string;
37
32
  }
38
- interface WSPubSub<T = unknown> {
33
+ interface WSTarget {
34
+ type?: string;
35
+ id: string;
36
+ }
37
+ interface WSMessage<T = unknown> {
38
+ type: WSMsgType;
39
39
  topic?: string;
40
- sender?: string;
41
- target?: string;
42
- payload?: T;
40
+ target?: WSTarget;
41
+ data?: T;
42
+ meta?: WSMeta;
43
43
  }
44
- interface WSTimeData {
44
+ interface AckPayload {
45
+ status: string;
46
+ wsuuid?: string;
47
+ }
48
+ interface ErrorPayload {
49
+ code: string;
50
+ message: string;
51
+ }
52
+ interface TimePayload {
45
53
  time: string;
46
54
  unix: number;
47
55
  }
48
- interface WSLogsData {
49
- time: string;
50
- msg: string;
56
+ interface LogsPayload {
57
+ code: string;
58
+ message: string;
51
59
  }
52
- interface WSCmdPayload {
53
- sender: string;
54
- command: string;
60
+ interface DirectPayload<T = unknown> {
61
+ action: string;
62
+ payload?: T;
55
63
  }
56
- interface WSNotifyData {
64
+ interface NotifyPayload {
57
65
  title?: string;
58
66
  icon?: string;
59
67
  body: string;
60
68
  }
61
69
  //#endregion
70
+ //#region src/types.d.ts
71
+ declare module '@wuisdk/core' {
72
+ interface WuiPluginMap {
73
+ readonly wss: IWssService;
74
+ }
75
+ }
76
+ declare module '@wuisdk/core' {
77
+ interface WuiEventMap {
78
+ 'wss:connected': void;
79
+ 'wss:disconnected': void;
80
+ }
81
+ }
82
+ interface WssPluginOptions {
83
+ worker: new () => Worker;
84
+ endpoint?: string;
85
+ }
86
+ interface IWssService {
87
+ readonly wsuuid: string;
88
+ post(packet: WSMessage): void;
89
+ direct(targetId: string, data: DirectPayload): void;
90
+ publish(topic: WSTopic, data: unknown): void;
91
+ subscribe<T>(topic: WSTopic, callback: (message: T) => void, signal?: AbortSignal): () => void;
92
+ }
93
+ //#endregion
62
94
  //#region src/service.d.ts
63
95
  export declare class WuiWssPlugin implements WuiPlugin {
64
96
  private options;
@@ -76,4 +108,4 @@ export declare const info: () => {
76
108
  name: string;
77
109
  };
78
110
  //#endregion
79
- export type { IWssService, WSCmdPayload, WSLogsData, WSNotifyData, WSPacket, WSParams, WSPubSub, WSTimeData, WSTopic, WssPluginOptions };
111
+ export type { AckPayload, DirectPayload, ErrorPayload, IWssService, LogsPayload, NotifyPayload, TimePayload, WSMessage, WSMeta, WSParams, WSTarget, WSTopic, WssPluginOptions };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import"@wuisdk/plugin-auth";var e=`@wuisdk/plugin-wss`,t=`0.1.11`,n=class{options;name=`wui-wss-plugin`;service;constructor(e){this.options=e}install(e){this.service=new r(e,this.options),e.registerPlugin(`wss`,this.service)}init(){this.service.init()}destroy(){this.service.destroy()}},r=class{ctx;options;abortController=new AbortController;worker=null;_wsuuid=null;subscribers=/* @__PURE__ */ new Map;constructor(e,t){this.ctx=e,this.options=t}init(){if(!window.Worker){console.warn(`[WssService] Web Workers not supported.`);return}if(!this.options.worker){console.warn(`[WssService] Missing Worker configuration.`);return}let{config:e}=this.ctx,{signal:t}=this.abortController;this.worker=new this.options.worker,this.worker.addEventListener(`message`,e=>{let{head:t,data:n}=e.data;switch(t){case`ACCEPT`:this.handleAccept(n);break;case`DISCON`:this.handleDisconnect();break;case`VERIFY`:console.log(`🐸`,t,n);break;case`KEYEXP`:this.handleKeyExp();break;case`DIRECT`:this.handleDirect(n)}let r=this.subscribers.get(t);r&&r.forEach(e=>e(n))},{signal:t});let n={head:`INIT`,data:{url:this.options.endpoint??`wss://wkrh.info/wss`,app:e.appName,uid:e.appCode,ver:e.version,rel:e.release}};this.worker.postMessage(n)}destroy(){this.abortController.abort(),this.worker?.terminate(),this.worker=null}get wsuuid(){return this._wsuuid??``}post(e){if(!this.worker){console.warn(`[WssService] Worker not initialized`);return}this.worker.postMessage(e)}direct(e,t){let n={head:`DIRECT`,data:{target:e,payload:t}};this.post(n)}publish(e,t){let n={head:e,data:{payload:t}};this.post(n)}subscribe(e,t,n){this.subscribers.has(e)||(this.subscribers.set(e,/* @__PURE__ */ new Set),this._wsuuid&&this.post({head:`SUBSCRIBE`,data:{topic:e}}));let r=this.subscribers.get(e),i=t;r.add(i);let a=!1,o=()=>{if(a)return;a=!0,n&&n.removeEventListener(`abort`,o);let t=this.subscribers.get(e);t&&(t.delete(i),t.size===0&&(this.subscribers.delete(e),this._wsuuid&&this.post({head:`UNSUBSCRIBE`,data:{topic:e}})))};return n&&(n.aborted?o():n.addEventListener(`abort`,o,{once:!0})),o}handleAccept(e){this._wsuuid=e.uuid??``,console.log(`wsuuid:`,this._wsuuid),this.ctx.events.emit(`wss:connected`),this.verifyToken();for(let e of this.subscribers.keys())this.post({head:`SUBSCRIBE`,data:{topic:e}})}handleDisconnect(){this._wsuuid=null,this.ctx.events.emit(`wss:disconnected`)}verifyToken(){let{storage:e}=this.ctx.config,t=localStorage.getItem(e.AUTHKEY);t&&this.post({head:`VERIFY`,data:t})}async handleKeyExp(){if(this.ctx.plugins.auth)try{await this.ctx.plugins.auth.refreshToken(),this.verifyToken()}catch(e){console.warn(`[WssService] Refresh token failed.`,e)}}handleDirect(e){switch(console.log(e),e.command){case`CONRST`:sessionStorage.clear(),window.location.reload();break;case`LOGOUT`:localStorage.clear(),sessionStorage.clear(),window.location.reload()}}};const i=()=>({version:t,name:e.split(`/`)[1]});export{n as WuiWssPlugin,i as info};
1
+ import{t as e}from"./ws.types-9tIaKFzx.js";import"@wuisdk/plugin-auth";var t=`@wuisdk/plugin-wss`,n=`0.1.13`,r=class{options;name=`wui-wss-plugin`;service;constructor(e){this.options=e}install(e){this.service=new i(e,this.options),e.registerPlugin(`wss`,this.service)}init(){this.service.init()}destroy(){this.service.destroy()}},i=class{ctx;options;abortController=new AbortController;worker=null;_wsuuid=null;subscribers=/* @__PURE__ */ new Map;constructor(e,t){this.ctx=e,this.options=t}init(){if(!window.Worker){console.warn(`[WssService] Web Workers not supported.`);return}if(!this.options.worker){console.warn(`[WssService] Missing Worker configuration.`);return}let{config:t}=this.ctx,{signal:n}=this.abortController;this.worker=new this.options.worker,this.worker.addEventListener(`message`,t=>{let{type:n,topic:r,data:i}=t.data;switch(n){case e.Ack:i&&this.handleAckMessage(i);break;case e.Error:i&&this.handleErrorMessage(i);break;case e.Direct:i&&this.handleDirect(i);break;case e.Disconnect:this.handleDisconnect();break;case e.Expired:this.handleExpired()}if(n===e.Event&&r){let e=this.subscribers.get(r);e&&e.forEach(e=>e(t.data))}},{signal:n});let r={type:e.Connect,data:{url:this.options.endpoint??`wss://wkrh.info/wss`,app:t.appName,uid:t.appCode,ver:t.version,rel:t.release}};this.worker.postMessage(r)}destroy(){this.abortController.abort(),this.worker?.terminate(),this.worker=null}get wsuuid(){return this._wsuuid??``}post(e){if(!this.worker){console.warn(`[WssService] Worker not initialized`);return}this.worker.postMessage(e)}direct(t,n){this.post({type:e.Direct,target:{id:t},data:n})}publish(t,n){this.post({type:e.Publish,topic:t,data:n})}subscribe(t,n,r){this.subscribers.has(t)||(this.subscribers.set(t,/* @__PURE__ */ new Set),this._wsuuid&&this.post({type:e.Subscribe,topic:t}));let i=this.subscribers.get(t),a=n;i.add(a);let o=!1,s=()=>{if(o)return;o=!0,r&&r.removeEventListener(`abort`,s);let n=this.subscribers.get(t);n&&(n.delete(a),n.size===0&&(this.subscribers.delete(t),this._wsuuid&&this.post({type:e.Unsubscribe,topic:t})))};return r&&(r.aborted?s():r.addEventListener(`abort`,s,{once:!0})),s}handleAckMessage(e){e.status===`connected`&&e.wsuuid&&this.handleConnected(e.wsuuid),e.status===`verified`&&console.log(`[WSS]`,`🐸Token verified successfully.`)}handleErrorMessage(e){console.log(`[WSS]`,`💥${e.code}: ${e.message}`)}handleConnected(t){this._wsuuid=t,console.log(`wsuuid:`,this._wsuuid),this.ctx.events.emit(`wss:connected`),this.verifyToken();for(let t of this.subscribers.keys())this.post({type:e.Subscribe,topic:t})}handleDisconnect(){this._wsuuid=null,this.ctx.events.emit(`wss:disconnected`)}verifyToken(){let{storage:t}=this.ctx.config,n=localStorage.getItem(t.AUTHKEY);n&&this.post({type:e.Verify,data:{token:n}})}async handleExpired(){if(this.ctx.plugins.auth)try{await this.ctx.plugins.auth.refreshToken(),this.verifyToken()}catch(e){console.warn(`[WssService] Refresh token failed.`,e)}}handleDirect(e){switch(e.action){case`CONRST`:sessionStorage.clear(),window.location.reload();break;case`LOGOUT`:localStorage.clear(),sessionStorage.clear(),window.location.reload();break;case`NOTIFY`:this.handleNotify(e.payload)}}handleNotify(e){let t=e.title??`Hub Notify`,n=e.icon??`https://cdn.jsdelivr.net/gh/wkrdev/assets/img/icon/icon-06.png`,r=e.body??``;Notification.requestPermission().then(e=>{e==`granted`&&new Notification(t,{body:r,icon:n})}).catch(e=>console.error(e))}};const a=()=>({version:n,name:t.split(`/`)[1]});export{e as WSMsgType,r as WuiWssPlugin,a as info};
@@ -0,0 +1 @@
1
+ const e={Subscribe:`SUBSCRIBE`,Unsubscribe:`UNSUBSCRIBE`,Publish:`PUBLISH`,Direct:`DIRECT`,Event:`EVENT`,Ack:`ACK`,Error:`ERROR`,Ping:`PING`,Pong:`PONG`,Connect:`CONNECT`,Disconnect:`DISCONNECT`,Verify:`VERIFY`,Expired:`EXPIRED`};export{e as t};
@@ -1 +1 @@
1
- let e=null,t,n;self.onmessage=t=>{let{head:n,data:i}=t.data;n==`INIT`?r(i):e?.readyState===WebSocket.OPEN&&e.send(JSON.stringify(t.data))};const r=o=>{let{url:s,app:c,uid:l,ver:u,rel:d}=o;if(!s||!c||!l||!u||!d){console.error(`[HubWorker] Invalid parameters`);return}let f=`${s}?app=${c}&uid=${l}&ver=${u}&rel=${d}`;e&&(e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null,e.close()),e=new WebSocket(f),e.onopen=()=>{self.postMessage({head:`SYS_CONNECTED`})},e.onclose=()=>{self.postMessage({head:`DISCON`}),clearInterval(t),clearTimeout(n),n=self.setTimeout(()=>r(o),a())},e.onerror=e=>{console.error(`[HubWorker] WebSocket Error`,e)},e.onmessage=e=>{if(typeof e.data==`string`)try{let t=JSON.parse(e.data);t.head===`ACCEPT`&&i(),self.postMessage(t)}catch(e){console.error(`[HubWorker] Parse Error:`,e)}}},i=()=>{clearInterval(t),t=setInterval(()=>{e&&e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({head:`PING`}))},5e4)},a=()=>Math.floor(Math.random()*20001)+1e4;
1
+ import{t as e}from"./ws.types-9tIaKFzx.js";let t=null,n,r;self.onmessage=n=>{let{type:r,data:a}=n.data;r===e.Connect?i(a):t?.readyState===WebSocket.OPEN&&t.send(JSON.stringify(n.data))};const i=c=>{let{url:l,app:u,uid:d,ver:f,rel:p}=c;if(!l||!u||!d||!f||!p){console.error(`[HubWorker] Invalid parameters`);return}let m=`${l}?app=${u}&uid=${d}&ver=${f}&rel=${p}`;t&&(t.onopen=null,t.onclose=null,t.onerror=null,t.onmessage=null,t.close()),t=new WebSocket(m),t.onopen=()=>{a({type:e.Connect})},t.onclose=()=>{a({type:e.Disconnect}),clearInterval(n),clearTimeout(r),r=self.setTimeout(()=>i(c),s())},t.onerror=e=>{console.error(`[HubWorker] WebSocket Error`,e)},t.onmessage=t=>{if(typeof t.data==`string`)try{let n=JSON.parse(t.data),r=n.data;n.type===e.Ack&&r.status===`connected`&&o(),a(n)}catch(e){console.error(`[HubWorker] Parse Error:`,e)}}},a=e=>self.postMessage(e),o=()=>{clearInterval(n),n=setInterval(()=>{if(t&&t.readyState===WebSocket.OPEN){let n={type:e.Ping};t.send(JSON.stringify(n))}},5e4)},s=()=>Math.floor(Math.random()*20001)+1e4;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wuisdk/plugin-wss",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {