@dnotifier-realtime/dnotifier 1.0.10 → 1.0.12

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 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,50 @@
1
+ export class DNotifier {
2
+ constructor({ appId, secret, transport, userId, onConnected, onMessage, onDisconnected, WebSocketImpl, }: {
3
+ appId: any;
4
+ secret: any;
5
+ transport: any;
6
+ userId: any;
7
+ onConnected: any;
8
+ onMessage: any;
9
+ onDisconnected: any;
10
+ WebSocketImpl: any;
11
+ });
12
+ appId: any;
13
+ secret: any;
14
+ userId: any;
15
+ url: string;
16
+ onConnectedCallback: any;
17
+ onMessageCallback: any;
18
+ onDisconnectedCallback: any;
19
+ isConnected: boolean;
20
+ transport: HttpTransport | WebsocketTransport;
21
+ connect(): Promise<void>;
22
+ authToken: any;
23
+ send({ senderId, receiverId, receiverIds, data }: {
24
+ senderId: any;
25
+ receiverId: any;
26
+ receiverIds: any;
27
+ data: any;
28
+ }): void;
29
+ sendBinary({ senderId, receiverIds, buffer, type }: {
30
+ senderId: any;
31
+ receiverIds: any;
32
+ buffer: any;
33
+ type?: string | undefined;
34
+ }): void;
35
+ sendWithOpenAI({ senderId, message, openaiApiKey, model, baseUrl }: {
36
+ senderId: string;
37
+ message: string | Array<{
38
+ role: string;
39
+ content: string;
40
+ }>;
41
+ openaiApiKey: string;
42
+ model?: string | undefined;
43
+ baseUrl?: string | undefined;
44
+ }): Promise<{
45
+ content: string;
46
+ }>;
47
+ }
48
+ import { HttpTransport } from "./transport/httpTransport.js";
49
+ import { WebsocketTransport } from "./transport/websocketTransport.js";
50
+ //# sourceMappingURL=dnotifier.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dnotifier.d.ts","sourceRoot":"","sources":["../src/dnotifier.js"],"names":[],"mappings":"AAqLA;IACE;;;;;;;;;OA8BC;IAhBC,WAAkB;IAClB,YAAoB;IACpB,YAAoB;IAEpB,YAAuC;IAEvC,yBAAoD;IACpD,uBAAgD;IAChD,4BAA0D;IAE1D,qBAAwB;IAExB,8CAGyB;IAG3B,yBAyFC;IAzEC,eAAkC;IA2EpC;;;;;aAuBC;IAED;;;;;aAkBC;IAcD,oEAPG;QAAwB,QAAQ,EAAxB,MAAM;QACmD,OAAO,EAAhE,MAAM,GAAG,KAAK,CAAC;YAAC,IAAI,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAA;SAAC,CAAC;QAC/B,YAAY,EAA5B,MAAM;QACW,KAAK;QACL,OAAO;KAChC,GAAU,OAAO,CAAC;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CA4BxC;CACF;8BAxN6B,8BAA8B;mCACzB,mCAAmC"}
@@ -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:_0x2665ee,secret:_0x289858,transport:_0x26811d,userId:_0x2a865b,onConnected:_0x5e2333,onMessage:_0x506fb7,onDisconnected:_0x3908c,WebSocketImpl:_0x4697c9}){if(!(_0x2665ee&&_0x289858&&_0x26811d&&_0x2a865b))throw new Error('appId,\x20secret,\x20transport,\x20and\x20userId\x20are\x20required');this['appId']=_0x2665ee,this['secret']=_0x289858,this['userId']=_0x2a865b,this['url']='wss://link.dchatter.com/ws',this['onConnectedCallback']=_0x5e2333||(()=>{}),this['onMessageCallback']=_0x506fb7||(()=>{}),this['onDisconnectedCallback']=_0x3908c||(()=>{}),this['isConnected']=!0x1,this['transport']='ws'===_0x26811d?new websocketTransport_js_1['WebsocketTransport'](_0x4697c9):new httpTransport_js_1['HttpTransport']();}async['connect'](){const _0x274c45=new httpTransport_js_1['HttpTransport']({'url':'https://link.dchatter.com/api/v1/sdk/auth'}),_0x4aa54a=await _0x274c45['send']({'appId':this['appId'],'appSecret':this['secret'],'userID':this['userId']});if(0xc8!==_0x4aa54a['_responseCode'])throw new Error('Authentication\x20Failed.');this['authToken']=_0x4aa54a['_responseData'],await this['transport']['connect'](this['url']);const _0x227024={'type':'text','code':0x65,'appId':this['appId'],'sender':(0x0,id_js_1['prefixId'])(this['appId'],this['userId']),'timestamp':Date['now'](),'token':this['authToken']},_0x1a78f5=(0x0,buffer_js_1['toUint8'])(JSON['stringify']({'token':this['authToken']})),_0x2f2456=(0x0,frame_js_1['framePacket'])(_0x227024,_0x1a78f5);this['transport']['sendBinary'](_0x2f2456);let _0x57d392=!0x1;this['transport']['on']('message',_0x2801dc=>{try{const {metadata:_0x581278,data:_0x401484}=_0x2801dc;if(!_0x57d392&&'102'===_0x581278['packet']['code']&&_0x581278['packet']['sender']['includes']((0x0,id_js_1['prefixId'])(this['appId'],this['userId'])))return _0x57d392=!0x0,this['isConnected']=!0x0,void this['onConnectedCallback']();_0x57d392&&this['onMessageCallback']({'metadata':{'sender':_0x581278['packet']['sender'],'timestamp':_0x581278['packet']['timestamp']},'payload':new payload_js_1['Payload'](_0x401484)});}catch(_0x3cf89a){console['error']('Packet\x20error:',_0x3cf89a);}}),this['transport']['on']('close',({code:_0x33328e,reason:_0x4ec293})=>{this['isConnected']&&(this['isConnected']=!0x1,this['onDisconnectedCallback']({'code':_0x33328e,'reason':_0x4ec293||'Disconnected'}));}),this['transport']['on']('error',_0x223d2f=>{this['isConnected']=!0x1,this['onDisconnectedCallback']({'code':0x1f4,'reason':(null==_0x223d2f?void 0x0:_0x223d2f['message'])||'Transport\x20error'});});}['send']({senderId:_0x453219,receiverId:_0x4a0c27,receiverIds:_0x43c7e0,data:_0x4eaaf0}){if(!_0x453219)throw new Error('senderId\x20required');if(!_0x4a0c27&&!_0x43c7e0)throw new Error('receiverId\x20or\x20receiverIds\x20required');const _0x5d8558=null!=_0x43c7e0?_0x43c7e0:[_0x4a0c27],_0x3403e1={'type':'text','code':0xc8,'appId':this['appId'],'sender':(0x0,id_js_1['prefixId'])(this['appId'],_0x453219),'receivers':_0x5d8558['map'](_0x415318=>(0x0,id_js_1['prefixId'])(this['appId'],_0x415318)),'timestamp':Date['now'](),'token':this['authToken']},_0x59851e=(0x0,buffer_js_1['toUint8'])(JSON['stringify'](_0x4eaaf0)),_0x4d57fe=(0x0,frame_js_1['framePacket'])(_0x3403e1,_0x59851e);this['transport']['sendBinary'](_0x4d57fe);}['sendBinary']({senderId:_0x44ac0e,receiverIds:_0x1168c4,buffer:_0x266030,type:_0x3697c7='binary'}){if(!_0x44ac0e)throw new Error('senderId\x20required');if(!_0x266030)throw new Error('buffer\x20is\x20required');const _0x18880c={'type':_0x3697c7,'code':0xca,'appId':this['appId'],'sender':(0x0,id_js_1['prefixId'])(this['appId'],_0x44ac0e),'receivers':_0x1168c4['map'](_0x493b18=>(0x0,id_js_1['prefixId'])(this['appId'],_0x493b18)),'timestamp':Date['now'](),'token':this['authToken']},_0x1dcd04=(0x0,frame_js_1['framePacket'])(_0x18880c,_0x266030);this['transport']['sendBinary'](_0x1dcd04);}async['sendWithOpenAI']({senderId:_0x2c5bb2,message:_0x3578ca,openaiApiKey:_0x266f20,model:_0x54cde4,baseUrl:_0x55f261}){if(!_0x2c5bb2)throw new Error('senderId\x20is\x20required');if(!_0x3578ca)throw new Error('message\x20is\x20required');if(!_0x266f20)throw new Error('openaiApiKey\x20is\x20required');const {content:_0x2f8553}=await(0x0,openai_js_1['chatStream'])({'apiKey':_0x266f20,'model':_0x54cde4,'messages':_0x3578ca,'baseUrl':_0x55f261}),_0x50fabf={'type':'openai','content':_0x2f8553,'ts':Date['now']()};return this['onMessageCallback']({'metadata':{'sender':(0x0,id_js_1['prefixId'])(this['appId'],_0x2c5bb2),'timestamp':Date['now']()},'payload':new payload_js_1['Payload']((0x0,buffer_js_1['toUint8'])(JSON['stringify'](_0x50fabf)))}),{'content':_0x2f8553};}}exports['DNotifier']=DNotifier;
@@ -0,0 +1,18 @@
1
+ export function chat(options: {
2
+ apiKey: string;
3
+ model?: string | undefined;
4
+ messages: string | Array<{
5
+ role: string;
6
+ content: string;
7
+ }>;
8
+ baseUrl?: string | undefined;
9
+ }): Promise<{
10
+ content: string;
11
+ usage?: object;
12
+ raw?: object;
13
+ }>;
14
+ export function chatStream(options: Object): Promise<{
15
+ content: string;
16
+ usage?: object;
17
+ }>;
18
+ //# sourceMappingURL=openai.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai.d.ts","sourceRoot":"","sources":["../../src/providers/openai.js"],"names":[],"mappings":"AAmCA,8BANG;IAAwB,MAAM,EAAtB,MAAM;IACW,KAAK;IACmC,QAAQ,EAAjE,MAAM,GAAG,KAAK,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAC,CAAC;IAC9B,OAAO;CAChC,GAAU,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAqCtE;AAOD,oCAHW,MAAM,GACJ,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAqExD"}
@@ -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(_0x34c7ed){if('string'==typeof _0x34c7ed)return[{'role':'user','content':_0x34c7ed}];if(Array['isArray'](_0x34c7ed)&&_0x34c7ed['length']>0x0)return _0x34c7ed['map'](_0x2b3f53=>({'role':_0x2b3f53['role']||'user','content':'string'==typeof _0x2b3f53['content']?_0x2b3f53['content']:String(_0x2b3f53['content'])}));throw new Error('message\x20must\x20be\x20a\x20non-empty\x20string\x20or\x20array\x20of\x20{\x20role,\x20content\x20}');}async function chat(_0x48eca6){var _0x59a685,_0x11d5dd,_0x5c7cdc,_0x4b5864,_0x569b34,_0x51d8bc;const {apiKey:_0xcaf27f,model:_0xf04917=DEFAULT_MODEL,messages:_0x401214,baseUrl:_0x23e722=DEFAULT_BASE_URL}=_0x48eca6;if(!_0xcaf27f||!_0x401214)throw new Error('openai.chat:\x20apiKey\x20and\x20messages\x20are\x20required');const _0x1a7a73=_0x23e722['replace'](/\/$/,'')+'/v1/chat/completions',_0x56c4ad={'model':_0xf04917,'messages':normalizeMessages(_0x401214),'stream':!0x1},_0x12efa5=await fetch(_0x1a7a73,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+_0xcaf27f},'body':JSON['stringify'](_0x56c4ad)}),_0x337bc0=await _0x12efa5['json']();if(!_0x12efa5['ok']){const _0x20c1cd=new Error((null===(_0x59a685=null==_0x337bc0?void 0x0:_0x337bc0['error'])||void 0x0===_0x59a685?void 0x0:_0x59a685['message'])||'OpenAI\x20API\x20error:\x20'+_0x12efa5['status']);throw _0x20c1cd['status']=_0x12efa5['status'],_0x20c1cd['code']=null===(_0x11d5dd=null==_0x337bc0?void 0x0:_0x337bc0['error'])||void 0x0===_0x11d5dd?void 0x0:_0x11d5dd['code'],_0x20c1cd;}return{'content':null!==(_0x51d8bc=null===(_0x569b34=null===(_0x4b5864=null===(_0x5c7cdc=null==_0x337bc0?void 0x0:_0x337bc0['choices'])||void 0x0===_0x5c7cdc?void 0x0:_0x5c7cdc[0x0])||void 0x0===_0x4b5864?void 0x0:_0x4b5864['message'])||void 0x0===_0x569b34?void 0x0:_0x569b34['content'])&&void 0x0!==_0x51d8bc?_0x51d8bc:'','usage':null==_0x337bc0?void 0x0:_0x337bc0['usage'],'raw':_0x337bc0};}async function chatStream(_0x496462){var _0x1f8cb4,_0x426841,_0x55bb8c,_0x5e297a,_0x45b51c;const {apiKey:_0x4ac6e6,model:_0x30bd06=DEFAULT_MODEL,messages:_0x5293b4,baseUrl:_0x4526ec=DEFAULT_BASE_URL,onChunk:_0x20c06b}=_0x496462;if(!_0x4ac6e6||!_0x5293b4)throw new Error('openai.chatStream:\x20apiKey\x20and\x20messages\x20are\x20required');const _0x696d72=_0x4526ec['replace'](/\/$/,'')+'/v1/chat/completions',_0x30a7db={'model':_0x30bd06,'messages':normalizeMessages(_0x5293b4),'stream':!0x0},_0x1a84fb=await fetch(_0x696d72,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+_0x4ac6e6},'body':JSON['stringify'](_0x30a7db)});if(!_0x1a84fb['ok']){const _0x275158=await _0x1a84fb['json']()['catch'](()=>({})),_0x1c7347=new Error((null===(_0x1f8cb4=null==_0x275158?void 0x0:_0x275158['error'])||void 0x0===_0x1f8cb4?void 0x0:_0x1f8cb4['message'])||'OpenAI\x20API\x20error:\x20'+_0x1a84fb['status']);throw _0x1c7347['status']=_0x1a84fb['status'],_0x1c7347['code']=null===(_0x426841=null==_0x275158?void 0x0:_0x275158['error'])||void 0x0===_0x426841?void 0x0:_0x426841['code'],_0x1c7347;}const _0x49d3ea=_0x1a84fb['body']['getReader'](),_0x11b980=new TextDecoder();let _0x57714c='',_0x2843ae='';for(;;){const {done:_0x3cd1c2,value:_0x44e19a}=await _0x49d3ea['read']();if(_0x3cd1c2)break;_0x2843ae+=_0x11b980['decode'](_0x44e19a,{'stream':!0x0});const _0x1bae37=_0x2843ae['split']('\x0a');_0x2843ae=_0x1bae37['pop']()||'';for(const _0x32b1c0 of _0x1bae37){const _0x230ae1=_0x32b1c0['trim']();if(''!==_0x230ae1&&'data:\x20[DONE]'!==_0x230ae1&&_0x230ae1['startsWith']('data:\x20'))try{const _0x3c3203=JSON['parse'](_0x230ae1['slice'](0x6)),_0x4d95dd=null===(_0x45b51c=null===(_0x5e297a=null===(_0x55bb8c=null==_0x3c3203?void 0x0:_0x3c3203['choices'])||void 0x0===_0x55bb8c?void 0x0:_0x55bb8c[0x0])||void 0x0===_0x5e297a?void 0x0:_0x5e297a['delta'])||void 0x0===_0x45b51c?void 0x0:_0x45b51c['content'];'string'==typeof _0x4d95dd&&(_0x57714c+=_0x4d95dd,_0x20c06b&&_0x20c06b(_0x4d95dd));}catch(_0x13a032){}}}return{'content':_0x57714c};}
@@ -0,0 +1,9 @@
1
+ export class HttpTransport {
2
+ constructor({ url }: {
3
+ url: any;
4
+ });
5
+ url: any;
6
+ send(payload: any): Promise<any>;
7
+ sendBinary(): void;
8
+ }
9
+ //# sourceMappingURL=httpTransport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"httpTransport.d.ts","sourceRoot":"","sources":["../../src/transport/httpTransport.js"],"names":[],"mappings":"AAAA;IASE;;OAEC;IADC,SAAc;IAGhB,iCAcC;IAED,mBAEC;CACF"}
@@ -0,0 +1 @@
1
+ 'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['HttpTransport']=void 0x0;class HttpTransport{constructor({url:_0x2903c8}){this['url']=_0x2903c8;}async['send'](_0x57feb6){const _0x5aa71f=await fetch(''+this['url'],{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](_0x57feb6)});if(!_0x5aa71f['ok']){const _0x513928=await _0x5aa71f['text']();throw new Error('DNotifier\x20HTTP\x20error:\x20'+_0x513928);}return await _0x5aa71f['json']();}['sendBinary'](){throw new Error('Binary\x20is\x20not\x20supported\x20over\x20HTTP\x20yet');}}exports['HttpTransport']=HttpTransport;
@@ -0,0 +1,19 @@
1
+ export class WebsocketTransport {
2
+ constructor(WebSocketImpl?: null);
3
+ socket: WebSocket | null;
4
+ WebSocketImpl: {
5
+ new (url: string | URL, protocols?: string | string[]): WebSocket;
6
+ prototype: WebSocket;
7
+ readonly CONNECTING: 0;
8
+ readonly OPEN: 1;
9
+ readonly CLOSING: 2;
10
+ readonly CLOSED: 3;
11
+ };
12
+ connect(url: any): Promise<any>;
13
+ _on(event: any, handler: any): void;
14
+ send(data: any): void;
15
+ sendBinary(buffer: any): void;
16
+ isOpen(): boolean | null;
17
+ close(): void;
18
+ }
19
+ //# sourceMappingURL=websocketTransport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocketTransport.d.ts","sourceRoot":"","sources":["../../src/transport/websocketTransport.js"],"names":[],"mappings":"AA8DA;IACE,kCAUC;IARC,yBAAkB;IAClB;;;;;;;MAE2D;IAO7D,gCAyCC;IAED,oCASC;IAED,sBAKC;IAED,8BAKC;IAED,yBAKC;IAED,cAEC;CACF"}
@@ -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(_0x2df9a5=null){if(super(),this['socket']=null,this['WebSocketImpl']=_0x2df9a5||('undefined'!=typeof window?window['WebSocket']:null),!this['WebSocketImpl'])throw new Error('No\x20WebSocket\x20implementation\x20provided');}['connect'](_0x2f4591){return new Promise((_0x871e3f,_0x3f5c52)=>{this['socket']=new this['WebSocketImpl'](_0x2f4591),'undefined'!=typeof window&&(this['socket']['binaryType']='arrayBuffer'),this['_on']('open',()=>_0x871e3f(!0x0)),this['_on']('error',_0xb3426=>{console['error']('WS\x20error',_0xb3426),_0x3f5c52(_0xb3426);}),this['_on']('close',_0x426323=>{const _0x316d97=null==_0x426323?void 0x0:_0x426323['code'],_0x480c47=null==_0x426323?void 0x0:_0x426323['reason'];this['emit']('close',{'code':_0x316d97,'reason':_0x480c47});}),this['_on']('message',async(_0x346bc0,_0x4e2ca9)=>{var _0x1cefff,_0x18d64e=null!==(_0x1cefff=null==_0x346bc0?void 0x0:_0x346bc0['data'])&&void 0x0!==_0x1cefff?_0x1cefff:_0x346bc0;'undefined'!=typeof Blob&&_0x18d64e instanceof Blob&&(_0x18d64e=await _0x18d64e['arrayBuffer']());const _0x4d1cf3=(0x0,frame_js_1['decodePacket'])(_0x18d64e);_0x4d1cf3&&this['emit']('message',_0x4d1cf3,_0x4e2ca9);});});}['_on'](_0x4b38f3,_0x456ada){this['socket']['on']?this['socket']['on'](_0x4b38f3,_0x456ada):this['socket']['on'+_0x4b38f3]=_0x456ada;}['send'](_0x487602){if(!this['isOpen']())throw new Error('WebSocket\x20not\x20connected');this['socket']['send'](_0x487602);}['sendBinary'](_0x1d86df){if(!this['isOpen']())throw new Error('WebSocket\x20not\x20connected');this['socket']['send'](_0x1d86df);}['isOpen'](){return this['socket']&&this['socket']['readyState']===this['WebSocketImpl']['OPEN'];}['close'](){var _0x43145b;null===(_0x43145b=this['socket'])||void 0x0===_0x43145b||_0x43145b['close']();}}exports['WebsocketTransport']=WebsocketTransport;
@@ -0,0 +1,2 @@
1
+ export function toUint8(data: any): any;
2
+ //# sourceMappingURL=buffer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buffer.d.ts","sourceRoot":"","sources":["../../src/utils/buffer.js"],"names":[],"mappings":"AAAA,wCAKC"}
@@ -0,0 +1 @@
1
+ 'use strict';function toUint8(_0x3ba0d3){return'undefined'!=typeof Buffer?Buffer['from'](_0x3ba0d3,'utf8'):new TextEncoder()['encode'](_0x3ba0d3);}Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['toUint8']=toUint8;
@@ -0,0 +1,6 @@
1
+ export function framePacket(metadata: any, dataBuffer: any): any;
2
+ export function decodePacket(chunk: any): {
3
+ metadata: any;
4
+ data: any;
5
+ } | null;
6
+ //# sourceMappingURL=frame.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frame.d.ts","sourceRoot":"","sources":["../../src/utils/frame.js"],"names":[],"mappings":"AAAA,iEAwBC;AASD;;;SA+DC"}
@@ -0,0 +1 @@
1
+ 'use strict';function framePacket(_0xfe1213,_0x22e08a){const _0x103824=Buffer['from'](JSON['stringify'](_0xfe1213)),_0x2fda2e=Buffer['isBuffer'](_0x22e08a)?_0x22e08a:Buffer['from'](_0x22e08a),_0x2a2e92=Buffer['alloc'](0x4+_0x103824['length']+0x4+_0x2fda2e['length']);let _0x41f670=0x0;return _0x2a2e92['writeUInt32BE'](_0x103824['length'],_0x41f670),_0x41f670+=0x4,_0x103824['copy'](_0x2a2e92,_0x41f670),_0x41f670+=_0x103824['length'],_0x2a2e92['writeUInt32BE'](_0x2fda2e['length'],_0x41f670),_0x41f670+=0x4,_0x2fda2e['copy'](_0x2a2e92,_0x41f670),_0x2a2e92;}Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['framePacket']=framePacket,exports['decodePacket']=decodePacket;let internalBuffer=Buffer['alloc'](0x0);function decodePacket(_0x8a9d42){try{Buffer['isBuffer'](_0x8a9d42)||(_0x8a9d42=Buffer['from'](_0x8a9d42)),internalBuffer=Buffer['concat']([internalBuffer,_0x8a9d42]);let _0x1d60b6=0x0;if(internalBuffer['length']<0x4)return null;const _0x13a92b=internalBuffer['readUInt32BE'](_0x1d60b6);if(_0x1d60b6+=0x4,internalBuffer['length']<_0x1d60b6+_0x13a92b)return null;const _0xbde734=internalBuffer['slice'](_0x1d60b6,_0x1d60b6+_0x13a92b),_0x39be61=JSON['parse'](_0xbde734['toString']());if(_0x1d60b6+=_0x13a92b,internalBuffer['length']<_0x1d60b6+0x4)return null;const _0x5e6acb=internalBuffer['readUInt32BE'](_0x1d60b6);if(_0x1d60b6+=0x4,internalBuffer['length']<_0x1d60b6+_0x5e6acb)return null;const _0x25377b=internalBuffer['slice'](_0x1d60b6,_0x1d60b6+_0x5e6acb);_0x1d60b6+=_0x5e6acb,internalBuffer=internalBuffer['slice'](_0x1d60b6);let _0x3a4efd=_0x25377b;if('text'===_0x39be61['type'])try{_0x3a4efd=JSON['parse'](_0x25377b['toString']('utf8'));}catch{_0x3a4efd=_0x25377b;}return{'metadata':_0x39be61,'data':_0x3a4efd};}catch(_0x33f7cb){return console['error']('decodePacket\x20error:',_0x33f7cb),null;}}
@@ -0,0 +1,2 @@
1
+ export function prefixId(appId: any, id: any): any;
2
+ //# sourceMappingURL=id.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"id.d.ts","sourceRoot":"","sources":["../../src/utils/id.js"],"names":[],"mappings":"AAAO,mDAGN"}
@@ -0,0 +1 @@
1
+ 'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['prefixId']=void 0x0;const prefixId=(_0x435f31,_0x57c303)=>_0x57c303['includes'](':')?_0x57c303:_0x435f31+':'+_0x57c303;exports['prefixId']=prefixId;
@@ -0,0 +1,9 @@
1
+ export class Payload {
2
+ constructor(buffer: any);
3
+ buffer: any;
4
+ raw(): any;
5
+ toString(encoding?: string): any;
6
+ toJSON(encoding?: string): any;
7
+ toBase64(): any;
8
+ }
9
+ //# sourceMappingURL=payload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payload.d.ts","sourceRoot":"","sources":["../../src/utils/payload.js"],"names":[],"mappings":"AAAA;IACE,yBAEC;IADC,YAAoB;IAItB,WAEC;IAGD,iCAEC;IAGD,+BAMC;IAGD,gBAEC;CACF"}
@@ -0,0 +1 @@
1
+ 'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['Payload']=void 0x0;class Payload{constructor(_0xf263da){this['buffer']=_0xf263da;}['raw'](){return this['buffer'];}['toString'](_0xfc5785='utf8'){return this['buffer']['toString'](_0xfc5785);}['toJSON'](_0x4c2ba6='utf8'){try{return JSON['parse'](this['buffer']['toString'](_0x4c2ba6));}catch(_0x3ac571){return null;}}['toBase64'](){return this['buffer']['toString']('base64');}}exports['Payload']=Payload;
package/package.json CHANGED
@@ -1,8 +1,12 @@
1
1
  {
2
2
  "name": "@dnotifier-realtime/dnotifier",
3
- "version": "1.0.10",
3
+ "version": "1.0.12",
4
4
  "description": "Real-time notification & messaging SDK",
5
- "main": "src/dnotifier.js",
5
+ "main": "dist/dnotifier.js",
6
+ "types": "dist/dnotifier.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
6
10
  "type": "module",
7
11
  "keywords": [
8
12
  "dnotifier",
@@ -22,10 +26,16 @@
22
26
  "dependencies": {
23
27
  "ws": "^8.19.0"
24
28
  },
25
- "devDependencies": {},
29
+ "devDependencies": {
30
+ "javascript-obfuscator": "^4.1.1",
31
+ "terser": "^5.36.0",
32
+ "typescript": "^5.9.3"
33
+ },
26
34
  "scripts": {
27
35
  "test": "echo \"Error: no test specified\" && exit 1",
28
- "start" : "node index.js"
36
+ "start": "node index.js",
37
+ "build": "tsc",
38
+ "publishprod": "node scripts/publish-prod.js"
29
39
  },
30
40
  "homepage": "https://dnotifier.com"
31
41
  }
package/src/dnotifier.js DELETED
@@ -1,349 +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 = "ws://127.0.0.1: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
- token : this.authToken
243
- };
244
-
245
- const payloadBuffer = toUint8(
246
- JSON.stringify({ token: this.authToken })
247
- );
248
- // console.log(this.authToken)
249
-
250
- const frame = framePacket(metadata, payloadBuffer);
251
- this.transport.sendBinary(frame);
252
-
253
- let handshakeDone = false;
254
-
255
- this.transport.on("message", (chunk) => {
256
- try {
257
- const { metadata, data } = chunk;
258
-
259
- if (
260
- !handshakeDone &&
261
- metadata.packet.code === "102" &&
262
- metadata.packet.sender.includes(
263
- prefixId(this.appId, this.userId)
264
- )
265
- ) {
266
- handshakeDone = true;
267
- this.isConnected = true;
268
- this.onConnectedCallback();
269
- return;
270
- }
271
-
272
- if (handshakeDone) {
273
- this.onMessageCallback({
274
- metadata: {
275
- sender: metadata.packet.sender,
276
- timestamp: metadata.packet.timestamp,
277
- },
278
- payload: new Payload(data),
279
- });
280
- }
281
- } catch (err) {
282
- console.error("Packet error:", err);
283
- }
284
- });
285
-
286
- this.transport.on("close", ({ code, reason }) => {
287
- if (this.isConnected) {
288
- this.isConnected = false;
289
- this.onDisconnectedCallback({
290
- code,
291
- reason: reason || "Disconnected",
292
- });
293
- }
294
- });
295
-
296
- this.transport.on("error", (err) => {
297
- this.isConnected = false;
298
- this.onDisconnectedCallback({
299
- code: 500,
300
- reason: err?.message || "Transport error",
301
- });
302
- });
303
- }
304
-
305
- send({ senderId, receiverId, receiverIds, data }) {
306
- if (!senderId) throw new Error("senderId required");
307
- if (!receiverId && !receiverIds)
308
- throw new Error("receiverId or receiverIds required");
309
-
310
- const receivers = receiverIds ?? [receiverId];
311
-
312
- const metadata = {
313
- type: "text",
314
- code: 200,
315
- appId: this.appId,
316
- sender: prefixId(this.appId, senderId),
317
- receivers: receivers.map((id) =>
318
- prefixId(this.appId, id)
319
- ),
320
- timestamp: Date.now(),
321
- token : this.authToken
322
- };
323
-
324
- const payloadBuffer = toUint8(JSON.stringify(data));
325
- const frame = framePacket(metadata, payloadBuffer);
326
-
327
- this.transport.sendBinary(frame);
328
- }
329
-
330
- sendBinary({ senderId, receiverIds, buffer, type = "binary" }) {
331
- if (!senderId) throw new Error("senderId required");
332
- if (!buffer) throw new Error("buffer is required");
333
-
334
- const metadata = {
335
- type,
336
- code: 202,
337
- appId: this.appId,
338
- sender: prefixId(this.appId, senderId),
339
- receivers: receiverIds.map((id) =>
340
- prefixId(this.appId, id)
341
- ),
342
- timestamp: Date.now(),
343
- token : this.authToken
344
- };
345
-
346
- const frame = framePacket(metadata, buffer);
347
- this.transport.sendBinary(frame);
348
- }
349
- }
@@ -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
- }
@@ -1,6 +0,0 @@
1
- export function toUint8(data) {
2
- if (typeof Buffer !== "undefined") {
3
- return Buffer.from(data, "utf8"); // Node
4
- }
5
- return new TextEncoder().encode(data); // Browser
6
- }
@@ -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
@@ -1,4 +0,0 @@
1
- export const prefixId = (appId, id) => {
2
- if (id.includes(":")) return id;
3
- return `${appId}:${id}`;
4
- };
@@ -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
- }