sendblue 1.0.1 → 1.1.2

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/.env ADDED
@@ -0,0 +1,5 @@
1
+ SENDBLUE_TEST_API_KEY=b8d493efb9682ce9000544da8e0d5de0
2
+ SENDBLUE_TEST_API_SECRET=9573ec4d4e8ae1f4a945d14f4ec7666c
3
+ TEST_NUMBER_1="+19173599290"
4
+ TEST_NUMBER_2="+18582144695"
5
+
package/.prettierrc ADDED
@@ -0,0 +1 @@
1
+ {}
package/README.md CHANGED
@@ -1,15 +1,64 @@
1
- # sendblue-node
2
- A node wrapper for the sendblue api
1
+ # Sendblue API
2
+
3
+ ## Overview
4
+
5
+ This package is a node.js wrapper for the Sendblue API. It provides a simple interface for sending and receiving messages.
6
+
7
+ ## Prerequisites
8
+
9
+ You will need to get API keys by signing up for a Sendblue account. You can do so [here](https://sendblue.co/).
10
+
11
+ ## Installation
12
+
13
+ `npm i sendblue-node`
14
+
15
+ ## Usage
16
+
17
+ ### Initializing
18
+
19
+ ```js
20
+ import Sendblue from 'sendblue-node'
21
+
22
+ // Load your key from an environment variable or secret management service
23
+ // (do not include your key directly in your code)
24
+ const SENDBLUE_API_KEY = process.env.SENDBLUE_API_KEY
25
+ const SENDBLUE_API_SECRET = process.env.SENDBLUE_API_SECRET
26
+
27
+ const sendblue = new Sendblue(SENDBLUE_API_KEY, SENDBLUE_API_SECRET)
28
+ ```
29
+
30
+ ### Send Message API Call
3
31
 
4
- ## Usage:
5
32
  ```js
6
- const Sendblue = require('sendblue');
33
+ ;(async () => {
34
+ const response = await sendblue.sendMessage({
35
+ number: '+19998887777',
36
+ content: 'Hello world!',
37
+ send_style: 'invisible',
38
+ media_url: 'https://source.unsplash.com/random.png',
39
+ status_callback: 'https://example.com/message-status/1234abcd'
40
+ })
41
+
42
+ console.log(response)
43
+ })()
44
+ ```
45
+
46
+ ### Send Group Message API call
47
+
48
+ ```js
49
+ ;(async () => {
50
+ const response = await sendblue.sendGroupMessage({
51
+ numbers: ['+19998887777', '+19998887778'],
52
+ content: 'Hello world!',
53
+ send_style: 'invisible',
54
+ media_url: 'https://source.unsplash.com/random.png',
55
+ status_callback: 'https://example.com/message-status/1234abcd'
56
+ })
57
+
58
+ console.log(response)
59
+ })()
60
+ ```
7
61
 
8
- const sendblue = new Sendblue("API_KEY", "API_SECRET");
62
+ ## Hint
9
63
 
10
- (async () => {
11
- const responseData = sendblue.sendText("+19999999999", "Hello World");
12
-
13
- console.log(responseData);
14
- })();
15
- ```
64
+ You can get free api keys for testing & hobby purposes by emailing Sendblue
package/config.js CHANGED
@@ -1,5 +1,31 @@
1
+ const DEFAULT_ENGINE = 'davinci';
2
+ const ORIGIN = 'https://api.openai.com';
3
+ const API_VERSION = 'v1';
4
+ const OPEN_AI_URL = `${ORIGIN}/${API_VERSION}`;
5
+
1
6
  module.exports = {
2
- sendblue_base_url: "https://api.sendblue.co/",
3
- send_message_endpoint: "api/send-message",
4
- unregister_number_endpoint: "api/unregister"
5
- }
7
+ completionURL(engine) {
8
+ return `${OPEN_AI_URL}/engines/${engine}/completions`;
9
+ },
10
+ searchURL(engine) {
11
+ return `${OPEN_AI_URL}/engines/${engine}/search`;
12
+ },
13
+ enginesUrl() {
14
+ return `${OPEN_AI_URL}/engines`;
15
+ },
16
+ engineUrl(engine) {
17
+ return `${OPEN_AI_URL}/engines/${engine}`;
18
+ },
19
+ classificationsUrl() {
20
+ return `${OPEN_AI_URL}/classifications`;
21
+ },
22
+ filesUrl() {
23
+ return `${OPEN_AI_URL}/files`;
24
+ },
25
+ answersUrl() {
26
+ return `${OPEN_AI_URL}/answers`;
27
+ },
28
+ embeddingsUrl(engine) {
29
+ return `${OPEN_AI_URL}/engines/${engine}/embeddings`;
30
+ }
31
+ };
@@ -0,0 +1,43 @@
1
+ export declare type MessageTypes = 'group' | 'message';
2
+ export interface Message {
3
+ accountEmail?: string;
4
+ content?: string;
5
+ is_outbound?: boolean;
6
+ status?: string;
7
+ error_code?: string;
8
+ error_message?: string;
9
+ message_handle?: string;
10
+ date_sent?: Date;
11
+ date_updated?: Date;
12
+ from_number?: string;
13
+ number?: string;
14
+ to_number?: string;
15
+ was_downgraded?: boolean;
16
+ plan?: string;
17
+ media_url?: string;
18
+ message_type?: string;
19
+ group_id?: string;
20
+ participants?: string[];
21
+ }
22
+ export declare class MessageImpl {
23
+ accountEmail: string | undefined;
24
+ content: string | undefined;
25
+ is_outbound: boolean | undefined;
26
+ status: string | undefined;
27
+ error_code: string | undefined;
28
+ error_message: string | undefined;
29
+ message_handle: string | undefined;
30
+ date_sent: Date | undefined;
31
+ date_updated: Date | undefined;
32
+ from_number: string | undefined;
33
+ number: string | undefined;
34
+ to_number: string | undefined;
35
+ was_downgraded: boolean | undefined;
36
+ plan: string | undefined;
37
+ media_url: string | undefined;
38
+ message_type: string | undefined;
39
+ group_id: string | undefined;
40
+ participants: string[] | undefined;
41
+ constructor(message: Message);
42
+ static from(data: Message): MessageImpl;
43
+ }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MessageImpl = void 0;
4
+ var MessageImpl = /** @class */ (function () {
5
+ function MessageImpl(message) {
6
+ this.accountEmail = message.accountEmail;
7
+ this.content = message.content;
8
+ this.is_outbound = message.is_outbound;
9
+ this.status = message.status;
10
+ this.error_code = message.error_code;
11
+ this.error_message = message.error_message;
12
+ this.message_handle = message.message_handle;
13
+ this.date_sent = message.date_sent;
14
+ this.date_updated = message.date_updated;
15
+ this.from_number = message.from_number;
16
+ this.number = message.number;
17
+ this.to_number = message.to_number;
18
+ this.was_downgraded = message.was_downgraded;
19
+ this.plan = message.plan;
20
+ this.media_url = message.media_url;
21
+ this.message_type = message.message_type;
22
+ this.group_id = message.group_id;
23
+ this.participants = message.participants;
24
+ }
25
+ MessageImpl.from = function (data) {
26
+ return new MessageImpl(data);
27
+ };
28
+ return MessageImpl;
29
+ }());
30
+ exports.MessageImpl = MessageImpl;
@@ -0,0 +1,27 @@
1
+ /// <reference types="node" />
2
+ import { Agent, AgentOptions } from 'https';
3
+ import { AxiosInstance, AxiosRequestConfig } from 'axios';
4
+ export interface RequestClientOptions {
5
+ timeout?: number;
6
+ keepAlive?: boolean;
7
+ keepAliveMsecs?: number;
8
+ maxSockets?: number;
9
+ maxTotalSockets?: number;
10
+ maxFreeSockets?: number;
11
+ scheduling?: 'fifo' | 'lifo';
12
+ logLevel?: 'debug' | 'info' | 'warn' | 'error';
13
+ }
14
+ export interface RequestClientRequestOptions {
15
+ logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
16
+ }
17
+ export declare class RequestClient {
18
+ defaultTimeout: number;
19
+ agentOpts: AgentOptions;
20
+ agent: Agent;
21
+ axios: AxiosInstance;
22
+ logLevel: string;
23
+ constructor(opts: RequestClientOptions, apiKey: string, apiSecret: string);
24
+ request(opts: AxiosRequestConfig & RequestClientRequestOptions): Promise<any>;
25
+ filterLoggingHeaders(headers: any): string[];
26
+ logRequest(options: AxiosRequestConfig): void;
27
+ }
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.RequestClient = void 0;
40
+ var https_1 = require("https");
41
+ var axios_1 = require("axios");
42
+ var DEFAULT_CONTENT_TYPE = 'application/json';
43
+ var DEFAULT_TIMEOUT = 30000;
44
+ var RequestClient = /** @class */ (function () {
45
+ function RequestClient(opts, apiKey, apiSecret) {
46
+ this.defaultTimeout = DEFAULT_TIMEOUT;
47
+ this.defaultTimeout = opts.timeout || DEFAULT_TIMEOUT;
48
+ this.logLevel = opts.logLevel || 'info';
49
+ this.agentOpts = {
50
+ keepAlive: opts.keepAlive || false,
51
+ keepAliveMsecs: opts.keepAliveMsecs || 1000,
52
+ maxSockets: opts.maxSockets || 256,
53
+ maxTotalSockets: opts.maxTotalSockets || 256,
54
+ maxFreeSockets: opts.maxFreeSockets || 256,
55
+ scheduling: opts.scheduling || 'fifo'
56
+ };
57
+ this.agent = new https_1.Agent(this.agentOpts);
58
+ this.axios = axios_1.default.create({
59
+ httpsAgent: this.agent,
60
+ baseURL: 'https://api.sendblue.co'
61
+ });
62
+ this.axios.defaults.headers.post['Content-Type'] = DEFAULT_CONTENT_TYPE;
63
+ this.axios.defaults.headers.post['sb-api-key-id'] = apiKey;
64
+ this.axios.defaults.headers.post['sb-api-secret-key'] = apiSecret;
65
+ }
66
+ RequestClient.prototype.request = function (opts) {
67
+ return __awaiter(this, void 0, void 0, function () {
68
+ var options, response, err_1;
69
+ return __generator(this, function (_a) {
70
+ switch (_a.label) {
71
+ case 0:
72
+ options = {
73
+ method: opts.method,
74
+ baseURL: opts.baseURL || this.axios.defaults.baseURL,
75
+ url: opts.url,
76
+ headers: opts.headers,
77
+ params: opts.params,
78
+ data: opts.data,
79
+ timeout: opts.timeout || this.defaultTimeout,
80
+ maxRedirects: opts.maxRedirects ? 10 : 0,
81
+ validateStatus: function (status) {
82
+ return status >= 200 && status < 300;
83
+ }
84
+ };
85
+ if (opts.logLevel === 'debug' || this.logLevel === 'debug') {
86
+ this.logRequest(options);
87
+ }
88
+ _a.label = 1;
89
+ case 1:
90
+ _a.trys.push([1, 3, , 4]);
91
+ return [4 /*yield*/, this.axios.request(options)];
92
+ case 2:
93
+ response = _a.sent();
94
+ if (opts.logLevel === 'debug') {
95
+ console.log("response.statusCode: ".concat(response.status));
96
+ console.log("response.headers: ".concat(JSON.stringify(response.headers)));
97
+ }
98
+ return [2 /*return*/, response.data];
99
+ case 3:
100
+ err_1 = _a.sent();
101
+ if (err_1.response) {
102
+ throw new Error(JSON.stringify(err_1.response.data, null, 2));
103
+ }
104
+ else {
105
+ throw new Error(err_1.message);
106
+ }
107
+ return [3 /*break*/, 4];
108
+ case 4: return [2 /*return*/];
109
+ }
110
+ });
111
+ });
112
+ };
113
+ RequestClient.prototype.filterLoggingHeaders = function (headers) {
114
+ return Object.keys(headers).filter(function (header) {
115
+ return (!'authorization'.includes(header.toLowerCase()) &&
116
+ !'sb-api-key-id'.includes(header.toLowerCase()) &&
117
+ !'sb-api-secret-key'.includes(header.toLowerCase()));
118
+ });
119
+ };
120
+ RequestClient.prototype.logRequest = function (options) {
121
+ console.log('-- BEGIN Sendblue API Request --');
122
+ console.log("".concat(options.method, " ").concat(options.baseURL).concat(options.url));
123
+ if (options.params) {
124
+ console.log('Querystring:');
125
+ console.log(options.params);
126
+ }
127
+ if (options.headers) {
128
+ console.log('Headers:');
129
+ var filteredHeaderKeys = this.filterLoggingHeaders(options.headers);
130
+ filteredHeaderKeys.forEach(function (header) {
131
+ return console.log("".concat(header, ": ").concat(options.headers[header]));
132
+ });
133
+ }
134
+ console.log('-- END Sendblue API Request --');
135
+ };
136
+ return RequestClient;
137
+ }());
138
+ exports.RequestClient = RequestClient;
@@ -0,0 +1,18 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ import { GroupMessageOptions, Groups } from '../rest/group-message';
3
+ import { MessageOptions, Messages } from '../rest/message';
4
+ import { RequestClient, RequestClientOptions, RequestClientRequestOptions } from './RequestClient';
5
+ export interface SendblueClientOptions {
6
+ axiosClientOptions?: RequestClientOptions;
7
+ logLevel?: 'debug' | 'info' | 'warn' | 'error';
8
+ }
9
+ export declare class SendblueClient {
10
+ axiosClient: RequestClient;
11
+ groups: Groups;
12
+ messages: Messages;
13
+ logLevel: 'debug' | 'info' | 'warn' | 'error';
14
+ constructor(apiKey: string, apiSecret: string, options: SendblueClientOptions);
15
+ request(options: AxiosRequestConfig & RequestClientRequestOptions): Promise<any>;
16
+ sendGroupMessage(options: GroupMessageOptions): Promise<import("./Message").MessageImpl>;
17
+ sendMessage(options: MessageOptions): Promise<import("./Message").MessageImpl>;
18
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SendblueClient = void 0;
4
+ var group_message_1 = require("../rest/group-message");
5
+ var message_1 = require("../rest/message");
6
+ var RequestClient_1 = require("./RequestClient");
7
+ var SendblueClient = /** @class */ (function () {
8
+ function SendblueClient(apiKey, apiSecret, options) {
9
+ var _a;
10
+ this.logLevel = 'info';
11
+ if (options.logLevel !== ((_a = options === null || options === void 0 ? void 0 : options.axiosClientOptions) === null || _a === void 0 ? void 0 : _a.logLevel)) {
12
+ if (!options.axiosClientOptions)
13
+ options.axiosClientOptions = {};
14
+ options.axiosClientOptions.logLevel = options.logLevel;
15
+ }
16
+ this.logLevel = options.logLevel || 'info';
17
+ this.axiosClient = new RequestClient_1.RequestClient((options === null || options === void 0 ? void 0 : options.axiosClientOptions) || {}, apiKey, apiSecret);
18
+ this.groups = new group_message_1.Groups(this);
19
+ this.messages = new message_1.Messages(this);
20
+ }
21
+ SendblueClient.prototype.request = function (options) {
22
+ return this.axiosClient.request(options);
23
+ };
24
+ SendblueClient.prototype.sendGroupMessage = function (options) {
25
+ return this.groups.sendGroupMessage(options);
26
+ };
27
+ SendblueClient.prototype.sendMessage = function (options) {
28
+ return this.messages.sendMessage(options);
29
+ };
30
+ return SendblueClient;
31
+ }());
32
+ exports.SendblueClient = SendblueClient;
@@ -0,0 +1,2 @@
1
+ import { SendblueClient } from './base/SendblueClient';
2
+ export default SendblueClient;
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var SendblueClient_1 = require("./base/SendblueClient");
4
+ exports.default = SendblueClient_1.SendblueClient;
@@ -0,0 +1,23 @@
1
+ import { MessageImpl } from '../../base/Message';
2
+ import { SendblueClient } from '../../base/SendblueClient';
3
+ import { ExpressiveSendStyles } from '../../types';
4
+ export interface GroupMessageOptions {
5
+ numbers?: string[];
6
+ groupId?: string;
7
+ content?: string;
8
+ media_url?: string;
9
+ send_style?: ExpressiveSendStyles;
10
+ status_callback?: string;
11
+ }
12
+ export declare class Groups {
13
+ private client;
14
+ constructor(client: SendblueClient);
15
+ /**
16
+ *
17
+ * @param {GroupMessageOptions} options Group message options
18
+ * @returns {Message} message
19
+ *
20
+ * @throws {Error} if the request fails
21
+ */
22
+ sendGroupMessage(options: GroupMessageOptions): Promise<MessageImpl>;
23
+ }
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.Groups = void 0;
40
+ var Message_1 = require("../../base/Message");
41
+ var Groups = /** @class */ (function () {
42
+ function Groups(client) {
43
+ this.client = client;
44
+ }
45
+ /**
46
+ *
47
+ * @param {GroupMessageOptions} options Group message options
48
+ * @returns {Message} message
49
+ *
50
+ * @throws {Error} if the request fails
51
+ */
52
+ Groups.prototype.sendGroupMessage = function (options) {
53
+ return __awaiter(this, void 0, void 0, function () {
54
+ var responseData;
55
+ return __generator(this, function (_a) {
56
+ switch (_a.label) {
57
+ case 0: return [4 /*yield*/, this.client.request({
58
+ method: 'POST',
59
+ url: '/api/send-group-message',
60
+ data: options
61
+ })];
62
+ case 1:
63
+ responseData = _a.sent();
64
+ if (this.client.logLevel === 'debug')
65
+ console.log('Response:', responseData);
66
+ return [2 /*return*/, Message_1.MessageImpl.from(responseData)];
67
+ }
68
+ });
69
+ });
70
+ };
71
+ return Groups;
72
+ }());
73
+ exports.Groups = Groups;
@@ -0,0 +1,14 @@
1
+ import { MessageImpl } from '../../base/Message';
2
+ import { SendblueClient } from '../../base/SendblueClient';
3
+ export interface MessageOptions {
4
+ number: string;
5
+ content?: string;
6
+ media_url?: string;
7
+ status_callback?: string;
8
+ send_style?: string;
9
+ }
10
+ export declare class Messages {
11
+ private client;
12
+ constructor(client: SendblueClient);
13
+ sendMessage(options: MessageOptions): Promise<MessageImpl>;
14
+ }
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.Messages = void 0;
40
+ var Message_1 = require("../../base/Message");
41
+ var Messages = /** @class */ (function () {
42
+ function Messages(client) {
43
+ this.client = client;
44
+ }
45
+ Messages.prototype.sendMessage = function (options) {
46
+ return __awaiter(this, void 0, void 0, function () {
47
+ var responseData;
48
+ return __generator(this, function (_a) {
49
+ switch (_a.label) {
50
+ case 0: return [4 /*yield*/, this.client.request({
51
+ method: 'POST',
52
+ url: '/api/send-message',
53
+ data: options
54
+ })];
55
+ case 1:
56
+ responseData = _a.sent();
57
+ if (this.client.logLevel === 'debug')
58
+ console.log('Response:', responseData);
59
+ return [2 /*return*/, Message_1.MessageImpl.from(responseData)];
60
+ }
61
+ });
62
+ });
63
+ };
64
+ return Messages;
65
+ }());
66
+ exports.Messages = Messages;
@@ -0,0 +1 @@
1
+ export declare type ExpressiveSendStyles = 'celebration' | 'shooting_star' | 'fireworks' | 'lasers' | 'love' | 'confetti' | 'balloons' | 'spotlight' | 'echo' | 'invisible' | 'gentle' | 'loud' | 'slam';
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/index.d.ts ADDED
@@ -0,0 +1,78 @@
1
+ declare module 'openai-api' {
2
+ export interface CompletionOpts {
3
+ engine: string;
4
+ prompt?: string;
5
+ maxTokens?: number;
6
+ temperature?: number;
7
+ topP?: number;
8
+ n?: number;
9
+ stream?: boolean;
10
+ logprobs?: number;
11
+ echo?: boolean;
12
+ stop?: string | string[];
13
+ presencePenalty?: number;
14
+ frequencyPenalty?: number;
15
+ bestOf?: number;
16
+ user?: string;
17
+ logitBias?: { [token: string]: number; };
18
+ }
19
+
20
+ export interface Completion {
21
+ data: {
22
+ id: string;
23
+ object: string;
24
+ created: number;
25
+ model: string;
26
+ choices: Choice[];
27
+ };
28
+ }
29
+
30
+ export interface Choice {
31
+ text: string;
32
+ index: number;
33
+ logprobs: any;
34
+ finish_reason: string;
35
+ }
36
+
37
+ export interface SearchOpts {
38
+ engine: string;
39
+ documents?: string[];
40
+ file?: string;
41
+ query: string;
42
+ maxRerank?: number;
43
+ returnMetadata?: boolean;
44
+ }
45
+
46
+ export interface Search {
47
+ data: Document[];
48
+ object: string;
49
+ }
50
+
51
+ export interface Document {
52
+ document: number;
53
+ object: string;
54
+ score: number;
55
+ metadata?: any;
56
+ }
57
+
58
+ export interface Embedding {
59
+ object: string;
60
+ data: EmbeddingData[];
61
+ model: string;
62
+ }
63
+
64
+ export interface EmbeddingData {
65
+ object: string;
66
+ index: number;
67
+ embedding: number[];
68
+ }
69
+
70
+ class OpenAI {
71
+ constructor(api: string);
72
+ complete(opts: CompletionOpts): Promise<Completion>;
73
+ encode(str: string): number[];
74
+ search(opts: SearchOpts): Promise<Search>;
75
+ }
76
+
77
+ export default OpenAI;
78
+ }
package/index.js CHANGED
@@ -1,34 +1,106 @@
1
- const axios = require('axios');
2
- const url = require('url');
1
+ "use strict";
3
2
 
4
3
  const config = require('./config');
4
+ const axios = require('axios');
5
5
 
6
- module.exports = class Sendblue {
7
- constructor(apiKey, apiSecret, opts) {
8
- this._api_key = apiKey;
9
- this._api_secret = apiSecret;
10
- this._opts = opts;
11
- }
6
+ const DEFAULT_ENGINE = "davinci";
7
+
8
+ class OpenAI {
9
+ constructor(api_key) {
10
+ this._api_key = api_key;
11
+ }
12
12
 
13
- async sendText(number, content, opts) {
14
- const response = await axios.post(url.resolve(config.sendblue_base_url, config.send_message_endpoint), {number, content, ...this.opts, ...opts}, {
15
- headers: {
16
- 'sb-api-key-id': this._api_key,
17
- 'sb-api-secret-key': this._api_secret
18
- }
19
- });
13
+ _send_request(url, method, opts = {}) {
14
+ let camelToUnderscore = (key) => {
15
+ let result = key.replace(/([A-Z])/g, " $1");
16
+ return result.split(' ').join('_').toLowerCase();
17
+ };
20
18
 
21
- return response.data;
19
+ const data = {};
20
+ for (const key in opts) {
21
+ data[camelToUnderscore(key)] = opts[key];
22
22
  }
23
23
 
24
- async unregister(number, opts) {
25
- const response = await axios.post(url.resolve(config.sendblue_base_url, config.unregister_number_endpoint), {number}, {
26
- headers: {
27
- 'sb-api-key-id': this._api_key,
28
- 'sb-api-secret-key': this._api_secret
29
- }
30
- });
24
+ return axios({
25
+ url,
26
+ headers: {
27
+ 'Authorization': `Bearer ${this._api_key}`,
28
+ 'Content-Type': 'application/json'
29
+ },
30
+ data: Object.keys(data).length ? data : '',
31
+ method,
32
+ });
33
+ }
31
34
 
32
- return response.data;
35
+ _check_embeddings_engine_name(engine) {
36
+ const availableEngineNames = [
37
+ 'text-similarity-ada-001',
38
+ 'text-similarity-babbage-001',
39
+ 'text-similarity-curie-001',
40
+ 'text-similarity-davinci-001',
41
+ 'text-search-ada-doc-001',
42
+ 'text-search-ada-query-001',
43
+ 'text-search-babbage-doc-001',
44
+ 'text-search-babbage-query-001',
45
+ 'text-search-curie-doc-001',
46
+ 'text-search-curie-query-001',
47
+ 'text-search-davinci-doc-001',
48
+ 'text-search-davinci-query-001',
49
+ 'code-search-ada-code-001',
50
+ 'code-search-ada-text-001',
51
+ 'code-search-babbage-code-001',
52
+ 'code-search-babbage-text-001',
53
+ ];
54
+
55
+ if (!availableEngineNames.includes(engine)) {
56
+ throw new Error(`Unknown engine name for embeddings. Available engine names are ${availableEngineNames}`);
33
57
  }
34
- }
58
+ }
59
+
60
+ complete(opts) {
61
+ const url = config.completionURL(opts.engine || DEFAULT_ENGINE);
62
+ delete opts.engine;
63
+
64
+ return this._send_request(url, 'post', opts);
65
+ }
66
+
67
+ encode() {
68
+ // This method is no longer supported in Node>=v14. See
69
+ return Promise.resolve(new Array(2047).fill(""));
70
+ }
71
+
72
+ search(opts) {
73
+ const url = config.searchURL(opts.engine || DEFAULT_ENGINE);
74
+ delete opts.engine;
75
+ return this._send_request(url, 'post', opts);
76
+ }
77
+
78
+ answers(opts) {
79
+ const url = config.answersUrl();
80
+ return this._send_request(url, 'post', opts);
81
+ }
82
+
83
+ classification(opts) {
84
+ const url = config.classificationsUrl();
85
+ return this._send_request(url, "post", opts);
86
+ }
87
+
88
+ engines() {
89
+ const url = config.enginesUrl();
90
+ return this._send_request(url, 'get');
91
+ }
92
+
93
+ engine(engine) {
94
+ const url = config.engineUrl(engine);
95
+ return this._send_request(url, 'get');
96
+ }
97
+
98
+ embeddings(opts) {
99
+ this._check_embeddings_engine_name(opts.engine);
100
+
101
+ const url = config.embeddingsUrl(opts.engine);
102
+ return this._send_request(url, 'post', opts);
103
+ }
104
+ }
105
+
106
+ module.exports = OpenAI;
package/package.json CHANGED
@@ -1,18 +1,44 @@
1
1
  {
2
2
  "name": "sendblue",
3
- "version": "1.0.1",
4
- "description": "A Node.js wrapper for the Sendblue API",
5
- "main": "index.js",
3
+ "version": "1.1.2",
4
+ "description": "A tiny client module for the Sendblue API",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
6
7
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
8
+ "prepublish": "npm run build",
9
+ "build": "tsc",
10
+ "test": "mocha --use_strict"
8
11
  },
9
- "author": "",
12
+ "keywords": [
13
+ "api",
14
+ "sms",
15
+ "imessage",
16
+ "node",
17
+ "imessage api",
18
+ "sms api",
19
+ "sendblue",
20
+ "sendblue api",
21
+ "sendblue-node"
22
+ ],
23
+ "author": "Nikita Jerschow",
24
+ "contributors": [
25
+ {
26
+ "url": "https://github.com/jerschow"
27
+ }
28
+ ],
10
29
  "license": "ISC",
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "https://github.com/sendblue-api/sendblue-node.git"
33
+ },
11
34
  "dependencies": {
12
- "axios": "^0.19.2"
35
+ "@types/node": "^18.11.7",
36
+ "axios": "^0.21.1",
37
+ "dotenv": "^8.2.0"
13
38
  },
14
- "keywords": ["sendblue", "iMessage API", "Blue Message API", "sendblue node"],
15
- "repository": {
16
- "url": "https://github.com/Njerschow/sendblue-node.git"
39
+ "devDependencies": {
40
+ "chai": "^4.3.4",
41
+ "mocha": "^8.3.2",
42
+ "typescript": "^4.8.4"
17
43
  }
18
44
  }
@@ -0,0 +1,47 @@
1
+ require('dotenv').config();
2
+ const expect = require('chai').expect;
3
+ const Sendblue = require('../dist/').default;
4
+
5
+ const api_key = process.env.SENDBLUE_TEST_API_KEY;
6
+ if (!api_key) {
7
+ throw new Error('api key is needed to run testsuite: set environment variable: SENDBLUE_TEST_API_KEY');
8
+ }
9
+
10
+ const api_secret = process.env.SENDBLUE_TEST_API_SECRET;
11
+ if (!api_secret) {
12
+ throw new Error('api secret is needed to run testsuite: set environment variable: SENDBLUE_TEST_API_SECRET');
13
+ }
14
+
15
+ const test_number_1 = process.env.TEST_NUMBER_1;
16
+ if (!test_number_1) {
17
+ throw new Error('test number 1 is needed to run testsuite: set environment variable: TEST_NUMBER_1');
18
+ }
19
+
20
+ const test_number_2 = process.env.TEST_NUMBER_2;
21
+ if (!test_number_2) {
22
+ throw new Error('test number 2 is needed to run testsuite: set environment variable: TEST_NUMBER_2');
23
+ }
24
+
25
+ describe('basic sendblue api methods', function () {
26
+ this.timeout(8000);
27
+
28
+ const sendblueClient = new Sendblue(api_key, api_secret, {logLevel: 'debug'});
29
+
30
+ it('should handle single message', async function () {
31
+ const result = await sendblueClient.sendMessage({
32
+ number: test_number_1,
33
+ content: 'hello world',
34
+ media_url: 'https://source.unsplash.com/random/1000x1000.png',
35
+ })
36
+ expect(result).to.be.ok;
37
+ });
38
+
39
+ it('should handle group message', async function () {
40
+ const result = await sendblueClient.sendGroupMessage({
41
+ numbers: [test_number_1, test_number_2],
42
+ content: 'hello world 2',
43
+ media_url: 'https://source.unsplash.com/random/1000x1000.png',
44
+ });
45
+ expect(result).to.be.ok;
46
+ });
47
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es5",
4
+ "module": "commonjs",
5
+ "declaration": true,
6
+ "outDir": "./dist",
7
+ "strict": true
8
+ },
9
+ "include": ["lib/**/*.ts"]
10
+ }