@dnotifier-realtime/dnotifier 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,23 @@
1
+ # DNotifier SDK
2
+
3
+ 🚀 **DNotifier** is a real-time notification & messaging SDK supporting **WebSocket and HTTP transports**, **binary streaming**, and **framed packet communication** — built for scalable and reliable real-time systems.
4
+
5
+ ---
6
+
7
+ ## ✨ Features
8
+
9
+ - 🔌 WebSocket & HTTP transport support
10
+ - 🔐 Secure authentication handshake
11
+ - 📩 Real-time messaging
12
+ - 📦 Binary data transfer (files, images, media)
13
+ - 🧠 Automatic packet framing & decoding
14
+ - ⚡ Handles partial packets & large payloads
15
+ - 🔄 Consistent client ↔ server protocol
16
+ - 🧩 Simple and developer-friendly API
17
+
18
+ ---
19
+
20
+ ## 📦 Installation
21
+
22
+ ```bash
23
+ npm install dnotifier
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@dnotifier-realtime/dnotifier",
3
+ "version": "1.0.0",
4
+ "description": "Real-time notification & messaging SDK",
5
+ "main": "src/dnotifier.js",
6
+ "type": "module",
7
+ "keywords": [
8
+ "dnotifier",
9
+ "websocket",
10
+ "realtime",
11
+ "notifications",
12
+ "sdk",
13
+ "binary",
14
+ "tcp",
15
+ "messaging"
16
+ ],
17
+ "author": "DNotifier",
18
+ "license": "MIT",
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "dependencies": {
23
+ "ws": "^8.19.0"
24
+ },
25
+ "devDependencies": {},
26
+ "scripts": {
27
+ "test": "echo \"Error: no test specified\" && exit 1"
28
+ },
29
+ "homepage": "https://dnotifier.com"
30
+ }
@@ -0,0 +1,147 @@
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
+ */
18
+ constructor({ appId, secret, transport, userId, onConnected, onMessage }) {
19
+ if (!appId || !secret || !transport || !userId) {
20
+ throw new Error("appId, secret, transport, and userId are required");
21
+ }
22
+
23
+ this.appId = appId;
24
+ this.secret = secret;
25
+ this.userId = userId;
26
+ this.url = "ws://34.208.142.201:7072";
27
+
28
+ this.onConnectedCallback = onConnected || (() => {});
29
+ this.onMessageCallback = onMessage || (() => {});
30
+
31
+ this.isConnected = false;
32
+
33
+ this.transport =
34
+ transport === "ws" ? new WebsocketTransport() : new HttpTransport();
35
+ }
36
+
37
+ async connect() {
38
+ // Step 1: Authenticate with Auth server
39
+ const authServer = new HttpTransport({
40
+ url: "https://link.dchatter.com/api/v1/sdk/auth",
41
+ });
42
+
43
+ const res = await authServer.send({
44
+ appId: this.appId,
45
+ appSecret: this.secret,
46
+ userID: this.userId,
47
+ });
48
+
49
+ if (res._responseCode !== 200) {
50
+ throw new Error("Authentication Failed.");
51
+ }
52
+ this.authToken = res._responseData;
53
+
54
+ // Step 2: Connect WebSocket
55
+ await this.transport.connect(this.url);
56
+
57
+ // Step 3: Send handshake packet
58
+ const metadata = {
59
+ type: "text",
60
+ code: 101, // handshake
61
+ appId: this.appId,
62
+ sender: prefixId(this.appId, this.userId),
63
+ timestamp: Date.now(),
64
+ };
65
+ const payloadBuffer = Buffer.from("handshake", "utf8");
66
+ const frame = framePacket(metadata, payloadBuffer);
67
+
68
+ this.transport.sendBinary(frame);
69
+
70
+ // Step 4: Listen for all incoming messages
71
+ let handshakeProcessed = false;
72
+
73
+ // Flag to ignore handshake response
74
+ let handshakeDone = false;
75
+
76
+ this.transport.on("message", (chunk) => {
77
+ try {
78
+
79
+ const metadata = chunk.metadata
80
+ const data = chunk.data;
81
+
82
+ // Handle handshake response internally
83
+ if (!handshakeProcessed && metadata.packet.code === '102' && metadata.packet.sender.includes(prefixId(this.appId, this.userId))) {
84
+ handshakeProcessed = true;
85
+ this.isConnected = true;
86
+ handshakeDone = true;
87
+ this.onConnectedCallback(); // notify developer
88
+
89
+ return; // do NOT forward handshake packet
90
+ }
91
+ // Forward all other messages to developer
92
+ if (handshakeDone && this.onMessageCallback) {
93
+ this.onMessageCallback({
94
+ metadata : {
95
+ sender : metadata.packet.sender,
96
+ timestamp : metadata.packet.timestamp,
97
+ },
98
+ payload: new Payload(data)
99
+ });
100
+
101
+ }
102
+ } catch (err) {
103
+ console.error("Error decoding packet:", err);
104
+ }
105
+ });
106
+ }
107
+
108
+ send({ senderId, receiverId, receiverIds, data }) {
109
+ if (!senderId) throw new Error("senderId required");
110
+ if (!receiverId && !receiverIds)
111
+ throw new Error("receiverId or receiverIds required");
112
+
113
+ const receivers = receiverIds ?? [receiverId];
114
+
115
+ const metadata = {
116
+ type: "text",
117
+ code: 200, // message
118
+ appId: this.appId,
119
+ sender: prefixId(this.appId, senderId),
120
+ receivers: receivers.map((id) => prefixId(this.appId, id)),
121
+ timestamp: Date.now(),
122
+ };
123
+
124
+ const payloadBuffer = Buffer.from(JSON.stringify(data), "utf8");
125
+ const frame = framePacket(metadata, payloadBuffer);
126
+
127
+ this.transport.sendBinary(frame);
128
+ }
129
+
130
+ sendBinary({ senderId, receiverIds, buffer, type = "binary" }) {
131
+ if (!senderId) throw new Error("senderId required");
132
+ if (!buffer) throw new Error("buffer is required");
133
+
134
+ const metadata = {
135
+ type,
136
+ code: 202, // binary stream
137
+ appId: this.appId,
138
+ sender: prefixId(this.appId, senderId),
139
+ receivers: receiverIds.map((id) => prefixId(this.appId, id)),
140
+ timestamp: Date.now(),
141
+ };
142
+
143
+ const frame = framePacket(metadata, buffer);
144
+
145
+ this.transport.sendBinary(frame);
146
+ }
147
+ }
@@ -0,0 +1,33 @@
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
+ }
@@ -0,0 +1,57 @@
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
+ }
@@ -0,0 +1,99 @@
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
+
@@ -0,0 +1,4 @@
1
+ export const prefixId = (appId, id) => {
2
+ if (id.includes(":")) return id;
3
+ return `${appId}:${id}`;
4
+ };
@@ -0,0 +1,30 @@
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
+ console.log(err)
22
+ return null;
23
+ }
24
+ }
25
+
26
+ /** Base64 if needed */
27
+ toBase64() {
28
+ return this.buffer.toString("base64");
29
+ }
30
+ }