docpouch-client 0.8.3 → 0.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +14 -5
- package/dist/index.js +189 -30
- package/dist/types.d.ts +9 -1
- package/dist/types.js +1 -2
- package/package.json +14 -7
- package/src/__tests__/index.test.ts +7 -7
- package/src/index.ts +230 -24
- package/src/types.ts +11 -1
- package/tsconfig.json +2 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
|
-
import type { I_UserEntry, I_UserLogin, I_UserCreation, I_UserUpdate, I_UserDisplay, I_DocumentEntry, I_DataStructure, I_LoginResponse, I_DocumentQuery, I_StructureCreation, I_WsMessage, I_EventString } from "./types.js";
|
|
1
|
+
import type { I_UserEntry, I_UserLogin, I_UserCreation, I_UserUpdate, I_UserDisplay, I_DocumentEntry, I_DataStructure, I_LoginResponse, I_DocumentQuery, I_StructureCreation, I_WsMessage, I_EventString, I_DocumentType } from "./types.js";
|
|
2
2
|
import { Socket } from "socket.io-client";
|
|
3
|
-
export default class
|
|
3
|
+
export default class dbPouchClient {
|
|
4
4
|
baseUrl: string;
|
|
5
|
-
private
|
|
5
|
+
private authToken;
|
|
6
6
|
socket: Socket;
|
|
7
|
-
|
|
7
|
+
callbackFunction: ((event: I_EventString, data: I_WsMessage) => void) | undefined;
|
|
8
|
+
realTimeSync: boolean;
|
|
9
|
+
private connectionInProgress;
|
|
10
|
+
constructor(host: string, port?: number, callback?: (event: I_EventString, data: I_WsMessage) => void);
|
|
11
|
+
private setupPermanentSocketListeners;
|
|
12
|
+
setRealTimeSync: (newRealTimeSync: boolean) => void;
|
|
13
|
+
private initWebSocket;
|
|
8
14
|
private request;
|
|
9
15
|
login(credentials: I_UserLogin): Promise<I_LoginResponse | null>;
|
|
10
16
|
listUsers(): Promise<I_UserEntry[]>;
|
|
@@ -20,7 +26,10 @@ export default class Index {
|
|
|
20
26
|
getStructures(): Promise<I_DataStructure[]>;
|
|
21
27
|
updateStructure(structureID: string, structureData: I_DataStructure): Promise<void>;
|
|
22
28
|
removeStructure(structureID: string): Promise<void>;
|
|
29
|
+
createType(type: I_DocumentType): Promise<I_DocumentType>;
|
|
30
|
+
removeType(typeID: string): Promise<void>;
|
|
31
|
+
getTypes(): Promise<I_DocumentType[]>;
|
|
23
32
|
setToken(token: string | null): void;
|
|
24
|
-
getToken(): string | null;
|
|
25
33
|
getVersion(): string;
|
|
34
|
+
debugSocketConnection(): void;
|
|
26
35
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,44 +1,154 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
1
|
+
import { io } from "socket.io-client";
|
|
2
|
+
import packetJson from '../package.json';
|
|
3
|
+
export default class dbPouchClient {
|
|
4
|
+
constructor(host, port = 80, callback) {
|
|
5
|
+
this.authToken = null;
|
|
6
|
+
this.realTimeSync = false;
|
|
7
|
+
this.connectionInProgress = false;
|
|
8
|
+
this.setRealTimeSync = (newRealTimeSync) => {
|
|
9
|
+
console.log(`Setting realtime sync to: ${newRealTimeSync}. Current setting: ${this.realTimeSync}`);
|
|
10
|
+
// Skip if the setting isn't changing
|
|
11
|
+
if (newRealTimeSync === this.realTimeSync) {
|
|
12
|
+
console.log("Realtime sync setting unchanged, skipping");
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
this.realTimeSync = newRealTimeSync;
|
|
16
|
+
if (newRealTimeSync && this.authToken) {
|
|
17
|
+
console.log("Activating realtime updates");
|
|
18
|
+
// Ensure we're not in the middle of another connection attempt
|
|
19
|
+
if (this.connectionInProgress) {
|
|
20
|
+
console.log("Connection already in progress, waiting before initializing");
|
|
21
|
+
setTimeout(() => this.initWebSocket(), 500);
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
this.initWebSocket();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
else if (!newRealTimeSync) {
|
|
28
|
+
console.log("Deactivating realtime updates");
|
|
29
|
+
if (this.socket.connected) {
|
|
30
|
+
console.log("Disconnecting socket");
|
|
31
|
+
this.socket.disconnect();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
this.baseUrl = host;
|
|
36
|
+
const socketUrl = host.includes('://') ? host : `http://${host}`;
|
|
37
|
+
// Don't append port twice if it's already in the URL
|
|
38
|
+
const socketUrlWithPort = socketUrl.includes(':') && !socketUrl.endsWith(':')
|
|
39
|
+
? socketUrl
|
|
40
|
+
: `${socketUrl}:${port}`;
|
|
41
|
+
console.log(`Initializing Socket.IO with URL: ${socketUrlWithPort}, path: /socket.io`);
|
|
42
|
+
this.socket = io(`${socketUrlWithPort}`, {
|
|
43
|
+
autoConnect: false,
|
|
44
|
+
transports: ['websocket'], // Try websocket only first
|
|
45
|
+
reconnection: true,
|
|
46
|
+
reconnectionAttempts: 5,
|
|
47
|
+
reconnectionDelay: 1000,
|
|
48
|
+
forceNew: true, // Force a new connection
|
|
49
|
+
auth: {
|
|
50
|
+
token: null // Will be set later
|
|
51
|
+
},
|
|
52
|
+
path: '/socket.io'
|
|
53
|
+
});
|
|
54
|
+
this.callbackFunction = callback;
|
|
55
|
+
this.setupPermanentSocketListeners();
|
|
56
|
+
}
|
|
57
|
+
setupPermanentSocketListeners() {
|
|
58
|
+
// These are permanent listeners that won't be removed
|
|
59
|
+
this.socket.on('connect_error', (error) => {
|
|
60
|
+
console.error('Socket connection error:', error.message);
|
|
61
|
+
this.connectionInProgress = false;
|
|
62
|
+
});
|
|
63
|
+
this.socket.on('connect', () => {
|
|
64
|
+
console.log('Socket connected successfully with ID:', this.socket.id);
|
|
65
|
+
this.connectionInProgress = false;
|
|
66
|
+
});
|
|
67
|
+
this.socket.on('disconnect', (reason) => {
|
|
68
|
+
console.log('Socket disconnected. Reason:', reason);
|
|
69
|
+
this.connectionInProgress = false;
|
|
70
|
+
});
|
|
71
|
+
this.socket.on('error', (error) => {
|
|
72
|
+
console.error('Socket error:', error);
|
|
73
|
+
this.connectionInProgress = false;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
initWebSocket() {
|
|
77
|
+
console.log("initWebSocket called. Auth token present:", !!this.authToken, "Connection in progress:", this.connectionInProgress, "Socket connected:", this.socket.connected);
|
|
78
|
+
if (!this.authToken) {
|
|
79
|
+
console.log("Skipping WebSocket initialization: No auth token");
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (this.connectionInProgress) {
|
|
83
|
+
console.log("Connection already in progress, skipping initialization");
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (this.socket.connected) {
|
|
87
|
+
console.log("Socket already connected with ID:", this.socket.id);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
this.connectionInProgress = true;
|
|
91
|
+
try {
|
|
92
|
+
console.log("Setting up WebSocket connection with token");
|
|
93
|
+
// Update the auth token
|
|
94
|
+
this.socket.auth = { token: this.authToken };
|
|
95
|
+
// Remove any dynamic event listeners that might have been added
|
|
96
|
+
this.socket.offAny();
|
|
97
|
+
// Set up event handler for application events
|
|
15
98
|
this.socket.onAny((event, data) => {
|
|
16
99
|
if (event === "heartbeatPing") {
|
|
17
100
|
console.log("Ping event received:", data);
|
|
18
101
|
this.socket.emit("heartbeatPong", Date.now());
|
|
19
102
|
}
|
|
20
|
-
else {
|
|
21
|
-
|
|
103
|
+
else if (this.callbackFunction) {
|
|
104
|
+
this.callbackFunction(event, data);
|
|
22
105
|
}
|
|
23
106
|
});
|
|
107
|
+
// Connect to the server
|
|
108
|
+
console.log("Connecting socket with auth token");
|
|
109
|
+
this.socket.connect();
|
|
110
|
+
// Add a timeout to detect if connection is taking too long
|
|
111
|
+
setTimeout(() => {
|
|
112
|
+
if (this.connectionInProgress) {
|
|
113
|
+
console.warn("Socket connection attempt timed out after 5 seconds");
|
|
114
|
+
this.connectionInProgress = false;
|
|
115
|
+
// If we're still not connected after the timeout, try again with polling
|
|
116
|
+
if (!this.socket.connected) {
|
|
117
|
+
console.log("Retrying connection with polling transport");
|
|
118
|
+
this.socket.io.opts.transports = ['polling', 'websocket'];
|
|
119
|
+
this.socket.connect();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}, 5000);
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
console.error('Error in initWebSocket:', error);
|
|
126
|
+
this.connectionInProgress = false;
|
|
24
127
|
}
|
|
25
128
|
}
|
|
26
129
|
async request(endpoint, method, body, requiresAuth = true) {
|
|
27
130
|
const headers = {
|
|
28
|
-
'Content-Type': 'application/json'
|
|
131
|
+
'Content-Type': 'application/json',
|
|
29
132
|
};
|
|
30
|
-
if (requiresAuth && this.
|
|
31
|
-
headers['Authorization'] = `Bearer ${this.
|
|
32
|
-
|
|
133
|
+
if (requiresAuth && this.authToken)
|
|
134
|
+
headers['Authorization'] = `Bearer ${this.authToken}`;
|
|
135
|
+
if (this.socket.id)
|
|
136
|
+
headers['X-Socket-ID'] = this.socket.id;
|
|
33
137
|
const options = {
|
|
34
138
|
method,
|
|
35
139
|
headers,
|
|
36
140
|
body: body ? JSON.stringify(body) : undefined
|
|
37
141
|
};
|
|
38
|
-
|
|
142
|
+
// Ensure endpoint starts with /
|
|
143
|
+
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
|
|
144
|
+
// Ensure baseUrl doesn't end with /
|
|
145
|
+
const normalizedBaseUrl = this.baseUrl.endsWith('/') ? this.baseUrl.slice(0, -1) : this.baseUrl;
|
|
146
|
+
const url = `${normalizedBaseUrl}${normalizedEndpoint}`;
|
|
147
|
+
console.log(`Making ${method} request to: ${url}`);
|
|
148
|
+
const response = await fetch(url, options);
|
|
39
149
|
if (!response.ok) {
|
|
40
150
|
if (response.status === 401 || response.status === 403) {
|
|
41
|
-
this.
|
|
151
|
+
this.authToken = null;
|
|
42
152
|
}
|
|
43
153
|
throw new Error(`API error: ${response.status} ${response.statusText}`);
|
|
44
154
|
}
|
|
@@ -48,7 +158,11 @@ class Index {
|
|
|
48
158
|
async login(credentials) {
|
|
49
159
|
const response = await this.request('/users/login', 'POST', credentials, false);
|
|
50
160
|
if (response.token) {
|
|
51
|
-
this.
|
|
161
|
+
this.authToken = response.token;
|
|
162
|
+
// Reconnect websocket with new token if realtime sync is enabled
|
|
163
|
+
if (this.realTimeSync) {
|
|
164
|
+
this.initWebSocket();
|
|
165
|
+
}
|
|
52
166
|
return { token: response.token, isAdmin: response.isAdmin };
|
|
53
167
|
}
|
|
54
168
|
return null;
|
|
@@ -94,15 +208,60 @@ class Index {
|
|
|
94
208
|
async removeStructure(structureID) {
|
|
95
209
|
await this.request(`/structures/remove/${structureID}`, 'DELETE');
|
|
96
210
|
}
|
|
97
|
-
|
|
98
|
-
|
|
211
|
+
// Data Type Endpoints
|
|
212
|
+
async createType(type) {
|
|
213
|
+
return await this.request('/types/write', 'POST', type);
|
|
214
|
+
}
|
|
215
|
+
async removeType(typeID) {
|
|
216
|
+
return await this.request(`/types/remove/${typeID}`, 'DELETE');
|
|
99
217
|
}
|
|
100
|
-
|
|
101
|
-
return this.
|
|
218
|
+
async getTypes() {
|
|
219
|
+
return await this.request('/types/list', 'GET');
|
|
220
|
+
}
|
|
221
|
+
setToken(token) {
|
|
222
|
+
console.log("Setting token to:", token ? "***token***" : "null");
|
|
223
|
+
const tokenChanged = this.authToken !== token;
|
|
224
|
+
this.authToken = token;
|
|
225
|
+
if (!tokenChanged) {
|
|
226
|
+
console.log("Token unchanged, no need to reconnect");
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
// If we have a new token and realtime sync is enabled
|
|
230
|
+
if (token && this.realTimeSync) {
|
|
231
|
+
console.log("New token set, will initialize WebSocket");
|
|
232
|
+
// Ensure any existing connection is closed first
|
|
233
|
+
if (this.socket.connected) {
|
|
234
|
+
console.log("Disconnecting existing socket before reconnecting with new token");
|
|
235
|
+
this.socket.disconnect();
|
|
236
|
+
}
|
|
237
|
+
// Wait a moment for the disconnect to complete
|
|
238
|
+
setTimeout(() => {
|
|
239
|
+
console.log("Initializing WebSocket with new token");
|
|
240
|
+
this.initWebSocket();
|
|
241
|
+
}, 300);
|
|
242
|
+
}
|
|
243
|
+
// If token was cleared or realtime sync is disabled
|
|
244
|
+
else if (this.socket.connected) {
|
|
245
|
+
console.log("Token cleared or realtime sync disabled, disconnecting");
|
|
246
|
+
this.socket.disconnect();
|
|
247
|
+
}
|
|
102
248
|
}
|
|
103
249
|
getVersion() {
|
|
104
|
-
return
|
|
250
|
+
return packetJson.version;
|
|
251
|
+
}
|
|
252
|
+
debugSocketConnection() {
|
|
253
|
+
console.log("Socket connection debug info:");
|
|
254
|
+
console.log("- Connected:", this.socket.connected);
|
|
255
|
+
console.log("- Socket ID:", this.socket.id);
|
|
256
|
+
console.log("- Auth token present:", !!this.authToken);
|
|
257
|
+
console.log("- Connection in progress:", this.connectionInProgress);
|
|
258
|
+
console.log("- Realtime sync enabled:", this.realTimeSync);
|
|
259
|
+
console.log("- Socket options:", this.socket.io.opts);
|
|
260
|
+
// Try to force reconnection
|
|
261
|
+
if (!this.socket.connected && this.authToken && this.realTimeSync) {
|
|
262
|
+
console.log("Attempting to force reconnection...");
|
|
263
|
+
this.socket.auth = { token: this.authToken };
|
|
264
|
+
this.socket.connect();
|
|
265
|
+
}
|
|
105
266
|
}
|
|
106
267
|
}
|
|
107
|
-
exports.default = Index;
|
|
108
|
-
module.exports = Index;
|
package/dist/types.d.ts
CHANGED
|
@@ -84,7 +84,15 @@ export interface I_StructureUpdate {
|
|
|
84
84
|
reference?: any;
|
|
85
85
|
fields?: any[];
|
|
86
86
|
}
|
|
87
|
-
export
|
|
87
|
+
export interface I_DocumentType {
|
|
88
|
+
_id?: string;
|
|
89
|
+
type: number;
|
|
90
|
+
subType: number;
|
|
91
|
+
name: string;
|
|
92
|
+
description?: string;
|
|
93
|
+
defaultStructureID?: string;
|
|
94
|
+
}
|
|
95
|
+
export type I_EventString = 'subscribe' | 'unsubscribe' | 'heartbeatPong' | "heartbeatPing" | "newDocument" | "newStructure" | "newUser" | "removedID" | "changedDocument" | "changedStructure" | "changedUser" | "confirmSubscription" | "confirmUnsubscription" | "removedUser" | "removedStructure" | "removedDocument";
|
|
88
96
|
export interface I_WsMessage {
|
|
89
97
|
newDocument?: I_DocumentEntry;
|
|
90
98
|
newStructure?: I_StructureEntry;
|
package/dist/types.js
CHANGED
package/package.json
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "docpouch-client",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.4",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"import": "./dist/index.js",
|
|
9
|
+
"require": "./dist/index.js"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"type": "module",
|
|
6
13
|
"scripts": {
|
|
7
14
|
"build": "tsc",
|
|
8
15
|
"test": "jest"
|
|
@@ -15,13 +22,13 @@
|
|
|
15
22
|
"license": "MIT",
|
|
16
23
|
"description": "A small class to more easily access the docPouch API",
|
|
17
24
|
"devDependencies": {
|
|
18
|
-
"@types/
|
|
19
|
-
"
|
|
20
|
-
"jest": "^
|
|
21
|
-
"ts-jest": "^29.
|
|
22
|
-
"@types/jest": "^29.5.14"
|
|
25
|
+
"@types/jest": "^29.5.14",
|
|
26
|
+
"@types/node": "^24.0.1",
|
|
27
|
+
"jest": "^30.0.0",
|
|
28
|
+
"ts-jest": "^29.4.0"
|
|
23
29
|
},
|
|
24
30
|
"dependencies": {
|
|
31
|
+
"socket.io-client": "^4.8.1",
|
|
25
32
|
"typescript": "^5.8.3"
|
|
26
33
|
}
|
|
27
|
-
}
|
|
34
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import dbPouchClient from '../index.js';
|
|
2
2
|
import packetJson from '../../package.json';
|
|
3
3
|
import {
|
|
4
4
|
I_UserLogin,
|
|
@@ -28,7 +28,7 @@ global.fetch = jest.fn();
|
|
|
28
28
|
const mockFetch = global.fetch as jest.Mock;
|
|
29
29
|
|
|
30
30
|
describe('Index Class', () => {
|
|
31
|
-
let index:
|
|
31
|
+
let index: dbPouchClient;
|
|
32
32
|
const baseUrl = 'http://example.com';
|
|
33
33
|
|
|
34
34
|
beforeEach(() => {
|
|
@@ -37,7 +37,7 @@ describe('Index Class', () => {
|
|
|
37
37
|
mockFetch.mockClear();
|
|
38
38
|
|
|
39
39
|
// Create a new instance of Index for each test
|
|
40
|
-
index = new
|
|
40
|
+
index = new dbPouchClient(baseUrl);
|
|
41
41
|
|
|
42
42
|
// Mock successful fetch response
|
|
43
43
|
mockFetch.mockImplementation(() =>
|
|
@@ -62,7 +62,7 @@ describe('Index Class', () => {
|
|
|
62
62
|
|
|
63
63
|
it('should connect socket and set up event handler when callback is provided', () => {
|
|
64
64
|
const mockCallback = jest.fn();
|
|
65
|
-
const indexWithCallback = new
|
|
65
|
+
const indexWithCallback = new dbPouchClient(baseUrl, mockCallback);
|
|
66
66
|
|
|
67
67
|
expect(indexWithCallback.socket.connect).toHaveBeenCalled();
|
|
68
68
|
expect(indexWithCallback.socket.onAny).toHaveBeenCalled();
|
|
@@ -86,7 +86,7 @@ describe('Index Class', () => {
|
|
|
86
86
|
jest.mock('../../package.json', () => ({ version: packetJson.version }), { virtual: true });
|
|
87
87
|
|
|
88
88
|
// We need to re-create the index instance to pick up the mocked package.json
|
|
89
|
-
const newIndex = new
|
|
89
|
+
const newIndex = new dbPouchClient(baseUrl);
|
|
90
90
|
expect(newIndex.getVersion()).toBe(packetJson.version);
|
|
91
91
|
});
|
|
92
92
|
});
|
|
@@ -472,7 +472,7 @@ describe('Index Class', () => {
|
|
|
472
472
|
describe('WebSocket functionality', () => {
|
|
473
473
|
it('should connect socket when callback is provided', () => {
|
|
474
474
|
const mockCallback = jest.fn();
|
|
475
|
-
const indexWithCallback = new
|
|
475
|
+
const indexWithCallback = new dbPouchClient(baseUrl, mockCallback);
|
|
476
476
|
|
|
477
477
|
// Verify that connect was called
|
|
478
478
|
expect(indexWithCallback.socket.connect).toHaveBeenCalled();
|
|
@@ -480,7 +480,7 @@ describe('Index Class', () => {
|
|
|
480
480
|
|
|
481
481
|
it('should set up event handler when callback is provided', () => {
|
|
482
482
|
const mockCallback = jest.fn();
|
|
483
|
-
const indexWithCallback = new
|
|
483
|
+
const indexWithCallback = new dbPouchClient(baseUrl, mockCallback);
|
|
484
484
|
|
|
485
485
|
// Verify that onAny was called
|
|
486
486
|
expect(indexWithCallback.socket.onAny).toHaveBeenCalled();
|
package/src/index.ts
CHANGED
|
@@ -6,42 +6,179 @@ import type {
|
|
|
6
6
|
I_UserDisplay,
|
|
7
7
|
I_DocumentEntry,
|
|
8
8
|
I_DataStructure,
|
|
9
|
-
I_LoginResponse, I_DocumentQuery, I_StructureCreation, I_WsMessage, I_EventString
|
|
9
|
+
I_LoginResponse, I_DocumentQuery, I_StructureCreation, I_WsMessage, I_EventString, I_DocumentType
|
|
10
10
|
} from "./types.js";
|
|
11
11
|
import {io, Socket} from "socket.io-client";
|
|
12
12
|
import packetJson from '../package.json'
|
|
13
13
|
|
|
14
|
-
export default class
|
|
14
|
+
export default class dbPouchClient {
|
|
15
15
|
baseUrl: string;
|
|
16
|
-
private
|
|
17
|
-
socket: Socket
|
|
16
|
+
private authToken: string | null = null;
|
|
17
|
+
socket: Socket;
|
|
18
|
+
callbackFunction;
|
|
19
|
+
realTimeSync: boolean = false;
|
|
20
|
+
private connectionInProgress = false;
|
|
18
21
|
|
|
19
|
-
constructor(baseUrl: string, callback?: (event: I_EventString, data: I_WsMessage) => void) {
|
|
20
|
-
this.baseUrl = baseUrl;
|
|
21
22
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
23
|
+
constructor(host: string, port: number = 80, callback?: (event: I_EventString, data: I_WsMessage) => void) {
|
|
24
|
+
this.baseUrl = host;
|
|
25
|
+
|
|
26
|
+
const socketUrl = host.includes('://') ? host : `http://${host}`;
|
|
27
|
+
|
|
28
|
+
// Don't append port twice if it's already in the URL
|
|
29
|
+
const socketUrlWithPort = socketUrl.includes(':') && !socketUrl.endsWith(':')
|
|
30
|
+
? socketUrl
|
|
31
|
+
: `${socketUrl}:${port}`;
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
console.log(`Initializing Socket.IO with URL: ${socketUrlWithPort}, path: /socket.io`);
|
|
35
|
+
|
|
36
|
+
this.socket = io(`${socketUrlWithPort}`, {
|
|
37
|
+
autoConnect: false,
|
|
38
|
+
transports: ['websocket'], // Try websocket only first
|
|
39
|
+
reconnection: true,
|
|
40
|
+
reconnectionAttempts: 5,
|
|
41
|
+
reconnectionDelay: 1000,
|
|
42
|
+
forceNew: true, // Force a new connection
|
|
43
|
+
auth: {
|
|
44
|
+
token: null // Will be set later
|
|
45
|
+
},
|
|
46
|
+
path: '/socket.io'
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
this.callbackFunction = callback;
|
|
50
|
+
|
|
51
|
+
this.setupPermanentSocketListeners();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
private setupPermanentSocketListeners() {
|
|
55
|
+
// These are permanent listeners that won't be removed
|
|
56
|
+
this.socket.on('connect_error', (error) => {
|
|
57
|
+
console.error('Socket connection error:', error.message);
|
|
58
|
+
this.connectionInProgress = false;
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
this.socket.on('connect', () => {
|
|
62
|
+
console.log('Socket connected successfully with ID:', this.socket.id);
|
|
63
|
+
this.connectionInProgress = false;
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
this.socket.on('disconnect', (reason) => {
|
|
67
|
+
console.log('Socket disconnected. Reason:', reason);
|
|
68
|
+
this.connectionInProgress = false;
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
this.socket.on('error', (error) => {
|
|
72
|
+
console.error('Socket error:', error);
|
|
73
|
+
this.connectionInProgress = false;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
setRealTimeSync = (newRealTimeSync: boolean) => {
|
|
78
|
+
console.log(`Setting realtime sync to: ${newRealTimeSync}. Current setting: ${this.realTimeSync}`);
|
|
79
|
+
|
|
80
|
+
// Skip if the setting isn't changing
|
|
81
|
+
if (newRealTimeSync === this.realTimeSync) {
|
|
82
|
+
console.log("Realtime sync setting unchanged, skipping");
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
this.realTimeSync = newRealTimeSync;
|
|
87
|
+
|
|
88
|
+
if (newRealTimeSync && this.authToken) {
|
|
89
|
+
console.log("Activating realtime updates");
|
|
90
|
+
|
|
91
|
+
// Ensure we're not in the middle of another connection attempt
|
|
92
|
+
if (this.connectionInProgress) {
|
|
93
|
+
console.log("Connection already in progress, waiting before initializing");
|
|
94
|
+
setTimeout(() => this.initWebSocket(), 500);
|
|
95
|
+
} else {
|
|
96
|
+
this.initWebSocket();
|
|
97
|
+
}
|
|
98
|
+
} else if (!newRealTimeSync) {
|
|
99
|
+
console.log("Deactivating realtime updates");
|
|
100
|
+
if (this.socket.connected) {
|
|
101
|
+
console.log("Disconnecting socket");
|
|
102
|
+
this.socket.disconnect();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private initWebSocket() {
|
|
108
|
+
console.log("initWebSocket called. Auth token present:", !!this.authToken,
|
|
109
|
+
"Connection in progress:", this.connectionInProgress,
|
|
110
|
+
"Socket connected:", this.socket.connected);
|
|
111
|
+
|
|
112
|
+
if (!this.authToken) {
|
|
113
|
+
console.log("Skipping WebSocket initialization: No auth token");
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (this.connectionInProgress) {
|
|
118
|
+
console.log("Connection already in progress, skipping initialization");
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (this.socket.connected) {
|
|
123
|
+
console.log("Socket already connected with ID:", this.socket.id);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
this.connectionInProgress = true;
|
|
128
|
+
|
|
129
|
+
try {
|
|
130
|
+
console.log("Setting up WebSocket connection with token");
|
|
131
|
+
|
|
132
|
+
// Update the auth token
|
|
133
|
+
this.socket.auth = { token: this.authToken };
|
|
134
|
+
|
|
135
|
+
// Remove any dynamic event listeners that might have been added
|
|
136
|
+
this.socket.offAny();
|
|
137
|
+
|
|
138
|
+
// Set up event handler for application events
|
|
25
139
|
this.socket.onAny((event: I_EventString, data: I_WsMessage) => {
|
|
26
140
|
if (event === "heartbeatPing") {
|
|
27
141
|
console.log("Ping event received:", data);
|
|
28
142
|
this.socket.emit("heartbeatPong", Date.now());
|
|
29
143
|
}
|
|
30
|
-
else {
|
|
31
|
-
|
|
144
|
+
else if (this.callbackFunction){
|
|
145
|
+
this.callbackFunction(event, data);
|
|
32
146
|
}
|
|
33
147
|
});
|
|
148
|
+
|
|
149
|
+
// Connect to the server
|
|
150
|
+
console.log("Connecting socket with auth token");
|
|
151
|
+
this.socket.connect();
|
|
152
|
+
|
|
153
|
+
// Add a timeout to detect if connection is taking too long
|
|
154
|
+
setTimeout(() => {
|
|
155
|
+
if (this.connectionInProgress) {
|
|
156
|
+
console.warn("Socket connection attempt timed out after 5 seconds");
|
|
157
|
+
this.connectionInProgress = false;
|
|
158
|
+
|
|
159
|
+
// If we're still not connected after the timeout, try again with polling
|
|
160
|
+
if (!this.socket.connected) {
|
|
161
|
+
console.log("Retrying connection with polling transport");
|
|
162
|
+
this.socket.io.opts.transports = ['polling', 'websocket'];
|
|
163
|
+
this.socket.connect();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}, 5000);
|
|
167
|
+
} catch (error) {
|
|
168
|
+
console.error('Error in initWebSocket:', error);
|
|
169
|
+
this.connectionInProgress = false;
|
|
34
170
|
}
|
|
35
171
|
}
|
|
36
172
|
|
|
37
173
|
private async request<T>(endpoint: string, method: string, body?: any, requiresAuth: boolean = true): Promise<T> {
|
|
38
174
|
const headers: HeadersInit = {
|
|
39
|
-
'Content-Type': 'application/json'
|
|
175
|
+
'Content-Type': 'application/json',
|
|
40
176
|
};
|
|
41
177
|
|
|
42
|
-
if (requiresAuth && this.
|
|
43
|
-
headers['Authorization'] = `Bearer ${this.
|
|
44
|
-
|
|
178
|
+
if (requiresAuth && this.authToken)
|
|
179
|
+
headers['Authorization'] = `Bearer ${this.authToken}`;
|
|
180
|
+
if (this.socket.id)
|
|
181
|
+
headers['X-Socket-ID'] = this.socket.id;
|
|
45
182
|
|
|
46
183
|
const options: RequestInit = {
|
|
47
184
|
method,
|
|
@@ -49,11 +186,19 @@ export default class Index {
|
|
|
49
186
|
body: body ? JSON.stringify(body) : undefined
|
|
50
187
|
};
|
|
51
188
|
|
|
52
|
-
|
|
189
|
+
// Ensure endpoint starts with /
|
|
190
|
+
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
|
|
191
|
+
// Ensure baseUrl doesn't end with /
|
|
192
|
+
const normalizedBaseUrl = this.baseUrl.endsWith('/') ? this.baseUrl.slice(0, -1) : this.baseUrl;
|
|
193
|
+
|
|
194
|
+
const url = `${normalizedBaseUrl}${normalizedEndpoint}`;
|
|
195
|
+
console.log(`Making ${method} request to: ${url}`);
|
|
196
|
+
|
|
197
|
+
const response = await fetch(url, options);
|
|
53
198
|
|
|
54
199
|
if (!response.ok) {
|
|
55
200
|
if (response.status === 401 || response.status === 403) {
|
|
56
|
-
this.
|
|
201
|
+
this.authToken = null;
|
|
57
202
|
}
|
|
58
203
|
throw new Error(`API error: ${response.status} ${response.statusText}`);
|
|
59
204
|
}
|
|
@@ -65,7 +210,13 @@ export default class Index {
|
|
|
65
210
|
async login(credentials: I_UserLogin): Promise<I_LoginResponse | null> {
|
|
66
211
|
const response = await this.request<I_LoginResponse>('/users/login', 'POST', credentials, false);
|
|
67
212
|
if (response.token) {
|
|
68
|
-
this.
|
|
213
|
+
this.authToken = response.token;
|
|
214
|
+
|
|
215
|
+
// Reconnect websocket with new token if realtime sync is enabled
|
|
216
|
+
if (this.realTimeSync) {
|
|
217
|
+
this.initWebSocket();
|
|
218
|
+
}
|
|
219
|
+
|
|
69
220
|
return {token: response.token, isAdmin: response.isAdmin};
|
|
70
221
|
}
|
|
71
222
|
return null;
|
|
@@ -125,17 +276,72 @@ export default class Index {
|
|
|
125
276
|
await this.request<void>(`/structures/remove/${structureID}`, 'DELETE');
|
|
126
277
|
}
|
|
127
278
|
|
|
128
|
-
|
|
129
|
-
|
|
279
|
+
// Data Type Endpoints
|
|
280
|
+
async createType(type: I_DocumentType): Promise<I_DocumentType> {
|
|
281
|
+
return await this.request<I_DocumentType>('/types/write', 'POST', type);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async removeType(typeID: string) {
|
|
285
|
+
return await this.request<void>(`/types/remove/${typeID}`, 'DELETE');
|
|
130
286
|
}
|
|
131
287
|
|
|
132
|
-
|
|
133
|
-
return this.
|
|
288
|
+
async getTypes(): Promise<I_DocumentType[]> {
|
|
289
|
+
return await this.request<I_DocumentType[]>('/types/list', 'GET');
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
setToken(token: string | null): void {
|
|
293
|
+
console.log("Setting token to:", token ? "***token***" : "null");
|
|
294
|
+
|
|
295
|
+
const tokenChanged = this.authToken !== token;
|
|
296
|
+
this.authToken = token;
|
|
297
|
+
|
|
298
|
+
if (!tokenChanged) {
|
|
299
|
+
console.log("Token unchanged, no need to reconnect");
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// If we have a new token and realtime sync is enabled
|
|
304
|
+
if (token && this.realTimeSync) {
|
|
305
|
+
console.log("New token set, will initialize WebSocket");
|
|
306
|
+
|
|
307
|
+
// Ensure any existing connection is closed first
|
|
308
|
+
if (this.socket.connected) {
|
|
309
|
+
console.log("Disconnecting existing socket before reconnecting with new token");
|
|
310
|
+
this.socket.disconnect();
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// Wait a moment for the disconnect to complete
|
|
314
|
+
setTimeout(() => {
|
|
315
|
+
console.log("Initializing WebSocket with new token");
|
|
316
|
+
this.initWebSocket();
|
|
317
|
+
}, 300);
|
|
318
|
+
}
|
|
319
|
+
// If token was cleared or realtime sync is disabled
|
|
320
|
+
else if (this.socket.connected) {
|
|
321
|
+
console.log("Token cleared or realtime sync disabled, disconnecting");
|
|
322
|
+
this.socket.disconnect();
|
|
323
|
+
}
|
|
134
324
|
}
|
|
135
325
|
|
|
136
326
|
getVersion() {
|
|
137
327
|
return packetJson.version;
|
|
138
328
|
}
|
|
139
|
-
}
|
|
140
329
|
|
|
141
|
-
|
|
330
|
+
debugSocketConnection(): void {
|
|
331
|
+
console.log("Socket connection debug info:");
|
|
332
|
+
console.log("- Connected:", this.socket.connected);
|
|
333
|
+
console.log("- Socket ID:", this.socket.id);
|
|
334
|
+
console.log("- Auth token present:", !!this.authToken);
|
|
335
|
+
console.log("- Connection in progress:", this.connectionInProgress);
|
|
336
|
+
console.log("- Realtime sync enabled:", this.realTimeSync);
|
|
337
|
+
console.log("- Socket options:", this.socket.io.opts);
|
|
338
|
+
|
|
339
|
+
// Try to force reconnection
|
|
340
|
+
if (!this.socket.connected && this.authToken && this.realTimeSync) {
|
|
341
|
+
console.log("Attempting to force reconnection...");
|
|
342
|
+
this.socket.auth = { token: this.authToken };
|
|
343
|
+
this.socket.connect();
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -104,10 +104,20 @@ export interface I_StructureUpdate {
|
|
|
104
104
|
fields?: any[];
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
+
// Document type related types
|
|
108
|
+
export interface I_DocumentType {
|
|
109
|
+
_id?: string;
|
|
110
|
+
type: number;
|
|
111
|
+
subType: number;
|
|
112
|
+
name: string;
|
|
113
|
+
description?: string;
|
|
114
|
+
defaultStructureID?: string;
|
|
115
|
+
}
|
|
116
|
+
|
|
107
117
|
// WebSocket-related types
|
|
108
118
|
export type I_EventString = 'subscribe' | 'unsubscribe' | 'heartbeatPong' | "heartbeatPing" | "newDocument" | "newStructure" |
|
|
109
119
|
"newUser" | "removedID" | "changedDocument" | "changedStructure" | "changedUser" | "confirmSubscription" |
|
|
110
|
-
"confirmUnsubscription";
|
|
120
|
+
"confirmUnsubscription" | "removedUser" | "removedStructure" | "removedDocument";
|
|
111
121
|
|
|
112
122
|
export interface I_WsMessage {
|
|
113
123
|
newDocument?: I_DocumentEntry;
|
package/tsconfig.json
CHANGED
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
"declaration": true,
|
|
14
14
|
"emitDeclarationOnly": false,
|
|
15
15
|
"resolveJsonModule": true,
|
|
16
|
-
"isolatedModules": true
|
|
16
|
+
"isolatedModules": true,
|
|
17
|
+
"allowSyntheticDefaultImports": true
|
|
17
18
|
},
|
|
18
19
|
"include": ["**/*.ts", "**/*.tsx"],
|
|
19
20
|
"exclude": ["node_modules", "**/*.test.ts", "**/*.types.ts", "./dist/**/*"]
|