docpouch-client 0.8.14 → 0.8.15

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 DELETED
@@ -1,207 +0,0 @@
1
- import { Socket } from "socket.io-client";
2
- /**
3
- * Client for interacting with docPouch API.
4
- */
5
- export default class docPouchClient {
6
- /**
7
- * The base URL of the server.
8
- *
9
- * @type {string}
10
- */
11
- baseUrl: string;
12
- /**
13
- * Socket.IO socket instance for real-time communication with the server.
14
- *
15
- * @type {Socket}
16
- */
17
- socket: Socket;
18
- /**
19
- * Callback function to handle socket events.
20
- *
21
- * @type {(event: I_EventString, data: I_WsMessage) => void}
22
- */
23
- callbackFunction: ((event: I_EventString, data: I_WsMessage) => void) | undefined;
24
- /**
25
- * Flag indicating whether real-time synchronization is enabled.
26
- *
27
- * @type {boolean}
28
- */
29
- realTimeSync: boolean;
30
- /**
31
- * Authentication token used to authorize requests.
32
- *
33
- * @private
34
- * @type {string | null}
35
- */
36
- private authToken;
37
- /**
38
- * Flag indicating whether a connection attempt is in progress.
39
- *
40
- * @private
41
- * @type {boolean}
42
- */
43
- private connectionInProgress;
44
- /**
45
- * Creates an instance of docPouchClient.
46
- *
47
- * @param {string} host - The base URL for the server.
48
- * @param {number} [port=80] - The port number to connect to (default is 80).
49
- * @param {(event: I_EventString, data: I_WsMessage) => void} [callback] - Optional callback function for socket events.
50
- */
51
- constructor(host: string, port?: number, callback?: (event: I_EventString, data: I_WsMessage) => void);
52
- /**
53
- * Sets the real-time synchronization status.
54
- *
55
- * @param {boolean} newRealTimeSync - The new real-time sync setting (true/false).
56
- */
57
- setRealTimeSync(newRealTimeSync: boolean): void;
58
- login(credentials: I_UserLogin): Promise<I_LoginResponse | null>;
59
- listUsers(): Promise<I_UserEntry[]>;
60
- updateUser(userID: string, userData: I_UserUpdate): Promise<void>;
61
- createUser(userData: I_UserCreation): Promise<I_UserDisplay>;
62
- removeUser(userID: string): Promise<void>;
63
- createDocument(document: I_DocumentEntry): Promise<I_DocumentEntry>;
64
- listDocuments(): Promise<I_DocumentEntry[]>;
65
- fetchDocuments(queryObject: I_DocumentQuery): Promise<I_DocumentEntry[]>;
66
- updateDocument(documentID: string, documentData: I_DocumentEntry): Promise<void>;
67
- removeDocument(documentID: string): Promise<void>;
68
- createStructure(structure: I_StructureCreation): Promise<I_DataStructure>;
69
- getStructures(): Promise<I_DataStructure[]>;
70
- updateStructure(structureID: string, structureData: I_DataStructure): Promise<void>;
71
- removeStructure(structureID: string): Promise<void>;
72
- createType(type: I_DocumentType): Promise<I_DocumentType>;
73
- removeType(typeID: string): Promise<void>;
74
- getTypes(): Promise<I_DocumentType[]>;
75
- updateType(updatedType: I_DocumentType): Promise<void>;
76
- setToken(token: string | null): void;
77
- getVersion(): string;
78
- debugSocketConnection(): void;
79
- /**
80
- * Sets up permanent socket listeners for the client.
81
- *
82
- * @private
83
- */
84
- private setupPermanentSocketListeners;
85
- /**
86
- * Initializes the WebSocket connection with the server.
87
- *
88
- * @private
89
- */
90
- private initWebSocket;
91
- private request;
92
- }
93
- export interface I_UserEntry extends I_UserCreation {
94
- _id: string;
95
- }
96
- export interface I_UserLogin {
97
- name: string;
98
- password: string;
99
- }
100
- export interface I_UserCreation {
101
- name: string;
102
- password: string;
103
- email?: string;
104
- department: string;
105
- group: string;
106
- isAdmin: boolean;
107
- }
108
- export interface I_UserUpdate {
109
- _id?: string;
110
- name?: string;
111
- password?: string;
112
- email?: string;
113
- department?: string;
114
- group?: string;
115
- isAdmin?: boolean;
116
- }
117
- export interface I_UserDisplay {
118
- _id: string;
119
- username: string;
120
- department: string;
121
- group: string;
122
- email?: string;
123
- }
124
- export interface I_LoginResponse {
125
- token: string;
126
- isAdmin: boolean;
127
- userName: string;
128
- }
129
- export interface I_DocumentEntry extends I_DocumentCreationOwned {
130
- _id: string;
131
- }
132
- export interface I_DocumentCreation {
133
- title: string;
134
- description?: string;
135
- type: number;
136
- subType: number;
137
- content: any;
138
- shareWithGroup: boolean;
139
- shareWithDepartment: boolean;
140
- }
141
- export interface I_DocumentCreationOwned extends I_DocumentCreation {
142
- owner: string;
143
- }
144
- export interface I_DocumentUpdate extends I_DocumentQuery {
145
- content?: any;
146
- description?: string;
147
- }
148
- export interface I_DocumentQuery {
149
- _id?: string;
150
- owner?: string;
151
- title?: string;
152
- type?: number;
153
- subType?: number;
154
- shareWithGroup?: boolean;
155
- shareWithDepartment?: boolean;
156
- }
157
- export interface I_DataStructure {
158
- _id?: string | undefined;
159
- name: string;
160
- description: string;
161
- fields: I_StructureField[];
162
- }
163
- export interface I_StructureField {
164
- name: string;
165
- type: string;
166
- items?: string;
167
- }
168
- export interface I_StructureEntry {
169
- _id?: string;
170
- name: string;
171
- description: string;
172
- fields: I_StructureField[];
173
- }
174
- export interface I_StructureCreation {
175
- name: string;
176
- description?: string;
177
- fields: I_StructureField[];
178
- }
179
- export interface I_StructureUpdate {
180
- _id?: string;
181
- name?: string;
182
- description?: string;
183
- fields?: I_StructureField[];
184
- }
185
- export interface I_DocumentType {
186
- _id?: string;
187
- type: number;
188
- subType: number;
189
- name: string;
190
- description?: string;
191
- defaultStructureID?: string;
192
- }
193
- export type I_EventString = 'heartbeatPong' | "heartbeatPing" | "newDocument" | "newStructure" | "newUser" | "newType" | "removedID" | "changedDocument" | "changedStructure" | "changedUser" | "changedType" | "removedUser" | "removedStructure" | "removedDocument" | "removedType";
194
- export interface I_WsMessage {
195
- newDocument?: I_DocumentEntry;
196
- newStructure?: I_StructureEntry;
197
- newUser?: I_UserEntry;
198
- removedID?: string;
199
- changedDocument?: I_DocumentUpdate;
200
- changedStructure?: I_StructureUpdate;
201
- changedUser?: I_UserUpdate;
202
- confirmSubscription?: boolean;
203
- confirmUnsubscription?: boolean;
204
- heartbeatPing?: number;
205
- heartbeatPong?: number;
206
- newType?: I_DocumentType;
207
- }
package/dist/index.js DELETED
@@ -1,308 +0,0 @@
1
- import { io } from "socket.io-client";
2
- import packetJson from '../package.json';
3
- /**
4
- * Client for interacting with docPouch API.
5
- */
6
- export default class docPouchClient {
7
- /**
8
- * Creates an instance of docPouchClient.
9
- *
10
- * @param {string} host - The base URL for the server.
11
- * @param {number} [port=80] - The port number to connect to (default is 80).
12
- * @param {(event: I_EventString, data: I_WsMessage) => void} [callback] - Optional callback function for socket events.
13
- */
14
- constructor(host, port = 80, callback) {
15
- /**
16
- * Flag indicating whether real-time synchronization is enabled.
17
- *
18
- * @type {boolean}
19
- */
20
- this.realTimeSync = false;
21
- /**
22
- * Authentication token used to authorize requests.
23
- *
24
- * @private
25
- * @type {string | null}
26
- */
27
- this.authToken = null;
28
- /**
29
- * Flag indicating whether a connection attempt is in progress.
30
- *
31
- * @private
32
- * @type {boolean}
33
- */
34
- this.connectionInProgress = false;
35
- this.baseUrl = host;
36
- const socketUrl = host.includes('://') ? host : `https://${host}`;
37
- const socketUrlWithPort = socketUrl.includes(':') && !socketUrl.endsWith(':')
38
- ? socketUrl
39
- : `${socketUrl}:${port}`;
40
- console.log(`Initializing Socket.IO with URL: ${socketUrlWithPort}, path: /socket.io`);
41
- this.socket = io(`${socketUrlWithPort}`, {
42
- autoConnect: false,
43
- transports: ['websocket'], // Try websocket only first
44
- reconnection: true,
45
- reconnectionAttempts: 5,
46
- reconnectionDelay: 1000,
47
- forceNew: true, // Force a new connection
48
- auth: {
49
- token: null // Will be set later
50
- },
51
- path: '/socket.io'
52
- });
53
- this.callbackFunction = callback;
54
- this.setupPermanentSocketListeners();
55
- }
56
- /**
57
- * Sets the real-time synchronization status.
58
- *
59
- * @param {boolean} newRealTimeSync - The new real-time sync setting (true/false).
60
- */
61
- setRealTimeSync(newRealTimeSync) {
62
- console.log(`Setting realtime sync to: ${newRealTimeSync}. Current setting: ${this.realTimeSync}`);
63
- // Skip if the setting isn't changing
64
- if (newRealTimeSync === this.realTimeSync) {
65
- console.log("Realtime sync setting unchanged, skipping");
66
- return;
67
- }
68
- this.realTimeSync = newRealTimeSync;
69
- if (newRealTimeSync && this.authToken) {
70
- console.log("Activating realtime updates");
71
- // Ensure we're not in the middle of another connection attempt
72
- if (this.connectionInProgress) {
73
- console.log("Connection already in progress, waiting before initializing");
74
- setTimeout(() => this.initWebSocket(), 500);
75
- }
76
- else {
77
- this.initWebSocket();
78
- }
79
- }
80
- else if (!newRealTimeSync) {
81
- console.log("Deactivating realtime updates");
82
- if (this.socket.connected) {
83
- console.log("Disconnecting socket");
84
- this.socket.disconnect();
85
- }
86
- }
87
- }
88
- // User Administration Endpoints
89
- async login(credentials) {
90
- const response = await this.request('/users/login', 'POST', credentials, false);
91
- if (response.token) {
92
- this.authToken = response.token;
93
- // Reconnect websocket with new token if realtime sync is enabled
94
- if (this.realTimeSync) {
95
- this.initWebSocket();
96
- }
97
- return { token: response.token, isAdmin: response.isAdmin, userName: response.userName };
98
- }
99
- return null;
100
- }
101
- async listUsers() {
102
- return await this.request('/users/list', 'GET');
103
- }
104
- async updateUser(userID, userData) {
105
- await this.request(`/users/update/${userID}`, 'PATCH', userData);
106
- }
107
- async createUser(userData) {
108
- return await this.request('/users/create', 'POST', userData);
109
- }
110
- async removeUser(userID) {
111
- await this.request(`/users/remove/${userID}`, 'DELETE');
112
- }
113
- // Document Management Endpoints
114
- async createDocument(document) {
115
- return await this.request('/docs/create', 'POST', document);
116
- }
117
- async listDocuments() {
118
- return await this.request('/docs/list', 'GET');
119
- }
120
- async fetchDocuments(queryObject) {
121
- return await this.request(`/docs/fetch/`, 'POST', queryObject);
122
- }
123
- async updateDocument(documentID, documentData) {
124
- await this.request(`/docs/update/${documentID}`, 'PATCH', documentData);
125
- }
126
- async removeDocument(documentID) {
127
- await this.request(`/docs/remove/${documentID}`, 'DELETE');
128
- }
129
- // Data Structure Endpoints
130
- async createStructure(structure) {
131
- return await this.request('/structures/create', 'POST', structure);
132
- }
133
- async getStructures() {
134
- return await this.request('/structures/list', 'GET');
135
- }
136
- async updateStructure(structureID, structureData) {
137
- await this.request(`/structures/update/${structureID}`, 'PATCH', structureData);
138
- }
139
- async removeStructure(structureID) {
140
- await this.request(`/structures/remove/${structureID}`, 'DELETE');
141
- }
142
- // Data Type Endpoints
143
- async createType(type) {
144
- return await this.request('/types/write', 'POST', type);
145
- }
146
- async removeType(typeID) {
147
- return await this.request(`/types/remove/${typeID}`, 'DELETE');
148
- }
149
- async getTypes() {
150
- return await this.request('/types/list', 'GET');
151
- }
152
- async updateType(updatedType) {
153
- await this.request(`/types/write`, 'POST', updatedType);
154
- }
155
- setToken(token) {
156
- console.log("Setting token to:", token ? "***token***" : "null");
157
- const tokenChanged = this.authToken !== token;
158
- this.authToken = token;
159
- if (!tokenChanged) {
160
- console.log("Token unchanged, no need to reconnect");
161
- return;
162
- }
163
- // If we have a new token and realtime sync is enabled
164
- if (token && this.realTimeSync) {
165
- console.log("New token set, will initialize WebSocket");
166
- // Ensure any existing connection is closed first
167
- if (this.socket.connected) {
168
- console.log("Disconnecting existing socket before reconnecting with new token");
169
- this.socket.disconnect();
170
- }
171
- // Wait a moment for the disconnect to complete
172
- setTimeout(() => {
173
- console.log("Initializing WebSocket with new token");
174
- this.initWebSocket();
175
- }, 300);
176
- }
177
- // If token was cleared or realtime sync is disabled
178
- else if (this.socket.connected) {
179
- console.log("Token cleared or realtime sync disabled, disconnecting");
180
- this.socket.disconnect();
181
- }
182
- }
183
- getVersion() {
184
- return packetJson.version;
185
- }
186
- debugSocketConnection() {
187
- console.log("Socket connection debug info:");
188
- console.log("- Connected:", this.socket.connected);
189
- console.log("- Socket ID:", this.socket.id);
190
- console.log("- Auth token present:", !!this.authToken);
191
- console.log("- Connection in progress:", this.connectionInProgress);
192
- console.log("- Realtime sync enabled:", this.realTimeSync);
193
- console.log("- Socket options:", this.socket.io.opts);
194
- // Try to force reconnection
195
- if (!this.socket.connected && this.authToken && this.realTimeSync) {
196
- console.log("Attempting to force reconnection...");
197
- this.socket.auth = { token: this.authToken };
198
- this.socket.connect();
199
- }
200
- }
201
- /**
202
- * Sets up permanent socket listeners for the client.
203
- *
204
- * @private
205
- */
206
- setupPermanentSocketListeners() {
207
- // These are permanent listeners that won't be removed
208
- this.socket.on('connect_error', (error) => {
209
- console.error('Socket connection error:', error.message);
210
- this.connectionInProgress = false;
211
- });
212
- this.socket.on('connect', () => {
213
- console.log('Socket connected successfully with ID:', this.socket.id);
214
- this.connectionInProgress = false;
215
- });
216
- this.socket.on('disconnect', (reason) => {
217
- console.log('Socket disconnected. Reason:', reason);
218
- this.connectionInProgress = false;
219
- });
220
- this.socket.on('error', (error) => {
221
- console.error('Socket error:', error);
222
- this.connectionInProgress = false;
223
- });
224
- }
225
- /**
226
- * Initializes the WebSocket connection with the server.
227
- *
228
- * @private
229
- */
230
- initWebSocket() {
231
- console.log("initWebSocket called. Auth token present:", !!this.authToken, "Connection in progress:", this.connectionInProgress, "Socket connected:", this.socket.connected);
232
- if (!this.authToken) {
233
- console.log("Skipping WebSocket initialization: No auth token");
234
- return;
235
- }
236
- if (this.connectionInProgress) {
237
- console.log("Connection already in progress, skipping initialization");
238
- return;
239
- }
240
- if (this.socket.connected) {
241
- console.log("Socket already connected with ID:", this.socket.id);
242
- return;
243
- }
244
- this.connectionInProgress = true;
245
- try {
246
- console.log("Setting up WebSocket connection with token");
247
- // Update the auth token
248
- this.socket.auth = { token: this.authToken };
249
- // Remove any dynamic event listeners that might have been added
250
- this.socket.offAny();
251
- // Set up event handler for application events
252
- this.socket.onAny((event, data) => {
253
- if (event === "heartbeatPing") {
254
- console.log("Ping event received:", data);
255
- this.socket.emit("heartbeatPong", Date.now());
256
- }
257
- else if (this.callbackFunction) {
258
- this.callbackFunction(event, data);
259
- }
260
- });
261
- // Connect to the server
262
- console.log("Connecting socket with auth token");
263
- this.socket.connect();
264
- // Add a timeout to detect if connection is taking too long
265
- setTimeout(() => {
266
- if (this.connectionInProgress) {
267
- console.warn("Socket connection attempt timed out after 5 seconds");
268
- this.connectionInProgress = false;
269
- // If we're still not connected after the timeout, try again with polling
270
- if (!this.socket.connected) {
271
- console.log("Retrying connection with polling transport");
272
- this.socket.io.opts.transports = ['polling', 'websocket'];
273
- this.socket.connect();
274
- }
275
- }
276
- }, 5000);
277
- }
278
- catch (error) {
279
- console.error('Error in initWebSocket:', error);
280
- this.connectionInProgress = false;
281
- }
282
- }
283
- async request(endpoint, method, body, requiresAuth = true) {
284
- const headers = {
285
- 'Content-Type': 'application/json',
286
- };
287
- if (requiresAuth && this.authToken)
288
- headers['Authorization'] = `Bearer ${this.authToken}`;
289
- if (this.socket.id)
290
- headers['X-Socket-ID'] = this.socket.id;
291
- const options = {
292
- method,
293
- headers,
294
- body: body ? JSON.stringify(body) : undefined
295
- };
296
- const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
297
- const normalizedBaseUrl = this.baseUrl.endsWith('/') ? this.baseUrl.slice(0, -1) : this.baseUrl;
298
- const url = `${normalizedBaseUrl}${normalizedEndpoint}`;
299
- const response = await fetch(url, options);
300
- if (!response.ok) {
301
- if (response.status === 401 || response.status === 403) {
302
- this.authToken = null;
303
- }
304
- throw new Error(`API error: ${response.status} ${response.statusText}`);
305
- }
306
- return await response.json();
307
- }
308
- }