bedloop 0.1.0-alpha.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 johan12361
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,198 @@
1
+ # Bedloop API Client
2
+
3
+ A TypeScript client for the Bedloop API with real-time messaging and booking management capabilities.
4
+
5
+ ## Features
6
+
7
+ - Authentication with automatic token management and retry logic
8
+ - Real-time message polling from conversations
9
+ - Booking management with date range queries
10
+ - Auto-retry mechanism for failed requests (up to 3 attempts)
11
+ - Memory-efficient cache with automatic cleanup
12
+ - Automatic token refresh every 12 hours
13
+ - Type-safe event system
14
+ - Full TypeScript support
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install bedloop
20
+ # or
21
+ pnpm add bedloop
22
+ # or
23
+ yarn add bedloop
24
+ ```
25
+
26
+ ## Quick Start
27
+
28
+ ```typescript
29
+ import { Client, EventType } from 'bedloop'
30
+
31
+ const client = new Client(
32
+ {
33
+ user: 'your-username',
34
+ password: 'your-password',
35
+ url: 'https://your-bedloop-instance.com'
36
+ },
37
+ {
38
+ interval: 5000,
39
+ beforeDays: 7,
40
+ afterDays: 30
41
+ }
42
+ )
43
+
44
+ client.connect((events) => {
45
+ events.forEach((event) => {
46
+ if (event.event === EventType.NEW_MESSAGE) {
47
+ console.log('New message:', event.newMessage)
48
+ }
49
+ })
50
+ })
51
+ ```
52
+
53
+ ## API Reference
54
+
55
+ ### Client
56
+
57
+ #### Constructor
58
+
59
+ ```typescript
60
+ new Client(options: ClientOptions, pollingOptions?: PollingOptions)
61
+ ```
62
+
63
+ **ClientOptions:**
64
+
65
+ - `user` (string): Username for authentication
66
+ - `password` (string): Password for authentication
67
+ - `url` (string): Base URL of your Bedloop instance
68
+ - `debug` (boolean, optional): Enable debug logging (default: false)
69
+
70
+ **PollingOptions:**
71
+
72
+ - `interval` (number): Polling interval in milliseconds (default: 5000)
73
+ - `beforeDays` (number): Days to look back for bookings (default: 7)
74
+ - `afterDays` (number): Days to look ahead for bookings (default: 30)
75
+
76
+ #### Methods
77
+
78
+ **connect(callback: (events: BedloopEvent[]) => void): Promise<void>**
79
+
80
+ Connects to the Bedloop API and starts polling for events. Automatically refreshes the authentication token every 12 hours.
81
+
82
+ **disconnect(): void**
83
+
84
+ Disconnects from the API and cleans up resources including token refresh interval.
85
+
86
+ ### Event Types
87
+
88
+ #### BedloopEvent
89
+
90
+ ```typescript
91
+ interface BedloopEvent {
92
+ event: EventType
93
+ timestamp: Date
94
+ newMessage?: {
95
+ bookingId: number
96
+ conversationId: number
97
+ messageId: number
98
+ message: ConversationMessage
99
+ }
100
+ }
101
+ ```
102
+
103
+ #### EventType Enum
104
+
105
+ ```typescript
106
+ enum EventType {
107
+ NEW_MESSAGE = 'new_message'
108
+ }
109
+ ```
110
+
111
+ ## Examples
112
+
113
+ ### Basic Usage
114
+
115
+ ```typescript
116
+ const client = new Client({
117
+ user: 'username',
118
+ password: 'password',
119
+ url: 'https://api.bedloop.com'
120
+ })
121
+
122
+ await client.connect((events) => {
123
+ events.forEach((event) => {
124
+ console.log('Event received:', event)
125
+ })
126
+ })
127
+ ```
128
+
129
+ ### With Debug Logging
130
+
131
+ ```typescript
132
+ const client = new Client({
133
+ user: 'username',
134
+ password: 'password',
135
+ url: 'https://api.bedloop.com',
136
+ debug: true
137
+ })
138
+ ```
139
+
140
+ ### Custom Polling Configuration
141
+
142
+ ```typescript
143
+ const client = new Client(
144
+ {
145
+ user: 'username',
146
+ password: 'password',
147
+ url: 'https://api.bedloop.com'
148
+ },
149
+ {
150
+ interval: 10000,
151
+ beforeDays: 14,
152
+ afterDays: 60
153
+ }
154
+ )
155
+ ```
156
+
157
+ ### Graceful Shutdown
158
+
159
+ ```typescript
160
+ const client = new Client({...})
161
+ await client.connect((events) => {...})
162
+
163
+ // Clean up resources when done
164
+ client.disconnect()
165
+ ```
166
+
167
+ ## Error Handling
168
+
169
+ The client automatically handles:
170
+
171
+ - Network failures with retry logic (3 attempts, 1 second intervals)
172
+ - Token expiration with automatic refresh every 12 hours
173
+ - Rate limiting with configurable polling intervals
174
+
175
+ ```typescript
176
+ client.connect((events) => {
177
+ try {
178
+ events.forEach((event) => {
179
+ // Process event
180
+ })
181
+ } catch (error) {
182
+ console.error('Error processing events:', error)
183
+ }
184
+ })
185
+ ```
186
+
187
+ ## License
188
+
189
+ MIT
190
+
191
+ ## Author
192
+
193
+ johan12361
194
+
195
+ ---
196
+
197
+ **Note:** This is an alpha release. The API may change in future versions.
198
+ # bedloop
package/dist/index.cjs ADDED
@@ -0,0 +1,351 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ Client: () => Client,
34
+ EventType: () => EventType
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+
38
+ // src/client/auth/getAuthorization.ts
39
+ var import_axios = __toESM(require("axios"), 1);
40
+ var MAX_RETRIES = 3;
41
+ var RETRY_DELAY = 1e3;
42
+ async function getAuthorization(options) {
43
+ const url = `${options.url}/api/v1/login`;
44
+ const headers = {
45
+ Accept: "application/json",
46
+ Authorization: createUserPass(options.user, options.password)
47
+ };
48
+ const debug = options.debug ?? false;
49
+ let lastError = null;
50
+ for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
51
+ try {
52
+ const response = await import_axios.default.get(url, { headers });
53
+ if (response.data && response.data.token && response.data.expires_at) {
54
+ if (attempt > 1 && debug) {
55
+ console.log(`Connection successful on attempt ${attempt}`);
56
+ }
57
+ return {
58
+ token: response.data.token,
59
+ expiresAt: new Date(response.data.expires_at)
60
+ };
61
+ } else {
62
+ throw new Error("Invalid authorization data");
63
+ }
64
+ } catch (error) {
65
+ lastError = error instanceof Error ? error : new Error(String(error));
66
+ if (attempt < MAX_RETRIES) {
67
+ if (debug) {
68
+ console.log(`Attempt ${attempt} failed, retrying in ${RETRY_DELAY / 1e3}s...`);
69
+ }
70
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
71
+ } else {
72
+ if (debug) {
73
+ console.warn(`All ${MAX_RETRIES} attempts failed`);
74
+ }
75
+ }
76
+ }
77
+ }
78
+ throw lastError || new Error("Authorization failed after retries");
79
+ }
80
+ function createUserPass(user, password) {
81
+ const token = Buffer.from(`${user}:${password}`, "utf8").toString("base64");
82
+ return `Basic ${token}`;
83
+ }
84
+
85
+ // src/client/request/getBookingByDate.ts
86
+ var import_axios2 = __toESM(require("axios"), 1);
87
+ async function getBookingByDate(baseUrl, token, startDate, endDate) {
88
+ const url = `${baseUrl}/api/v1/bookings?start_date=${startDate}&end_date=${endDate}`;
89
+ const headers = {
90
+ Accept: "application/json",
91
+ Authorization: `Bearer ${token}`
92
+ };
93
+ const response = await import_axios2.default.get(url, { headers });
94
+ if (!response.data) {
95
+ throw new Error("No data received from getBookingByDate");
96
+ }
97
+ if (!Array.isArray(response.data.data)) {
98
+ throw new Error("Invalid data format received from getBookingByDate");
99
+ }
100
+ return response.data.data;
101
+ }
102
+
103
+ // src/client/request/getMessages.ts
104
+ var import_axios3 = __toESM(require("axios"), 1);
105
+ async function getMessages(baseUrl, token, bookingId) {
106
+ const url = `${baseUrl}/api/v1/threads/${bookingId}`;
107
+ const headers = {
108
+ Accept: "application/json",
109
+ Authorization: `Bearer ${token}`
110
+ };
111
+ const response = await import_axios3.default.get(url, { headers });
112
+ if (!response.data) {
113
+ throw new Error("No data received from getBookingByDate");
114
+ }
115
+ if (!Array.isArray(response.data.data)) {
116
+ throw new Error("Invalid data format received from getBookingByDate");
117
+ }
118
+ return response.data.data;
119
+ }
120
+
121
+ // src/utils/cache.ts
122
+ var LimitedCache = class {
123
+ constructor(maxSize = 1e3, maxAgeMinutes = 60) {
124
+ this.cache = /* @__PURE__ */ new Map();
125
+ this.maxSize = maxSize;
126
+ this.maxAge = maxAgeMinutes * 60 * 1e3;
127
+ }
128
+ // Agrega un elemento al cache
129
+ set(key, value) {
130
+ if (this.cache.size >= this.maxSize) {
131
+ const firstKey = this.cache.keys().next().value;
132
+ if (firstKey !== void 0) {
133
+ this.cache.delete(firstKey);
134
+ }
135
+ }
136
+ this.cache.set(key, { value, timestamp: Date.now() });
137
+ }
138
+ // Verifica si un elemento existe en el cache
139
+ has(key) {
140
+ const entry = this.cache.get(key);
141
+ if (!entry) return false;
142
+ if (Date.now() - entry.timestamp > this.maxAge) {
143
+ this.cache.delete(key);
144
+ return false;
145
+ }
146
+ return true;
147
+ }
148
+ // Limpia elementos expirados
149
+ cleanup() {
150
+ const now = Date.now();
151
+ for (const [key, entry] of this.cache.entries()) {
152
+ if (now - entry.timestamp > this.maxAge) {
153
+ this.cache.delete(key);
154
+ }
155
+ }
156
+ }
157
+ // Obtiene el tamaño actual del cache
158
+ get size() {
159
+ return this.cache.size;
160
+ }
161
+ };
162
+
163
+ // src/utils/date.ts
164
+ function addDays(date, days) {
165
+ const result = new Date(date.getTime() + days * 24 * 60 * 60 * 1e3);
166
+ return result.toISOString().split("T")[0];
167
+ }
168
+ function getMinutesAgo(minutes) {
169
+ return new Date(Date.now() - minutes * 60 * 1e3);
170
+ }
171
+
172
+ // src/utils/tokenValidation.ts
173
+ function isTokenExpired(authorization) {
174
+ return /* @__PURE__ */ new Date() >= authorization.expiresAt;
175
+ }
176
+
177
+ // src/enums/messageDirection.ts
178
+ var MESSAGE_DIRECTION = {
179
+ OUTGOING: 0,
180
+ INCOMING: 1
181
+ };
182
+
183
+ // src/types/messages.ts
184
+ var DEFAULT_RECENT_MINUTES = 5;
185
+ var DEFAULT_CACHE_SIZE = 1e3;
186
+ var DEFAULT_CACHE_AGE_MINUTES = 60;
187
+
188
+ // src/client/pollingMessages/filterMessages.ts
189
+ function filterNewMessages(conversations, bookingId, cache, recentMinutes = DEFAULT_RECENT_MINUTES) {
190
+ const newMessages = [];
191
+ const cutoffTime = getMinutesAgo(recentMinutes);
192
+ for (const conversation of conversations) {
193
+ if (!conversation.messages || conversation.messages.length === 0) {
194
+ continue;
195
+ }
196
+ for (const message of conversation.messages) {
197
+ if (message.in_out !== MESSAGE_DIRECTION.INCOMING) {
198
+ continue;
199
+ }
200
+ if (cache.has(message.id)) {
201
+ continue;
202
+ }
203
+ const receivedAt = new Date(message.created_at);
204
+ if (receivedAt < cutoffTime) {
205
+ continue;
206
+ }
207
+ cache.set(message.id, message);
208
+ newMessages.push({
209
+ bookingId,
210
+ conversationId: conversation.id,
211
+ message
212
+ });
213
+ }
214
+ }
215
+ return newMessages;
216
+ }
217
+
218
+ // src/types/events.ts
219
+ var EventType = /* @__PURE__ */ ((EventType2) => {
220
+ EventType2["NEW_MESSAGE"] = "new_message";
221
+ return EventType2;
222
+ })(EventType || {});
223
+
224
+ // src/client/pollingMessages/pollingMessages.ts
225
+ var messagesCache = new LimitedCache(DEFAULT_CACHE_SIZE, DEFAULT_CACHE_AGE_MINUTES);
226
+ async function pollingMessages(clientConfig, getAuthorization2, pollingOptions, callback) {
227
+ const baseUrl = clientConfig.url;
228
+ const debug = clientConfig.debug ?? false;
229
+ const cleanupInterval = setInterval(
230
+ () => {
231
+ messagesCache.cleanup();
232
+ },
233
+ 10 * 60 * 1e3
234
+ );
235
+ const pollingInterval = setInterval(() => {
236
+ void (async () => {
237
+ try {
238
+ const authorization = getAuthorization2();
239
+ if (isTokenExpired(authorization)) {
240
+ if (debug) {
241
+ console.warn("Authorization token has expired");
242
+ }
243
+ clearInterval(pollingInterval);
244
+ clearInterval(cleanupInterval);
245
+ return;
246
+ }
247
+ const token = authorization.token;
248
+ const now = /* @__PURE__ */ new Date();
249
+ const startDate = addDays(now, -pollingOptions.beforeDays);
250
+ const endDate = addDays(now, pollingOptions.afterDays);
251
+ if (debug) {
252
+ console.log(`Polling bookings from ${startDate} to ${endDate}`);
253
+ }
254
+ const bookings = await getBookingByDate(baseUrl, token, startDate, endDate);
255
+ const messagesPromises = bookings.map(async (booking) => {
256
+ try {
257
+ const conversations = await getMessages(baseUrl, token, String(booking.booking_number));
258
+ if (conversations.length === 0) return [];
259
+ return filterNewMessages(conversations, booking.booking_number, messagesCache);
260
+ } catch (error) {
261
+ if (debug) {
262
+ console.error(`Error getting messages for booking ${booking.booking_number}:`, error);
263
+ }
264
+ return [];
265
+ }
266
+ });
267
+ const results = await Promise.all(messagesPromises);
268
+ const allNewMessages = results.flat();
269
+ if (allNewMessages.length > 0) {
270
+ if (debug) {
271
+ console.log(`Found ${allNewMessages.length} new message(s)`);
272
+ }
273
+ const events = allNewMessages.map((msg) => ({
274
+ event: "new_message" /* NEW_MESSAGE */,
275
+ timestamp: /* @__PURE__ */ new Date(),
276
+ newMessage: {
277
+ bookingId: msg.bookingId,
278
+ conversationId: msg.conversationId,
279
+ messageId: msg.message.id,
280
+ message: msg.message
281
+ }
282
+ }));
283
+ callback(events);
284
+ }
285
+ } catch (error) {
286
+ if (debug) {
287
+ console.error("Error polling messages:", error);
288
+ }
289
+ }
290
+ })();
291
+ }, pollingOptions.interval);
292
+ }
293
+
294
+ // src/client/client.ts
295
+ var defaultPollingOptions = {
296
+ interval: 5e3,
297
+ // 5 segundos
298
+ beforeDays: 7,
299
+ afterDays: 30
300
+ };
301
+ var Client = class {
302
+ constructor(options, pollingOptions = {}) {
303
+ this.options = options;
304
+ this.pollingOptions = {
305
+ ...defaultPollingOptions,
306
+ ...pollingOptions
307
+ };
308
+ if (this.options.debug) {
309
+ console.log("Client initialized");
310
+ }
311
+ }
312
+ async refreshToken() {
313
+ try {
314
+ this.authorization = await getAuthorization(this.options);
315
+ if (this.options.debug) {
316
+ console.log("Token refreshed:", this.authorization);
317
+ }
318
+ } catch (error) {
319
+ if (this.options.debug) {
320
+ console.error("Error refreshing token:", error);
321
+ }
322
+ }
323
+ }
324
+ async connect(callback) {
325
+ this.authorization = await getAuthorization(this.options);
326
+ if (this.options.debug) {
327
+ console.log("Connected:", this.authorization);
328
+ }
329
+ this.tokenRefreshInterval = setInterval(
330
+ () => {
331
+ void this.refreshToken();
332
+ },
333
+ 12 * 60 * 60 * 1e3
334
+ );
335
+ pollingMessages(this.options, () => this.authorization, this.pollingOptions, callback);
336
+ }
337
+ disconnect() {
338
+ if (this.tokenRefreshInterval) {
339
+ clearInterval(this.tokenRefreshInterval);
340
+ this.tokenRefreshInterval = void 0;
341
+ }
342
+ if (this.options.debug) {
343
+ console.log("Client disconnected");
344
+ }
345
+ }
346
+ };
347
+ // Annotate the CommonJS export names for ESM import in node:
348
+ 0 && (module.exports = {
349
+ Client,
350
+ EventType
351
+ });
@@ -0,0 +1,48 @@
1
+ interface ConversationMessage {
2
+ id: number;
3
+ thread_id: number | null;
4
+ in_out: number;
5
+ message: string;
6
+ external_id: string | null;
7
+ type: string | null;
8
+ created_at: string;
9
+ }
10
+
11
+ declare enum EventType {
12
+ NEW_MESSAGE = "new_message"
13
+ }
14
+ interface BedloopEvent {
15
+ event: EventType;
16
+ timestamp: Date;
17
+ newMessage?: {
18
+ bookingId?: number;
19
+ conversationId?: number;
20
+ messageId?: number;
21
+ message?: ConversationMessage;
22
+ };
23
+ }
24
+
25
+ interface ClientOptions {
26
+ user: string;
27
+ password: string;
28
+ url: string;
29
+ debug?: boolean;
30
+ }
31
+ interface PollingOptions {
32
+ interval: number;
33
+ beforeDays: number;
34
+ afterDays: number;
35
+ }
36
+
37
+ declare class Client {
38
+ readonly options: ClientOptions;
39
+ readonly pollingOptions: PollingOptions;
40
+ private authorization?;
41
+ private tokenRefreshInterval?;
42
+ constructor(options: ClientOptions, pollingOptions?: Partial<PollingOptions>);
43
+ private refreshToken;
44
+ connect(callback: (events: BedloopEvent[]) => void): Promise<void>;
45
+ disconnect(): void;
46
+ }
47
+
48
+ export { type BedloopEvent, Client, type ClientOptions, EventType, type PollingOptions };
@@ -0,0 +1,48 @@
1
+ interface ConversationMessage {
2
+ id: number;
3
+ thread_id: number | null;
4
+ in_out: number;
5
+ message: string;
6
+ external_id: string | null;
7
+ type: string | null;
8
+ created_at: string;
9
+ }
10
+
11
+ declare enum EventType {
12
+ NEW_MESSAGE = "new_message"
13
+ }
14
+ interface BedloopEvent {
15
+ event: EventType;
16
+ timestamp: Date;
17
+ newMessage?: {
18
+ bookingId?: number;
19
+ conversationId?: number;
20
+ messageId?: number;
21
+ message?: ConversationMessage;
22
+ };
23
+ }
24
+
25
+ interface ClientOptions {
26
+ user: string;
27
+ password: string;
28
+ url: string;
29
+ debug?: boolean;
30
+ }
31
+ interface PollingOptions {
32
+ interval: number;
33
+ beforeDays: number;
34
+ afterDays: number;
35
+ }
36
+
37
+ declare class Client {
38
+ readonly options: ClientOptions;
39
+ readonly pollingOptions: PollingOptions;
40
+ private authorization?;
41
+ private tokenRefreshInterval?;
42
+ constructor(options: ClientOptions, pollingOptions?: Partial<PollingOptions>);
43
+ private refreshToken;
44
+ connect(callback: (events: BedloopEvent[]) => void): Promise<void>;
45
+ disconnect(): void;
46
+ }
47
+
48
+ export { type BedloopEvent, Client, type ClientOptions, EventType, type PollingOptions };
package/dist/index.js ADDED
@@ -0,0 +1,313 @@
1
+ // src/client/auth/getAuthorization.ts
2
+ import axios from "axios";
3
+ var MAX_RETRIES = 3;
4
+ var RETRY_DELAY = 1e3;
5
+ async function getAuthorization(options) {
6
+ const url = `${options.url}/api/v1/login`;
7
+ const headers = {
8
+ Accept: "application/json",
9
+ Authorization: createUserPass(options.user, options.password)
10
+ };
11
+ const debug = options.debug ?? false;
12
+ let lastError = null;
13
+ for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
14
+ try {
15
+ const response = await axios.get(url, { headers });
16
+ if (response.data && response.data.token && response.data.expires_at) {
17
+ if (attempt > 1 && debug) {
18
+ console.log(`Connection successful on attempt ${attempt}`);
19
+ }
20
+ return {
21
+ token: response.data.token,
22
+ expiresAt: new Date(response.data.expires_at)
23
+ };
24
+ } else {
25
+ throw new Error("Invalid authorization data");
26
+ }
27
+ } catch (error) {
28
+ lastError = error instanceof Error ? error : new Error(String(error));
29
+ if (attempt < MAX_RETRIES) {
30
+ if (debug) {
31
+ console.log(`Attempt ${attempt} failed, retrying in ${RETRY_DELAY / 1e3}s...`);
32
+ }
33
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
34
+ } else {
35
+ if (debug) {
36
+ console.warn(`All ${MAX_RETRIES} attempts failed`);
37
+ }
38
+ }
39
+ }
40
+ }
41
+ throw lastError || new Error("Authorization failed after retries");
42
+ }
43
+ function createUserPass(user, password) {
44
+ const token = Buffer.from(`${user}:${password}`, "utf8").toString("base64");
45
+ return `Basic ${token}`;
46
+ }
47
+
48
+ // src/client/request/getBookingByDate.ts
49
+ import axios2 from "axios";
50
+ async function getBookingByDate(baseUrl, token, startDate, endDate) {
51
+ const url = `${baseUrl}/api/v1/bookings?start_date=${startDate}&end_date=${endDate}`;
52
+ const headers = {
53
+ Accept: "application/json",
54
+ Authorization: `Bearer ${token}`
55
+ };
56
+ const response = await axios2.get(url, { headers });
57
+ if (!response.data) {
58
+ throw new Error("No data received from getBookingByDate");
59
+ }
60
+ if (!Array.isArray(response.data.data)) {
61
+ throw new Error("Invalid data format received from getBookingByDate");
62
+ }
63
+ return response.data.data;
64
+ }
65
+
66
+ // src/client/request/getMessages.ts
67
+ import axios3 from "axios";
68
+ async function getMessages(baseUrl, token, bookingId) {
69
+ const url = `${baseUrl}/api/v1/threads/${bookingId}`;
70
+ const headers = {
71
+ Accept: "application/json",
72
+ Authorization: `Bearer ${token}`
73
+ };
74
+ const response = await axios3.get(url, { headers });
75
+ if (!response.data) {
76
+ throw new Error("No data received from getBookingByDate");
77
+ }
78
+ if (!Array.isArray(response.data.data)) {
79
+ throw new Error("Invalid data format received from getBookingByDate");
80
+ }
81
+ return response.data.data;
82
+ }
83
+
84
+ // src/utils/cache.ts
85
+ var LimitedCache = class {
86
+ constructor(maxSize = 1e3, maxAgeMinutes = 60) {
87
+ this.cache = /* @__PURE__ */ new Map();
88
+ this.maxSize = maxSize;
89
+ this.maxAge = maxAgeMinutes * 60 * 1e3;
90
+ }
91
+ // Agrega un elemento al cache
92
+ set(key, value) {
93
+ if (this.cache.size >= this.maxSize) {
94
+ const firstKey = this.cache.keys().next().value;
95
+ if (firstKey !== void 0) {
96
+ this.cache.delete(firstKey);
97
+ }
98
+ }
99
+ this.cache.set(key, { value, timestamp: Date.now() });
100
+ }
101
+ // Verifica si un elemento existe en el cache
102
+ has(key) {
103
+ const entry = this.cache.get(key);
104
+ if (!entry) return false;
105
+ if (Date.now() - entry.timestamp > this.maxAge) {
106
+ this.cache.delete(key);
107
+ return false;
108
+ }
109
+ return true;
110
+ }
111
+ // Limpia elementos expirados
112
+ cleanup() {
113
+ const now = Date.now();
114
+ for (const [key, entry] of this.cache.entries()) {
115
+ if (now - entry.timestamp > this.maxAge) {
116
+ this.cache.delete(key);
117
+ }
118
+ }
119
+ }
120
+ // Obtiene el tamaño actual del cache
121
+ get size() {
122
+ return this.cache.size;
123
+ }
124
+ };
125
+
126
+ // src/utils/date.ts
127
+ function addDays(date, days) {
128
+ const result = new Date(date.getTime() + days * 24 * 60 * 60 * 1e3);
129
+ return result.toISOString().split("T")[0];
130
+ }
131
+ function getMinutesAgo(minutes) {
132
+ return new Date(Date.now() - minutes * 60 * 1e3);
133
+ }
134
+
135
+ // src/utils/tokenValidation.ts
136
+ function isTokenExpired(authorization) {
137
+ return /* @__PURE__ */ new Date() >= authorization.expiresAt;
138
+ }
139
+
140
+ // src/enums/messageDirection.ts
141
+ var MESSAGE_DIRECTION = {
142
+ OUTGOING: 0,
143
+ INCOMING: 1
144
+ };
145
+
146
+ // src/types/messages.ts
147
+ var DEFAULT_RECENT_MINUTES = 5;
148
+ var DEFAULT_CACHE_SIZE = 1e3;
149
+ var DEFAULT_CACHE_AGE_MINUTES = 60;
150
+
151
+ // src/client/pollingMessages/filterMessages.ts
152
+ function filterNewMessages(conversations, bookingId, cache, recentMinutes = DEFAULT_RECENT_MINUTES) {
153
+ const newMessages = [];
154
+ const cutoffTime = getMinutesAgo(recentMinutes);
155
+ for (const conversation of conversations) {
156
+ if (!conversation.messages || conversation.messages.length === 0) {
157
+ continue;
158
+ }
159
+ for (const message of conversation.messages) {
160
+ if (message.in_out !== MESSAGE_DIRECTION.INCOMING) {
161
+ continue;
162
+ }
163
+ if (cache.has(message.id)) {
164
+ continue;
165
+ }
166
+ const receivedAt = new Date(message.created_at);
167
+ if (receivedAt < cutoffTime) {
168
+ continue;
169
+ }
170
+ cache.set(message.id, message);
171
+ newMessages.push({
172
+ bookingId,
173
+ conversationId: conversation.id,
174
+ message
175
+ });
176
+ }
177
+ }
178
+ return newMessages;
179
+ }
180
+
181
+ // src/types/events.ts
182
+ var EventType = /* @__PURE__ */ ((EventType2) => {
183
+ EventType2["NEW_MESSAGE"] = "new_message";
184
+ return EventType2;
185
+ })(EventType || {});
186
+
187
+ // src/client/pollingMessages/pollingMessages.ts
188
+ var messagesCache = new LimitedCache(DEFAULT_CACHE_SIZE, DEFAULT_CACHE_AGE_MINUTES);
189
+ async function pollingMessages(clientConfig, getAuthorization2, pollingOptions, callback) {
190
+ const baseUrl = clientConfig.url;
191
+ const debug = clientConfig.debug ?? false;
192
+ const cleanupInterval = setInterval(
193
+ () => {
194
+ messagesCache.cleanup();
195
+ },
196
+ 10 * 60 * 1e3
197
+ );
198
+ const pollingInterval = setInterval(() => {
199
+ void (async () => {
200
+ try {
201
+ const authorization = getAuthorization2();
202
+ if (isTokenExpired(authorization)) {
203
+ if (debug) {
204
+ console.warn("Authorization token has expired");
205
+ }
206
+ clearInterval(pollingInterval);
207
+ clearInterval(cleanupInterval);
208
+ return;
209
+ }
210
+ const token = authorization.token;
211
+ const now = /* @__PURE__ */ new Date();
212
+ const startDate = addDays(now, -pollingOptions.beforeDays);
213
+ const endDate = addDays(now, pollingOptions.afterDays);
214
+ if (debug) {
215
+ console.log(`Polling bookings from ${startDate} to ${endDate}`);
216
+ }
217
+ const bookings = await getBookingByDate(baseUrl, token, startDate, endDate);
218
+ const messagesPromises = bookings.map(async (booking) => {
219
+ try {
220
+ const conversations = await getMessages(baseUrl, token, String(booking.booking_number));
221
+ if (conversations.length === 0) return [];
222
+ return filterNewMessages(conversations, booking.booking_number, messagesCache);
223
+ } catch (error) {
224
+ if (debug) {
225
+ console.error(`Error getting messages for booking ${booking.booking_number}:`, error);
226
+ }
227
+ return [];
228
+ }
229
+ });
230
+ const results = await Promise.all(messagesPromises);
231
+ const allNewMessages = results.flat();
232
+ if (allNewMessages.length > 0) {
233
+ if (debug) {
234
+ console.log(`Found ${allNewMessages.length} new message(s)`);
235
+ }
236
+ const events = allNewMessages.map((msg) => ({
237
+ event: "new_message" /* NEW_MESSAGE */,
238
+ timestamp: /* @__PURE__ */ new Date(),
239
+ newMessage: {
240
+ bookingId: msg.bookingId,
241
+ conversationId: msg.conversationId,
242
+ messageId: msg.message.id,
243
+ message: msg.message
244
+ }
245
+ }));
246
+ callback(events);
247
+ }
248
+ } catch (error) {
249
+ if (debug) {
250
+ console.error("Error polling messages:", error);
251
+ }
252
+ }
253
+ })();
254
+ }, pollingOptions.interval);
255
+ }
256
+
257
+ // src/client/client.ts
258
+ var defaultPollingOptions = {
259
+ interval: 5e3,
260
+ // 5 segundos
261
+ beforeDays: 7,
262
+ afterDays: 30
263
+ };
264
+ var Client = class {
265
+ constructor(options, pollingOptions = {}) {
266
+ this.options = options;
267
+ this.pollingOptions = {
268
+ ...defaultPollingOptions,
269
+ ...pollingOptions
270
+ };
271
+ if (this.options.debug) {
272
+ console.log("Client initialized");
273
+ }
274
+ }
275
+ async refreshToken() {
276
+ try {
277
+ this.authorization = await getAuthorization(this.options);
278
+ if (this.options.debug) {
279
+ console.log("Token refreshed:", this.authorization);
280
+ }
281
+ } catch (error) {
282
+ if (this.options.debug) {
283
+ console.error("Error refreshing token:", error);
284
+ }
285
+ }
286
+ }
287
+ async connect(callback) {
288
+ this.authorization = await getAuthorization(this.options);
289
+ if (this.options.debug) {
290
+ console.log("Connected:", this.authorization);
291
+ }
292
+ this.tokenRefreshInterval = setInterval(
293
+ () => {
294
+ void this.refreshToken();
295
+ },
296
+ 12 * 60 * 60 * 1e3
297
+ );
298
+ pollingMessages(this.options, () => this.authorization, this.pollingOptions, callback);
299
+ }
300
+ disconnect() {
301
+ if (this.tokenRefreshInterval) {
302
+ clearInterval(this.tokenRefreshInterval);
303
+ this.tokenRefreshInterval = void 0;
304
+ }
305
+ if (this.options.debug) {
306
+ console.log("Client disconnected");
307
+ }
308
+ }
309
+ };
310
+ export {
311
+ Client,
312
+ EventType
313
+ };
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "bedloop",
3
+ "version": "0.1.0-alpha.0",
4
+ "type": "module",
5
+ "description": "TypeScript client for Bedloop API with real-time messaging and booking management",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "require": {
12
+ "types": "./dist/index.d.cts",
13
+ "default": "./dist/index.cjs"
14
+ },
15
+ "import": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ }
19
+ }
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "scripts": {
27
+ "build": "tsup",
28
+ "dev": "tsc --watch",
29
+ "playground": "tsx playground/playground.ts",
30
+ "lint": "eslint src/**/*.ts",
31
+ "lint:fix": "eslint src/**/*.ts --fix",
32
+ "format": "prettier --write \"src/**/*.ts\"",
33
+ "typecheck": "tsc --noEmit",
34
+ "test": "vitest",
35
+ "test:ui": "vitest --ui",
36
+ "test:run": "vitest run",
37
+ "test:coverage": "vitest run --coverage",
38
+ "prepublishOnly": "pnpm build"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "24.10.1",
42
+ "@typescript-eslint/eslint-plugin": "8.48.0",
43
+ "@typescript-eslint/parser": "8.48.0",
44
+ "eslint": "9.39.1",
45
+ "eslint-config-prettier": "10.1.8",
46
+ "eslint-plugin-prettier": "5.5.4",
47
+ "prettier": "3.7.3",
48
+ "tsup": "8.5.1",
49
+ "tsx": "4.20.6",
50
+ "typescript": "5.9.3"
51
+ },
52
+ "keywords": [
53
+ "bedloop",
54
+ "api",
55
+ "client",
56
+ "typescript",
57
+ "messaging",
58
+ "booking",
59
+ "real-time",
60
+ "polling"
61
+ ],
62
+ "repository": {
63
+ "type": "git",
64
+ "url": "https://github.com/johan12361/bedloop.git"
65
+ },
66
+ "bugs": {
67
+ "url": "https://github.com/johan12361/bedloop/issues"
68
+ },
69
+ "homepage": "https://github.com/johan12361/bedloop#readme",
70
+ "author": "johan12361",
71
+ "license": "MIT",
72
+ "packageManager": "pnpm@10.18.3",
73
+ "dependencies": {
74
+ "axios": "1.13.2"
75
+ }
76
+ }