@dnotifier-realtime/dnotifier 1.0.9 → 1.0.11
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/README.md +14 -0
- package/dist/dnotifier.js +1 -0
- package/dist/providers/openai.js +1 -0
- package/dist/transport/httpTransport.js +1 -0
- package/dist/transport/websocketTransport.js +1 -0
- package/dist/utils/buffer.js +1 -0
- package/dist/utils/frame.js +1 -0
- package/dist/utils/id.js +1 -0
- package/dist/utils/payload.js +1 -0
- package/package.json +13 -4
- package/dnotifier-realtime-dnotifier-1.0.0.tgz +0 -0
- package/src/dnotifier.js +0 -345
- package/src/transport/httpTransport.js +0 -33
- package/src/transport/websocketTransport.js +0 -154
- package/src/utils/buffer.js +0 -6
- package/src/utils/frame.js +0 -99
- package/src/utils/id.js +0 -4
- package/src/utils/payload.js +0 -29
package/README.md
CHANGED
|
@@ -70,3 +70,17 @@ notifier.sendBinary({
|
|
|
70
70
|
buffer
|
|
71
71
|
});
|
|
72
72
|
|
|
73
|
+
// --- OpenAI (and compatible APIs) ---
|
|
74
|
+
// Send a message to OpenAI; the model response is delivered to receivers via onMessage.
|
|
75
|
+
// No OpenAI SDK or integration needed on the receiver side.
|
|
76
|
+
|
|
77
|
+
await notifier.sendWithOpenAI({
|
|
78
|
+
senderId: "YOUR-UNIQUE-USERID",
|
|
79
|
+
message: "What is 2 + 2?", // or messages: [{ role: "user", content: "..." }]
|
|
80
|
+
openaiApiKey: process.env.OPENAI_API_KEY,
|
|
81
|
+
model: "gpt-4o-mini", // optional, default gpt-4o-mini
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// SDK streams from OpenAI internally and calls onMessage once with the full response; payload.toJSON():
|
|
85
|
+
// { type: "openai", content: "...", ts: 1234567890 }
|
|
86
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['DNotifier']=void 0x0;const httpTransport_js_1=require('./transport/httpTransport.js'),websocketTransport_js_1=require('./transport/websocketTransport.js'),id_js_1=require('./utils/id.js'),frame_js_1=require('./utils/frame.js'),payload_js_1=require('./utils/payload.js'),buffer_js_1=require('./utils/buffer.js'),openai_js_1=require('./providers/openai.js');class DNotifier{constructor({appId:_0x55ccfe,secret:_0x55db45,transport:_0x2c185f,userId:_0x9cc723,onConnected:_0x45548d,onMessage:_0x580684,onDisconnected:_0x2f1ac5,WebSocketImpl:_0x52f594}){if(!(_0x55ccfe&&_0x55db45&&_0x2c185f&&_0x9cc723))throw new Error('appId,\x20secret,\x20transport,\x20and\x20userId\x20are\x20required');this['appId']=_0x55ccfe,this['secret']=_0x55db45,this['userId']=_0x9cc723,this['url']='wss://link.dchatter.com/ws',this['onConnectedCallback']=_0x45548d||(()=>{}),this['onMessageCallback']=_0x580684||(()=>{}),this['onDisconnectedCallback']=_0x2f1ac5||(()=>{}),this['isConnected']=!0x1,this['transport']='ws'===_0x2c185f?new websocketTransport_js_1['WebsocketTransport'](_0x52f594):new httpTransport_js_1['HttpTransport']();}async['connect'](){const _0x294853=new httpTransport_js_1['HttpTransport']({'url':'https://link.dchatter.com/api/v1/sdk/auth'}),_0x2e4014=await _0x294853['send']({'appId':this['appId'],'appSecret':this['secret'],'userID':this['userId']});if(0xc8!==_0x2e4014['_responseCode'])throw new Error('Authentication\x20Failed.');this['authToken']=_0x2e4014['_responseData'],await this['transport']['connect'](this['url']);const _0x21a1a7={'type':'text','code':0x65,'appId':this['appId'],'sender':(0x0,id_js_1['prefixId'])(this['appId'],this['userId']),'timestamp':Date['now'](),'token':this['authToken']},_0x43ede5=(0x0,buffer_js_1['toUint8'])(JSON['stringify']({'token':this['authToken']})),_0x30647b=(0x0,frame_js_1['framePacket'])(_0x21a1a7,_0x43ede5);this['transport']['sendBinary'](_0x30647b);let _0x38ce64=!0x1;this['transport']['on']('message',_0x1e8b4e=>{try{const {metadata:_0x597aa3,data:_0x16124f}=_0x1e8b4e;if(!_0x38ce64&&'102'===_0x597aa3['packet']['code']&&_0x597aa3['packet']['sender']['includes']((0x0,id_js_1['prefixId'])(this['appId'],this['userId'])))return _0x38ce64=!0x0,this['isConnected']=!0x0,void this['onConnectedCallback']();_0x38ce64&&this['onMessageCallback']({'metadata':{'sender':_0x597aa3['packet']['sender'],'timestamp':_0x597aa3['packet']['timestamp']},'payload':new payload_js_1['Payload'](_0x16124f)});}catch(_0x51ce15){console['error']('Packet\x20error:',_0x51ce15);}}),this['transport']['on']('close',({code:_0x592aa5,reason:_0x400b5f})=>{this['isConnected']&&(this['isConnected']=!0x1,this['onDisconnectedCallback']({'code':_0x592aa5,'reason':_0x400b5f||'Disconnected'}));}),this['transport']['on']('error',_0x2addf4=>{this['isConnected']=!0x1,this['onDisconnectedCallback']({'code':0x1f4,'reason':(null==_0x2addf4?void 0x0:_0x2addf4['message'])||'Transport\x20error'});});}['send']({senderId:_0xbb2b98,receiverId:_0x587b94,receiverIds:_0x4f2ad1,data:_0x47fd1b}){if(!_0xbb2b98)throw new Error('senderId\x20required');if(!_0x587b94&&!_0x4f2ad1)throw new Error('receiverId\x20or\x20receiverIds\x20required');const _0x25a95d=null!=_0x4f2ad1?_0x4f2ad1:[_0x587b94],_0x1a25d0={'type':'text','code':0xc8,'appId':this['appId'],'sender':(0x0,id_js_1['prefixId'])(this['appId'],_0xbb2b98),'receivers':_0x25a95d['map'](_0x12f457=>(0x0,id_js_1['prefixId'])(this['appId'],_0x12f457)),'timestamp':Date['now'](),'token':this['authToken']},_0x402db7=(0x0,buffer_js_1['toUint8'])(JSON['stringify'](_0x47fd1b)),_0x345582=(0x0,frame_js_1['framePacket'])(_0x1a25d0,_0x402db7);this['transport']['sendBinary'](_0x345582);}['sendBinary']({senderId:_0x582f42,receiverIds:_0x47ed85,buffer:_0x1fd5f3,type:_0x216758='binary'}){if(!_0x582f42)throw new Error('senderId\x20required');if(!_0x1fd5f3)throw new Error('buffer\x20is\x20required');const _0x3312de={'type':_0x216758,'code':0xca,'appId':this['appId'],'sender':(0x0,id_js_1['prefixId'])(this['appId'],_0x582f42),'receivers':_0x47ed85['map'](_0x22e60e=>(0x0,id_js_1['prefixId'])(this['appId'],_0x22e60e)),'timestamp':Date['now'](),'token':this['authToken']},_0x25278b=(0x0,frame_js_1['framePacket'])(_0x3312de,_0x1fd5f3);this['transport']['sendBinary'](_0x25278b);}async['sendWithOpenAI']({senderId:_0xdaa33d,message:_0x2bb693,openaiApiKey:_0x5ad29f,model:_0x5632b4,baseUrl:_0x2d9ec3}){if(!_0xdaa33d)throw new Error('senderId\x20is\x20required');if(!_0x2bb693)throw new Error('message\x20is\x20required');if(!_0x5ad29f)throw new Error('openaiApiKey\x20is\x20required');const {content:_0x68fdaa}=await(0x0,openai_js_1['chatStream'])({'apiKey':_0x5ad29f,'model':_0x5632b4,'messages':_0x2bb693,'baseUrl':_0x2d9ec3}),_0x28073f={'type':'openai','content':_0x68fdaa,'ts':Date['now']()};return this['onMessageCallback']({'metadata':{'sender':(0x0,id_js_1['prefixId'])(this['appId'],_0xdaa33d),'timestamp':Date['now']()},'payload':new payload_js_1['Payload']((0x0,buffer_js_1['toUint8'])(JSON['stringify'](_0x28073f)))}),{'content':_0x68fdaa};}}exports['DNotifier']=DNotifier;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['chat']=chat,exports['chatStream']=chatStream;const DEFAULT_BASE_URL='https://api.openai.com',DEFAULT_MODEL='gpt-4o-mini';function normalizeMessages(_0x50abb1){if('string'==typeof _0x50abb1)return[{'role':'user','content':_0x50abb1}];if(Array['isArray'](_0x50abb1)&&_0x50abb1['length']>0x0)return _0x50abb1['map'](_0x5544c1=>({'role':_0x5544c1['role']||'user','content':'string'==typeof _0x5544c1['content']?_0x5544c1['content']:String(_0x5544c1['content'])}));throw new Error('message\x20must\x20be\x20a\x20non-empty\x20string\x20or\x20array\x20of\x20{\x20role,\x20content\x20}');}async function chat(_0x4b4d75){var _0x3dca58,_0x3b77bc,_0x14b95d,_0x3a24f4,_0x34ad9b,_0x323132;const {apiKey:_0x12cccb,model:_0x20d43d=DEFAULT_MODEL,messages:_0x33cee3,baseUrl:_0x7b60b9=DEFAULT_BASE_URL}=_0x4b4d75;if(!_0x12cccb||!_0x33cee3)throw new Error('openai.chat:\x20apiKey\x20and\x20messages\x20are\x20required');const _0x20c6ff=_0x7b60b9['replace'](/\/$/,'')+'/v1/chat/completions',_0x26f01b={'model':_0x20d43d,'messages':normalizeMessages(_0x33cee3),'stream':!0x1},_0x5f3935=await fetch(_0x20c6ff,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+_0x12cccb},'body':JSON['stringify'](_0x26f01b)}),_0x128491=await _0x5f3935['json']();if(!_0x5f3935['ok']){const _0x1ae56d=new Error((null===(_0x3dca58=null==_0x128491?void 0x0:_0x128491['error'])||void 0x0===_0x3dca58?void 0x0:_0x3dca58['message'])||'OpenAI\x20API\x20error:\x20'+_0x5f3935['status']);throw _0x1ae56d['status']=_0x5f3935['status'],_0x1ae56d['code']=null===(_0x3b77bc=null==_0x128491?void 0x0:_0x128491['error'])||void 0x0===_0x3b77bc?void 0x0:_0x3b77bc['code'],_0x1ae56d;}return{'content':null!==(_0x323132=null===(_0x34ad9b=null===(_0x3a24f4=null===(_0x14b95d=null==_0x128491?void 0x0:_0x128491['choices'])||void 0x0===_0x14b95d?void 0x0:_0x14b95d[0x0])||void 0x0===_0x3a24f4?void 0x0:_0x3a24f4['message'])||void 0x0===_0x34ad9b?void 0x0:_0x34ad9b['content'])&&void 0x0!==_0x323132?_0x323132:'','usage':null==_0x128491?void 0x0:_0x128491['usage'],'raw':_0x128491};}async function chatStream(_0x4bc918){var _0xcba38b,_0x3dc6f9,_0x5c12d9,_0x43072b,_0x54133a;const {apiKey:_0x33bc26,model:_0x1373d8=DEFAULT_MODEL,messages:_0x3881f5,baseUrl:_0x1fa013=DEFAULT_BASE_URL,onChunk:_0x367a69}=_0x4bc918;if(!_0x33bc26||!_0x3881f5)throw new Error('openai.chatStream:\x20apiKey\x20and\x20messages\x20are\x20required');const _0x40ee40=_0x1fa013['replace'](/\/$/,'')+'/v1/chat/completions',_0xf0f0a5={'model':_0x1373d8,'messages':normalizeMessages(_0x3881f5),'stream':!0x0},_0x2e0ab5=await fetch(_0x40ee40,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+_0x33bc26},'body':JSON['stringify'](_0xf0f0a5)});if(!_0x2e0ab5['ok']){const _0x1f9364=await _0x2e0ab5['json']()['catch'](()=>({})),_0x3978de=new Error((null===(_0xcba38b=null==_0x1f9364?void 0x0:_0x1f9364['error'])||void 0x0===_0xcba38b?void 0x0:_0xcba38b['message'])||'OpenAI\x20API\x20error:\x20'+_0x2e0ab5['status']);throw _0x3978de['status']=_0x2e0ab5['status'],_0x3978de['code']=null===(_0x3dc6f9=null==_0x1f9364?void 0x0:_0x1f9364['error'])||void 0x0===_0x3dc6f9?void 0x0:_0x3dc6f9['code'],_0x3978de;}const _0x16e1c4=_0x2e0ab5['body']['getReader'](),_0x1e8620=new TextDecoder();let _0x31d6cb='',_0x2b690e='';for(;;){const {done:_0x59c879,value:_0x3fba43}=await _0x16e1c4['read']();if(_0x59c879)break;_0x2b690e+=_0x1e8620['decode'](_0x3fba43,{'stream':!0x0});const _0x4f56f3=_0x2b690e['split']('\x0a');_0x2b690e=_0x4f56f3['pop']()||'';for(const _0x3dbef4 of _0x4f56f3){const _0x2ae682=_0x3dbef4['trim']();if(''!==_0x2ae682&&'data:\x20[DONE]'!==_0x2ae682&&_0x2ae682['startsWith']('data:\x20'))try{const _0x25f8aa=JSON['parse'](_0x2ae682['slice'](0x6)),_0xdc0ab=null===(_0x54133a=null===(_0x43072b=null===(_0x5c12d9=null==_0x25f8aa?void 0x0:_0x25f8aa['choices'])||void 0x0===_0x5c12d9?void 0x0:_0x5c12d9[0x0])||void 0x0===_0x43072b?void 0x0:_0x43072b['delta'])||void 0x0===_0x54133a?void 0x0:_0x54133a['content'];'string'==typeof _0xdc0ab&&(_0x31d6cb+=_0xdc0ab,_0x367a69&&_0x367a69(_0xdc0ab));}catch(_0x3c5f9a){}}}return{'content':_0x31d6cb};}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['HttpTransport']=void 0x0;class HttpTransport{constructor({url:_0x5980be}){this['url']=_0x5980be;}async['send'](_0x4a3fe0){const _0x1c0707=await fetch(''+this['url'],{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](_0x4a3fe0)});if(!_0x1c0707['ok']){const _0x297ded=await _0x1c0707['text']();throw new Error('DNotifier\x20HTTP\x20error:\x20'+_0x297ded);}return await _0x1c0707['json']();}['sendBinary'](){throw new Error('Binary\x20is\x20not\x20supported\x20over\x20HTTP\x20yet');}}exports['HttpTransport']=HttpTransport;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['WebsocketTransport']=void 0x0;const events_1=require('events'),frame_js_1=require('../utils/frame.js');class WebsocketTransport extends events_1['default']{constructor(_0x153d87=null){if(super(),this['socket']=null,this['WebSocketImpl']=_0x153d87||('undefined'!=typeof window?window['WebSocket']:null),!this['WebSocketImpl'])throw new Error('No\x20WebSocket\x20implementation\x20provided');}['connect'](_0x1f8043){return new Promise((_0x3981bb,_0x316d9a)=>{this['socket']=new this['WebSocketImpl'](_0x1f8043),'undefined'!=typeof window&&(this['socket']['binaryType']='arrayBuffer'),this['_on']('open',()=>_0x3981bb(!0x0)),this['_on']('error',_0x15a099=>{console['error']('WS\x20error',_0x15a099),_0x316d9a(_0x15a099);}),this['_on']('close',_0x426081=>{const _0x542531=null==_0x426081?void 0x0:_0x426081['code'],_0x30a788=null==_0x426081?void 0x0:_0x426081['reason'];this['emit']('close',{'code':_0x542531,'reason':_0x30a788});}),this['_on']('message',async(_0x4e1027,_0x47cac6)=>{var _0x60ca4c,_0x94b066=null!==(_0x60ca4c=null==_0x4e1027?void 0x0:_0x4e1027['data'])&&void 0x0!==_0x60ca4c?_0x60ca4c:_0x4e1027;'undefined'!=typeof Blob&&_0x94b066 instanceof Blob&&(_0x94b066=await _0x94b066['arrayBuffer']());const _0x2e5a70=(0x0,frame_js_1['decodePacket'])(_0x94b066);_0x2e5a70&&this['emit']('message',_0x2e5a70,_0x47cac6);});});}['_on'](_0x3207df,_0x1a711a){this['socket']['on']?this['socket']['on'](_0x3207df,_0x1a711a):this['socket']['on'+_0x3207df]=_0x1a711a;}['send'](_0x2fb390){if(!this['isOpen']())throw new Error('WebSocket\x20not\x20connected');this['socket']['send'](_0x2fb390);}['sendBinary'](_0x3b96e6){if(!this['isOpen']())throw new Error('WebSocket\x20not\x20connected');this['socket']['send'](_0x3b96e6);}['isOpen'](){return this['socket']&&this['socket']['readyState']===this['WebSocketImpl']['OPEN'];}['close'](){var _0x512a0b;null===(_0x512a0b=this['socket'])||void 0x0===_0x512a0b||_0x512a0b['close']();}}exports['WebsocketTransport']=WebsocketTransport;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';function toUint8(_0x494c76){return'undefined'!=typeof Buffer?Buffer['from'](_0x494c76,'utf8'):new TextEncoder()['encode'](_0x494c76);}Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['toUint8']=toUint8;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';function framePacket(_0x3889b8,_0x28bd73){const _0x146587=Buffer['from'](JSON['stringify'](_0x3889b8)),_0x29210b=Buffer['isBuffer'](_0x28bd73)?_0x28bd73:Buffer['from'](_0x28bd73),_0x4f7379=Buffer['alloc'](0x4+_0x146587['length']+0x4+_0x29210b['length']);let _0x42f4ec=0x0;return _0x4f7379['writeUInt32BE'](_0x146587['length'],_0x42f4ec),_0x42f4ec+=0x4,_0x146587['copy'](_0x4f7379,_0x42f4ec),_0x42f4ec+=_0x146587['length'],_0x4f7379['writeUInt32BE'](_0x29210b['length'],_0x42f4ec),_0x42f4ec+=0x4,_0x29210b['copy'](_0x4f7379,_0x42f4ec),_0x4f7379;}Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['framePacket']=framePacket,exports['decodePacket']=decodePacket;let internalBuffer=Buffer['alloc'](0x0);function decodePacket(_0x50c16c){try{Buffer['isBuffer'](_0x50c16c)||(_0x50c16c=Buffer['from'](_0x50c16c)),internalBuffer=Buffer['concat']([internalBuffer,_0x50c16c]);let _0x45d6ff=0x0;if(internalBuffer['length']<0x4)return null;const _0x1b5353=internalBuffer['readUInt32BE'](_0x45d6ff);if(_0x45d6ff+=0x4,internalBuffer['length']<_0x45d6ff+_0x1b5353)return null;const _0x119970=internalBuffer['slice'](_0x45d6ff,_0x45d6ff+_0x1b5353),_0x5855fe=JSON['parse'](_0x119970['toString']());if(_0x45d6ff+=_0x1b5353,internalBuffer['length']<_0x45d6ff+0x4)return null;const _0x1941f2=internalBuffer['readUInt32BE'](_0x45d6ff);if(_0x45d6ff+=0x4,internalBuffer['length']<_0x45d6ff+_0x1941f2)return null;const _0x5f4a25=internalBuffer['slice'](_0x45d6ff,_0x45d6ff+_0x1941f2);_0x45d6ff+=_0x1941f2,internalBuffer=internalBuffer['slice'](_0x45d6ff);let _0x5dc8fd=_0x5f4a25;if('text'===_0x5855fe['type'])try{_0x5dc8fd=JSON['parse'](_0x5f4a25['toString']('utf8'));}catch{_0x5dc8fd=_0x5f4a25;}return{'metadata':_0x5855fe,'data':_0x5dc8fd};}catch(_0x349459){return console['error']('decodePacket\x20error:',_0x349459),null;}}
|
package/dist/utils/id.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['prefixId']=void 0x0;const prefixId=(_0x55e479,_0x3a62bc)=>_0x3a62bc['includes'](':')?_0x3a62bc:_0x55e479+':'+_0x3a62bc;exports['prefixId']=prefixId;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['Payload']=void 0x0;class Payload{constructor(_0x19890c){this['buffer']=_0x19890c;}['raw'](){return this['buffer'];}['toString'](_0x3a8f53='utf8'){return this['buffer']['toString'](_0x3a8f53);}['toJSON'](_0x16d800='utf8'){try{return JSON['parse'](this['buffer']['toString'](_0x16d800));}catch(_0x8602d8){return null;}}['toBase64'](){return this['buffer']['toString']('base64');}}exports['Payload']=Payload;
|
package/package.json
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dnotifier-realtime/dnotifier",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.11",
|
|
4
4
|
"description": "Real-time notification & messaging SDK",
|
|
5
|
-
"main": "
|
|
5
|
+
"main": "dist/dnotifier.js",
|
|
6
|
+
"files": [
|
|
7
|
+
"dist"
|
|
8
|
+
],
|
|
6
9
|
"type": "module",
|
|
7
10
|
"keywords": [
|
|
8
11
|
"dnotifier",
|
|
@@ -22,10 +25,16 @@
|
|
|
22
25
|
"dependencies": {
|
|
23
26
|
"ws": "^8.19.0"
|
|
24
27
|
},
|
|
25
|
-
"devDependencies": {
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"javascript-obfuscator": "^4.1.1",
|
|
30
|
+
"terser": "^5.36.0",
|
|
31
|
+
"typescript": "^5.9.3"
|
|
32
|
+
},
|
|
26
33
|
"scripts": {
|
|
27
34
|
"test": "echo \"Error: no test specified\" && exit 1",
|
|
28
|
-
"start"
|
|
35
|
+
"start": "node index.js",
|
|
36
|
+
"build": "tsc",
|
|
37
|
+
"publishprod": "node scripts/publish-prod.js"
|
|
29
38
|
},
|
|
30
39
|
"homepage": "https://dnotifier.com"
|
|
31
40
|
}
|
|
Binary file
|
package/src/dnotifier.js
DELETED
|
@@ -1,345 +0,0 @@
|
|
|
1
|
-
// import { HttpTransport } from "./transport/httpTransport.js";
|
|
2
|
-
// import { WebsocketTransport } from "./transport/websocketTransport.js";
|
|
3
|
-
// import { prefixId } from "./utils/id.js";
|
|
4
|
-
// import { framePacket, decodePacket } from "./utils/frame.js";
|
|
5
|
-
// import {Payload} from './utils/payload.js'
|
|
6
|
-
// // import { decodePacket } from "./utils/decode.js";
|
|
7
|
-
|
|
8
|
-
// export class DNotifier {
|
|
9
|
-
// /**
|
|
10
|
-
// * @param {Object} options
|
|
11
|
-
// * @param {string} options.appId
|
|
12
|
-
// * @param {string} options.secret
|
|
13
|
-
// * @param {string} options.transport - "ws" or "http"
|
|
14
|
-
// * @param {string} options.userId
|
|
15
|
-
// * @param {function} options.onConnected - callback when handshake is done
|
|
16
|
-
// * @param {function} options.onMessage - callback for all subsequent messages
|
|
17
|
-
// * @param {function} options.onDisconnected - callback when disconnection happens
|
|
18
|
-
// *
|
|
19
|
-
// */
|
|
20
|
-
// constructor({ appId, secret, transport, userId, onConnected, onMessage, onDisconnected }) {
|
|
21
|
-
// if (!appId || !secret || !transport || !userId) {
|
|
22
|
-
// throw new Error("appId, secret, transport, and userId are required");
|
|
23
|
-
// }
|
|
24
|
-
|
|
25
|
-
// this.appId = appId;
|
|
26
|
-
// this.secret = secret;
|
|
27
|
-
// this.userId = userId;
|
|
28
|
-
// this.url = "ws://127.0.0.1:7072";
|
|
29
|
-
|
|
30
|
-
// this.onConnectedCallback = onConnected || (() => {});
|
|
31
|
-
// this.onMessageCallback = onMessage || (() => {});
|
|
32
|
-
// this.onDisconnectedCallback = onDisconnected || (() => {});
|
|
33
|
-
|
|
34
|
-
// this.isConnected = false;
|
|
35
|
-
|
|
36
|
-
// this.transport =
|
|
37
|
-
// transport === "ws" ? new WebsocketTransport() : new HttpTransport();
|
|
38
|
-
// }
|
|
39
|
-
|
|
40
|
-
// async connect() {
|
|
41
|
-
// // Step 1: Authenticate with Auth server
|
|
42
|
-
// const authServer = new HttpTransport({
|
|
43
|
-
// url: "https://link.dchatter.com/api/v1/sdk/auth",
|
|
44
|
-
// });
|
|
45
|
-
|
|
46
|
-
// const res = await authServer.send({
|
|
47
|
-
// appId: this.appId,
|
|
48
|
-
// appSecret: this.secret,
|
|
49
|
-
// userID: this.userId,
|
|
50
|
-
// });
|
|
51
|
-
|
|
52
|
-
// if (res._responseCode !== 200) {
|
|
53
|
-
// throw new Error("Authentication Failed.");
|
|
54
|
-
// }
|
|
55
|
-
// this.authToken = res._responseData;
|
|
56
|
-
|
|
57
|
-
// // Step 2: Connect WebSocket
|
|
58
|
-
// await this.transport.connect(this.url);
|
|
59
|
-
|
|
60
|
-
// // Step 3: Send handshake packet
|
|
61
|
-
// const metadata = {
|
|
62
|
-
// type: "text",
|
|
63
|
-
// code: 101, // handshake
|
|
64
|
-
// appId: this.appId,
|
|
65
|
-
// sender: prefixId(this.appId, this.userId),
|
|
66
|
-
// timestamp: Date.now(),
|
|
67
|
-
// };
|
|
68
|
-
// const payloadBuffer = Buffer.from(JSON.stringify({ token : this.authToken+ "123" }), "utf8");
|
|
69
|
-
// const frame = framePacket(metadata, payloadBuffer);
|
|
70
|
-
|
|
71
|
-
// this.transport.sendBinary(frame);
|
|
72
|
-
|
|
73
|
-
// // Step 4: Listen for all incoming messages
|
|
74
|
-
// let handshakeProcessed = false;
|
|
75
|
-
|
|
76
|
-
// // Flag to ignore handshake response
|
|
77
|
-
// let handshakeDone = false;
|
|
78
|
-
|
|
79
|
-
// this.transport.on("message", (chunk) => {
|
|
80
|
-
// try {
|
|
81
|
-
|
|
82
|
-
// const metadata = chunk.metadata
|
|
83
|
-
// const data = chunk.data;
|
|
84
|
-
|
|
85
|
-
// // Handle handshake response internally
|
|
86
|
-
// if (!handshakeProcessed && metadata.packet.code === '102' && metadata.packet.sender.includes(prefixId(this.appId, this.userId))) {
|
|
87
|
-
// handshakeProcessed = true;
|
|
88
|
-
// this.isConnected = true;
|
|
89
|
-
// handshakeDone = true;
|
|
90
|
-
// this.onConnectedCallback(); // notify developer
|
|
91
|
-
|
|
92
|
-
// return; // do NOT forward handshake packet
|
|
93
|
-
// }
|
|
94
|
-
// // Forward all other messages to developer
|
|
95
|
-
// if (handshakeDone && this.onMessageCallback) {
|
|
96
|
-
// this.onMessageCallback({
|
|
97
|
-
// metadata : {
|
|
98
|
-
// sender : metadata.packet.sender,
|
|
99
|
-
// timestamp : metadata.packet.timestamp,
|
|
100
|
-
// },
|
|
101
|
-
// payload: new Payload(data)
|
|
102
|
-
// });
|
|
103
|
-
|
|
104
|
-
// }
|
|
105
|
-
// } catch (err) {
|
|
106
|
-
// console.error("Error decoding packet:", err);
|
|
107
|
-
// }
|
|
108
|
-
// });
|
|
109
|
-
|
|
110
|
-
// this.transport.on("close", ({ code, reason }) => {
|
|
111
|
-
// if (this.isConnected) {
|
|
112
|
-
// this.isConnected = false;
|
|
113
|
-
|
|
114
|
-
// this.onDisconnectedCallback({
|
|
115
|
-
// code,
|
|
116
|
-
// reason: reason?.toString?.() || "Disconnected"
|
|
117
|
-
// });
|
|
118
|
-
// }
|
|
119
|
-
// });
|
|
120
|
-
|
|
121
|
-
// this.transport.on("error", (err) => {
|
|
122
|
-
// this.isConnected = false;
|
|
123
|
-
|
|
124
|
-
// this.onDisconnectedCallback({
|
|
125
|
-
// code,
|
|
126
|
-
// reason: reason?.toString?.() || "Disconnected"
|
|
127
|
-
// });
|
|
128
|
-
// });
|
|
129
|
-
|
|
130
|
-
// }
|
|
131
|
-
|
|
132
|
-
// send({ senderId, receiverId, receiverIds, data }) {
|
|
133
|
-
// if (!senderId) throw new Error("senderId required");
|
|
134
|
-
// if (!receiverId && !receiverIds)
|
|
135
|
-
// throw new Error("receiverId or receiverIds required");
|
|
136
|
-
|
|
137
|
-
// const receivers = receiverIds ?? [receiverId];
|
|
138
|
-
|
|
139
|
-
// const metadata = {
|
|
140
|
-
// type: "text",
|
|
141
|
-
// code: 200, // message
|
|
142
|
-
// appId: this.appId,
|
|
143
|
-
// sender: prefixId(this.appId, senderId),
|
|
144
|
-
// receivers: receivers.map((id) => prefixId(this.appId, id)),
|
|
145
|
-
// timestamp: Date.now(),
|
|
146
|
-
// };
|
|
147
|
-
|
|
148
|
-
// const payloadBuffer = Buffer.from(JSON.stringify(data), "utf8");
|
|
149
|
-
// const frame = framePacket(metadata, payloadBuffer);
|
|
150
|
-
|
|
151
|
-
// this.transport.sendBinary(frame);
|
|
152
|
-
// }
|
|
153
|
-
|
|
154
|
-
// sendBinary({ senderId, receiverIds, buffer, type = "binary" }) {
|
|
155
|
-
// if (!senderId) throw new Error("senderId required");
|
|
156
|
-
// if (!buffer) throw new Error("buffer is required");
|
|
157
|
-
|
|
158
|
-
// const metadata = {
|
|
159
|
-
// type,
|
|
160
|
-
// code: 202, // binary stream
|
|
161
|
-
// appId: this.appId,
|
|
162
|
-
// sender: prefixId(this.appId, senderId),
|
|
163
|
-
// receivers: receiverIds.map((id) => prefixId(this.appId, id)),
|
|
164
|
-
// timestamp: Date.now(),
|
|
165
|
-
// };
|
|
166
|
-
|
|
167
|
-
// const frame = framePacket(metadata, buffer);
|
|
168
|
-
|
|
169
|
-
// this.transport.sendBinary(frame);
|
|
170
|
-
// }
|
|
171
|
-
// }
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
import { HttpTransport } from "./transport/httpTransport.js";
|
|
175
|
-
import { WebsocketTransport } from "./transport/websocketTransport.js";
|
|
176
|
-
import { prefixId } from "./utils/id.js";
|
|
177
|
-
import { framePacket } from "./utils/frame.js";
|
|
178
|
-
import { Payload } from "./utils/payload.js";
|
|
179
|
-
import { toUint8 } from "./utils/buffer.js";
|
|
180
|
-
|
|
181
|
-
export class DNotifier {
|
|
182
|
-
constructor({
|
|
183
|
-
appId,
|
|
184
|
-
secret,
|
|
185
|
-
transport,
|
|
186
|
-
userId,
|
|
187
|
-
onConnected,
|
|
188
|
-
onMessage,
|
|
189
|
-
onDisconnected,
|
|
190
|
-
WebSocketImpl, // 👈 OPTIONAL injection
|
|
191
|
-
}) {
|
|
192
|
-
if (!appId || !secret || !transport || !userId) {
|
|
193
|
-
throw new Error("appId, secret, transport, and userId are required");
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
this.appId = appId;
|
|
197
|
-
this.secret = secret;
|
|
198
|
-
this.userId = userId;
|
|
199
|
-
// this.url = "wss://34.208.142.201/ws:7072";
|
|
200
|
-
this.url = "wss://link.dchatter.com/ws";
|
|
201
|
-
|
|
202
|
-
this.onConnectedCallback = onConnected || (() => {});
|
|
203
|
-
this.onMessageCallback = onMessage || (() => {});
|
|
204
|
-
this.onDisconnectedCallback = onDisconnected || (() => {});
|
|
205
|
-
|
|
206
|
-
this.isConnected = false;
|
|
207
|
-
|
|
208
|
-
this.transport =
|
|
209
|
-
transport === "ws"
|
|
210
|
-
? new WebsocketTransport(WebSocketImpl)
|
|
211
|
-
: new HttpTransport();
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
async connect() {
|
|
215
|
-
// Step 1: Authenticate
|
|
216
|
-
const authServer = new HttpTransport({
|
|
217
|
-
url: "https://link.dchatter.com/api/v1/sdk/auth",
|
|
218
|
-
});
|
|
219
|
-
|
|
220
|
-
const res = await authServer.send({
|
|
221
|
-
appId: this.appId,
|
|
222
|
-
appSecret: this.secret,
|
|
223
|
-
userID: this.userId,
|
|
224
|
-
});
|
|
225
|
-
|
|
226
|
-
if (res._responseCode !== 200) {
|
|
227
|
-
throw new Error("Authentication Failed.");
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
this.authToken = res._responseData;
|
|
231
|
-
|
|
232
|
-
// Step 2: WebSocket connect
|
|
233
|
-
await this.transport.connect(this.url);
|
|
234
|
-
|
|
235
|
-
// Step 3: Handshake
|
|
236
|
-
const metadata = {
|
|
237
|
-
type: "text",
|
|
238
|
-
code: 101,
|
|
239
|
-
appId: this.appId,
|
|
240
|
-
sender: prefixId(this.appId, this.userId),
|
|
241
|
-
timestamp: Date.now(),
|
|
242
|
-
};
|
|
243
|
-
|
|
244
|
-
const payloadBuffer = toUint8(
|
|
245
|
-
JSON.stringify({ token: this.authToken })
|
|
246
|
-
);
|
|
247
|
-
|
|
248
|
-
const frame = framePacket(metadata, payloadBuffer);
|
|
249
|
-
this.transport.sendBinary(frame);
|
|
250
|
-
|
|
251
|
-
let handshakeDone = false;
|
|
252
|
-
|
|
253
|
-
this.transport.on("message", (chunk) => {
|
|
254
|
-
try {
|
|
255
|
-
const { metadata, data } = chunk;
|
|
256
|
-
|
|
257
|
-
if (
|
|
258
|
-
!handshakeDone &&
|
|
259
|
-
metadata.packet.code === "102" &&
|
|
260
|
-
metadata.packet.sender.includes(
|
|
261
|
-
prefixId(this.appId, this.userId)
|
|
262
|
-
)
|
|
263
|
-
) {
|
|
264
|
-
handshakeDone = true;
|
|
265
|
-
this.isConnected = true;
|
|
266
|
-
this.onConnectedCallback();
|
|
267
|
-
return;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
if (handshakeDone) {
|
|
271
|
-
this.onMessageCallback({
|
|
272
|
-
metadata: {
|
|
273
|
-
sender: metadata.packet.sender,
|
|
274
|
-
timestamp: metadata.packet.timestamp,
|
|
275
|
-
},
|
|
276
|
-
payload: new Payload(data),
|
|
277
|
-
});
|
|
278
|
-
}
|
|
279
|
-
} catch (err) {
|
|
280
|
-
console.error("Packet error:", err);
|
|
281
|
-
}
|
|
282
|
-
});
|
|
283
|
-
|
|
284
|
-
this.transport.on("close", ({ code, reason }) => {
|
|
285
|
-
if (this.isConnected) {
|
|
286
|
-
this.isConnected = false;
|
|
287
|
-
this.onDisconnectedCallback({
|
|
288
|
-
code,
|
|
289
|
-
reason: reason || "Disconnected",
|
|
290
|
-
});
|
|
291
|
-
}
|
|
292
|
-
});
|
|
293
|
-
|
|
294
|
-
this.transport.on("error", (err) => {
|
|
295
|
-
this.isConnected = false;
|
|
296
|
-
this.onDisconnectedCallback({
|
|
297
|
-
code: 500,
|
|
298
|
-
reason: err?.message || "Transport error",
|
|
299
|
-
});
|
|
300
|
-
});
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
send({ senderId, receiverId, receiverIds, data }) {
|
|
304
|
-
if (!senderId) throw new Error("senderId required");
|
|
305
|
-
if (!receiverId && !receiverIds)
|
|
306
|
-
throw new Error("receiverId or receiverIds required");
|
|
307
|
-
|
|
308
|
-
const receivers = receiverIds ?? [receiverId];
|
|
309
|
-
|
|
310
|
-
const metadata = {
|
|
311
|
-
type: "text",
|
|
312
|
-
code: 200,
|
|
313
|
-
appId: this.appId,
|
|
314
|
-
sender: prefixId(this.appId, senderId),
|
|
315
|
-
receivers: receivers.map((id) =>
|
|
316
|
-
prefixId(this.appId, id)
|
|
317
|
-
),
|
|
318
|
-
timestamp: Date.now(),
|
|
319
|
-
};
|
|
320
|
-
|
|
321
|
-
const payloadBuffer = toUint8(JSON.stringify(data));
|
|
322
|
-
const frame = framePacket(metadata, payloadBuffer);
|
|
323
|
-
|
|
324
|
-
this.transport.sendBinary(frame);
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
sendBinary({ senderId, receiverIds, buffer, type = "binary" }) {
|
|
328
|
-
if (!senderId) throw new Error("senderId required");
|
|
329
|
-
if (!buffer) throw new Error("buffer is required");
|
|
330
|
-
|
|
331
|
-
const metadata = {
|
|
332
|
-
type,
|
|
333
|
-
code: 202,
|
|
334
|
-
appId: this.appId,
|
|
335
|
-
sender: prefixId(this.appId, senderId),
|
|
336
|
-
receivers: receiverIds.map((id) =>
|
|
337
|
-
prefixId(this.appId, id)
|
|
338
|
-
),
|
|
339
|
-
timestamp: Date.now(),
|
|
340
|
-
};
|
|
341
|
-
|
|
342
|
-
const frame = framePacket(metadata, buffer);
|
|
343
|
-
this.transport.sendBinary(frame);
|
|
344
|
-
}
|
|
345
|
-
}
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
export class HttpTransport {
|
|
2
|
-
// constructor({ url, appId, secret, userId }) {
|
|
3
|
-
// this.url = url;
|
|
4
|
-
// this.appId = appId;
|
|
5
|
-
// this.appSecret = secret;
|
|
6
|
-
// this.userId = userId;
|
|
7
|
-
|
|
8
|
-
// }
|
|
9
|
-
|
|
10
|
-
constructor({url}){
|
|
11
|
-
this.url = url;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
async send(payload) {
|
|
15
|
-
const res = await fetch(`${this.url}`, {
|
|
16
|
-
method: "POST",
|
|
17
|
-
headers: {
|
|
18
|
-
"Content-Type": "application/json",
|
|
19
|
-
},
|
|
20
|
-
body: JSON.stringify(payload)
|
|
21
|
-
});
|
|
22
|
-
|
|
23
|
-
if (!res.ok) {
|
|
24
|
-
const text = await res.text();
|
|
25
|
-
throw new Error(`DNotifier HTTP error: ${text}`);
|
|
26
|
-
}
|
|
27
|
-
return await res.json();
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
sendBinary() {
|
|
31
|
-
throw new Error("Binary is not supported over HTTP yet");
|
|
32
|
-
}
|
|
33
|
-
}
|
|
@@ -1,154 +0,0 @@
|
|
|
1
|
-
// import WebSocket from "ws";
|
|
2
|
-
// import EventEmitter from "events";
|
|
3
|
-
// import { decodePacket } from "../utils/frame.js";
|
|
4
|
-
|
|
5
|
-
// export class WebsocketTransport extends EventEmitter {
|
|
6
|
-
// constructor() {
|
|
7
|
-
// super();
|
|
8
|
-
// this.socket = null;
|
|
9
|
-
// }
|
|
10
|
-
|
|
11
|
-
// async connect(url) {
|
|
12
|
-
// return new Promise((resolve, reject) => {
|
|
13
|
-
// this.socket = new WebSocket(url);
|
|
14
|
-
|
|
15
|
-
// this.socket.on("open", () => {
|
|
16
|
-
// resolve(true);
|
|
17
|
-
// });
|
|
18
|
-
|
|
19
|
-
// this.socket.on("error", (err) => {
|
|
20
|
-
// console.error("WS error", err);
|
|
21
|
-
// reject(err);
|
|
22
|
-
// });
|
|
23
|
-
|
|
24
|
-
// this.socket.on("close", (code, reason) => {
|
|
25
|
-
// console.warn("WS closed", code, reason.toString());
|
|
26
|
-
// this.emit("close", { code, reason });
|
|
27
|
-
// });
|
|
28
|
-
|
|
29
|
-
// this.socket.on("message", (data, isBinary) => {
|
|
30
|
-
// var chunk = decodePacket(data);
|
|
31
|
-
// if(chunk){
|
|
32
|
-
// this.emit("message", chunk, isBinary);
|
|
33
|
-
// }
|
|
34
|
-
// });
|
|
35
|
-
// });
|
|
36
|
-
// }
|
|
37
|
-
|
|
38
|
-
// send(data) {
|
|
39
|
-
// if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
|
|
40
|
-
// throw new Error("WebSocket not connected");
|
|
41
|
-
// }
|
|
42
|
-
// this.socket.send(data);
|
|
43
|
-
// }
|
|
44
|
-
|
|
45
|
-
// sendBinary(buffer) {
|
|
46
|
-
// if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
|
|
47
|
-
// throw new Error("WebSocket not connected");
|
|
48
|
-
// }
|
|
49
|
-
// this.socket.send(buffer, { binary: true });
|
|
50
|
-
// }
|
|
51
|
-
|
|
52
|
-
// close() {
|
|
53
|
-
// if (this.socket) {
|
|
54
|
-
// this.socket.close();
|
|
55
|
-
// }
|
|
56
|
-
// }
|
|
57
|
-
// }
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
import EventEmitter from "events";
|
|
61
|
-
import { decodePacket } from "../utils/frame.js";
|
|
62
|
-
|
|
63
|
-
export class WebsocketTransport extends EventEmitter {
|
|
64
|
-
constructor(WebSocketImpl = null) {
|
|
65
|
-
super();
|
|
66
|
-
this.socket = null;
|
|
67
|
-
this.WebSocketImpl =
|
|
68
|
-
WebSocketImpl ||
|
|
69
|
-
(typeof window !== "undefined" ? window.WebSocket : null);
|
|
70
|
-
|
|
71
|
-
if (!this.WebSocketImpl) {
|
|
72
|
-
throw new Error("No WebSocket implementation provided");
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
connect(url) {
|
|
77
|
-
return new Promise((resolve, reject) => {
|
|
78
|
-
this.socket = new this.WebSocketImpl(url);
|
|
79
|
-
|
|
80
|
-
// Browser: binary messages as ArrayBuffer
|
|
81
|
-
if (typeof window !== "undefined") {
|
|
82
|
-
this.socket.binaryType = "arrayBuffer";
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
// ✅ OPEN
|
|
86
|
-
this._on("open", () => resolve(true));
|
|
87
|
-
|
|
88
|
-
// ❌ ERROR
|
|
89
|
-
this._on("error", (err) => {
|
|
90
|
-
console.error("WS error", err);
|
|
91
|
-
reject(err);
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
// 🔌 CLOSE
|
|
95
|
-
this._on("close", (event) => {
|
|
96
|
-
const code = event?.code;
|
|
97
|
-
const reason = event?.reason;
|
|
98
|
-
this.emit("close", { code, reason });
|
|
99
|
-
});
|
|
100
|
-
|
|
101
|
-
// 📩 MESSAGE
|
|
102
|
-
this._on("message", async (event, isBinary) => {
|
|
103
|
-
// console.log('event', event)
|
|
104
|
-
var data = event?.data ?? event;
|
|
105
|
-
|
|
106
|
-
// Convert Blob -> ArrayBuffer in browser
|
|
107
|
-
if (typeof Blob !== "undefined" && data instanceof Blob) {
|
|
108
|
-
data = await data.arrayBuffer();
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
const chunk = decodePacket(data);
|
|
112
|
-
if (chunk) {
|
|
113
|
-
this.emit("message", chunk, isBinary);
|
|
114
|
-
}
|
|
115
|
-
});
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
_on(event, handler) {
|
|
120
|
-
// Node (ws)
|
|
121
|
-
if (this.socket.on) {
|
|
122
|
-
this.socket.on(event, handler);
|
|
123
|
-
}
|
|
124
|
-
// Browser
|
|
125
|
-
else {
|
|
126
|
-
this.socket[`on${event}`] = handler;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
send(data) {
|
|
131
|
-
if (!this.isOpen()) {
|
|
132
|
-
throw new Error("WebSocket not connected");
|
|
133
|
-
}
|
|
134
|
-
this.socket.send(data);
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
sendBinary(buffer) {
|
|
138
|
-
if (!this.isOpen()) {
|
|
139
|
-
throw new Error("WebSocket not connected");
|
|
140
|
-
}
|
|
141
|
-
this.socket.send(buffer); // browser + node compatible
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
isOpen() {
|
|
145
|
-
return (
|
|
146
|
-
this.socket &&
|
|
147
|
-
this.socket.readyState === this.WebSocketImpl.OPEN
|
|
148
|
-
);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
close() {
|
|
152
|
-
this.socket?.close();
|
|
153
|
-
}
|
|
154
|
-
}
|
package/src/utils/buffer.js
DELETED
package/src/utils/frame.js
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
export function framePacket(metadata, dataBuffer) {
|
|
2
|
-
const metaBuf = Buffer.from(JSON.stringify(metadata));
|
|
3
|
-
const dataBuf = Buffer.isBuffer(dataBuffer)
|
|
4
|
-
? dataBuffer
|
|
5
|
-
: Buffer.from(dataBuffer);
|
|
6
|
-
|
|
7
|
-
const frame = Buffer.alloc(
|
|
8
|
-
4 + metaBuf.length + 4 + dataBuf.length
|
|
9
|
-
);
|
|
10
|
-
|
|
11
|
-
let offset = 0;
|
|
12
|
-
|
|
13
|
-
frame.writeUInt32BE(metaBuf.length, offset);
|
|
14
|
-
offset += 4;
|
|
15
|
-
|
|
16
|
-
metaBuf.copy(frame, offset);
|
|
17
|
-
offset += metaBuf.length;
|
|
18
|
-
|
|
19
|
-
frame.writeUInt32BE(dataBuf.length, offset);
|
|
20
|
-
offset += 4;
|
|
21
|
-
|
|
22
|
-
dataBuf.copy(frame, offset);
|
|
23
|
-
|
|
24
|
-
return frame;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* decodePacket
|
|
29
|
-
* Takes a single framed packet (Buffer)
|
|
30
|
-
* Returns { metadata, data }
|
|
31
|
-
*/
|
|
32
|
-
let internalBuffer = Buffer.alloc(0);
|
|
33
|
-
|
|
34
|
-
export function decodePacket(chunk) {
|
|
35
|
-
try {
|
|
36
|
-
if (!Buffer.isBuffer(chunk)) {
|
|
37
|
-
chunk = Buffer.from(chunk);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// Append incoming chunk
|
|
41
|
-
internalBuffer = Buffer.concat([internalBuffer, chunk]);
|
|
42
|
-
|
|
43
|
-
let offset = 0;
|
|
44
|
-
|
|
45
|
-
// 1️⃣ Need metadata length
|
|
46
|
-
if (internalBuffer.length < 4) {
|
|
47
|
-
return null;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
const metaLength = internalBuffer.readUInt32BE(offset);
|
|
51
|
-
offset += 4;
|
|
52
|
-
|
|
53
|
-
// 2️⃣ Need metadata
|
|
54
|
-
if (internalBuffer.length < offset + metaLength) {
|
|
55
|
-
return null;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
const metaBuf = internalBuffer.slice(offset, offset + metaLength);
|
|
59
|
-
const metadata = JSON.parse(metaBuf.toString());
|
|
60
|
-
offset += metaLength;
|
|
61
|
-
|
|
62
|
-
// 3️⃣ Need payload length
|
|
63
|
-
if (internalBuffer.length < offset + 4) {
|
|
64
|
-
return null;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
const dataLength = internalBuffer.readUInt32BE(offset);
|
|
68
|
-
offset += 4;
|
|
69
|
-
|
|
70
|
-
// 4️⃣ Need payload
|
|
71
|
-
if (internalBuffer.length < offset + dataLength) {
|
|
72
|
-
return null;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
const dataBuf = internalBuffer.slice(offset, offset + dataLength);
|
|
76
|
-
offset += dataLength;
|
|
77
|
-
|
|
78
|
-
// 5️⃣ Remove consumed bytes
|
|
79
|
-
internalBuffer = internalBuffer.slice(offset);
|
|
80
|
-
|
|
81
|
-
// 6️⃣ Decode text (optional)
|
|
82
|
-
let data = dataBuf;
|
|
83
|
-
if (metadata.type === "text") {
|
|
84
|
-
try {
|
|
85
|
-
data = JSON.parse(dataBuf.toString("utf8"));
|
|
86
|
-
} catch {
|
|
87
|
-
// Not JSON, return raw buffer
|
|
88
|
-
data = dataBuf;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
return { metadata, data };
|
|
93
|
-
} catch (err) {
|
|
94
|
-
console.error("decodePacket error:", err);
|
|
95
|
-
return null;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
|
package/src/utils/id.js
DELETED
package/src/utils/payload.js
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
export class Payload {
|
|
2
|
-
constructor(buffer) {
|
|
3
|
-
this.buffer = buffer;
|
|
4
|
-
}
|
|
5
|
-
|
|
6
|
-
/** Raw Buffer */
|
|
7
|
-
raw() {
|
|
8
|
-
return this.buffer;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
/** Convert buffer to string */
|
|
12
|
-
toString(encoding = "utf8") {
|
|
13
|
-
return this.buffer.toString(encoding);
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
/** Safely parse JSON */
|
|
17
|
-
toJSON(encoding = "utf8") {
|
|
18
|
-
try {
|
|
19
|
-
return JSON.parse(this.buffer.toString(encoding));
|
|
20
|
-
} catch (err) {
|
|
21
|
-
return null;
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/** Base64 if needed */
|
|
26
|
-
toBase64() {
|
|
27
|
-
return this.buffer.toString("base64");
|
|
28
|
-
}
|
|
29
|
-
}
|