@twilio/mcs-client 0.5.2-rc.2 → 0.5.3-rc.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.
@@ -1,584 +0,0 @@
1
- /*
2
- @license
3
- Copyright (c) 2018, Twilio, Inc.
4
-
5
- Permission to use, copy, modify, and/or distribute this software for any
6
- purpose with or without fee is hereby granted, provided that the above
7
- copyright notice and this permission notice appear in all copies.
8
-
9
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
12
- SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
14
- OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
15
- CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
-
17
- */
18
- 'use strict';
19
-
20
- var global =
21
- typeof global !== "undefined"
22
- ? global
23
- : typeof self !== "undefined"
24
- ? self
25
- : typeof window !== "undefined"
26
- ? window
27
- : {};
28
-
29
- Object.defineProperty(exports, '__esModule', { value: true });
30
-
31
- var log$2 = require('loglevel');
32
- var operationRetrier = require('@twilio/operation-retrier');
33
- var declarativeTypeValidator = require('@twilio/declarative-type-validator');
34
-
35
- function _interopNamespace(e) {
36
- if (e && e.__esModule) return e;
37
- var n = Object.create(null);
38
- if (e) {
39
- Object.keys(e).forEach(function (k) {
40
- if (k !== 'default') {
41
- var d = Object.getOwnPropertyDescriptor(e, k);
42
- Object.defineProperty(n, k, d.get ? d : {
43
- enumerable: true,
44
- get: function () {
45
- return e[k];
46
- }
47
- });
48
- }
49
- });
50
- }
51
- n['default'] = e;
52
- return Object.freeze(n);
53
- }
54
-
55
- var log__namespace = /*#__PURE__*/_interopNamespace(log$2);
56
-
57
- /*! *****************************************************************************
58
- Copyright (c) Microsoft Corporation.
59
-
60
- Permission to use, copy, modify, and/or distribute this software for any
61
- purpose with or without fee is hereby granted.
62
-
63
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
64
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
65
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
66
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
67
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
68
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
69
- PERFORMANCE OF THIS SOFTWARE.
70
- ***************************************************************************** */
71
-
72
- function __decorate(decorators, target, key, desc) {
73
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
74
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
75
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
76
- return c > 3 && r && Object.defineProperty(target, key, r), r;
77
- }
78
-
79
- function __metadata(metadataKey, metadataValue) {
80
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
81
- }
82
-
83
- function prepareLine(prefix, args) {
84
- return [`${new Date().toISOString()} MCS Client ${prefix}:`].concat(Array.from(args));
85
- }
86
- class Logger {
87
- constructor(prefix) {
88
- this.prefix = "";
89
- this.prefix =
90
- prefix !== null && prefix !== undefined && prefix.length > 0
91
- ? prefix + " "
92
- : "";
93
- }
94
- static scope(prefix) {
95
- return new Logger(prefix);
96
- }
97
- setLevel(level) {
98
- log__namespace.setLevel(level);
99
- }
100
- static setLevel(level) {
101
- log__namespace.setLevel(level);
102
- }
103
- /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
104
- trace(...args) {
105
- log__namespace.trace.apply(null, prepareLine(this.prefix + "T", args));
106
- }
107
- debug(...args) {
108
- log__namespace.debug.apply(null, prepareLine(this.prefix + "D", args));
109
- }
110
- info(...args) {
111
- log__namespace.info.apply(null, prepareLine(this.prefix + "I", args));
112
- }
113
- warn(...args) {
114
- log__namespace.warn.apply(null, prepareLine(this.prefix + "W", args));
115
- }
116
- error(...args) {
117
- log__namespace.error.apply(null, prepareLine(this.prefix + "E", args));
118
- }
119
- static trace(...args) {
120
- log__namespace.trace.apply(null, prepareLine("T", args));
121
- }
122
- static debug(...args) {
123
- log__namespace.debug.apply(null, prepareLine("D", args));
124
- }
125
- static info(...args) {
126
- log__namespace.info.apply(null, prepareLine("I", args));
127
- }
128
- static warn(...args) {
129
- log__namespace.warn.apply(null, prepareLine("W", args));
130
- }
131
- static error(...args) {
132
- log__namespace.error.apply(null, prepareLine("E", args));
133
- }
134
- }
135
-
136
- const MINIMUM_RETRY_DELAY = 1000;
137
- const MAXIMUM_RETRY_DELAY = 4000;
138
- const MAXIMUM_ATTEMPTS_COUNT = 3;
139
- const RETRY_WHEN_THROTTLED = true;
140
- const regionalMcsHost = (region) => `https://mcs.${region !== null && region !== void 0 ? region : "us1"}.twilio.com`;
141
- const isFullUrl = (url) => url.startsWith("http");
142
- const fullUrl = (partUrl, region) => `${!isFullUrl(partUrl) ? regionalMcsHost(region) : ""}${partUrl}`;
143
- class Configuration {
144
- constructor(token, baseUrl, baseSetUrl, options) {
145
- var _a, _b, _c, _d, _e, _f;
146
- const constructorOptions = (_b = (_a = options.MCS) !== null && _a !== void 0 ? _a : options) !== null && _b !== void 0 ? _b : {};
147
- this.region = (_d = (_c = constructorOptions.region) !== null && _c !== void 0 ? _c : options.region) !== null && _d !== void 0 ? _d : 'us1';
148
- this.mediaUrl = fullUrl(baseUrl, this.region);
149
- this.mediaSetUrl = baseSetUrl ? fullUrl(baseSetUrl) : `${this.mediaUrl}Set`;
150
- this.token = token;
151
- this.retryWhenThrottledOverride =
152
- (_e = constructorOptions.retryWhenThrottledOverride) !== null && _e !== void 0 ? _e : RETRY_WHEN_THROTTLED;
153
- this.backoffConfigOverride = (_f = constructorOptions.backoffConfigOverride) !== null && _f !== void 0 ? _f : Configuration.backoffConfigDefault;
154
- }
155
- static get backoffConfigDefault() {
156
- return {
157
- min: MINIMUM_RETRY_DELAY,
158
- max: MAXIMUM_RETRY_DELAY,
159
- maxAttemptsCount: MAXIMUM_ATTEMPTS_COUNT,
160
- };
161
- }
162
- static get retryWhenThrottledDefault() {
163
- return RETRY_WHEN_THROTTLED;
164
- }
165
- updateToken(token) {
166
- this.token = token;
167
- }
168
- }
169
-
170
- /**
171
- * @classdesc A Media represents a metadata information for the media upload
172
- * @property {String} sid - The server-assigned unique identifier for Media
173
- * @property {String} serviceSid - Service instance id which Media belongs/uploaded to
174
- * @property {Date} dateCreated - When the Media was created
175
- * @property {Date} dateUpdated - When the Media was updated
176
- * @property {Number} size - Size of media, bytes
177
- * @property {String} contentType - content type of media
178
- * @property {String} fileName - file name, if present, null otherwise
179
- * @property {MediaCategory} category - attachment category
180
- */
181
- class Media {
182
- constructor(config, network, data) {
183
- this.config = config;
184
- this.network = network;
185
- this._update(data);
186
- }
187
- get sid() {
188
- return this.state.sid;
189
- }
190
- get serviceSid() {
191
- return this.state.serviceSid;
192
- }
193
- get dateCreated() {
194
- return this.state.dateCreated;
195
- }
196
- get dateUpdated() {
197
- return this.state.dateUpdated;
198
- }
199
- get contentType() {
200
- return this.state.contentType;
201
- }
202
- get size() {
203
- return this.state.size;
204
- }
205
- /** @deprecated Use filename instead */
206
- get fileName() {
207
- return this.state.filename;
208
- }
209
- get filename() {
210
- return this.state.filename;
211
- }
212
- get category() {
213
- return this.state.category;
214
- }
215
- /**
216
- * Returns direct content URL to uploaded binary. This URL will expire after some time.
217
- * This function gets a new URL every time, preventing it from expiring but putting additional load on backend.
218
- * See getCachedContentUrl() for a function that reduces the amount of network requests.
219
- *
220
- * It is reasonable to build your own refresh logic upon these two functions: as soon as URL returned
221
- * by getCachedContentUrl() returns 40x status you should call getContentUrl() to refresh it.
222
- *
223
- * @returns {Promise<string>}
224
- */
225
- async getContentUrl() {
226
- const response = await this.network.get(`${this.config.mediaUrl}/${this.sid}`);
227
- this._update(response.body);
228
- return Promise.resolve(this.state.contentDirectUrl);
229
- }
230
- /**
231
- * Returns direct content URL to uploaded binary. This URL will expire after some time.
232
- * This function does not support getting a new URL however. Once set it will remain the same.
233
- * Use getContentUrl() to query a new one.
234
- *
235
- * It is reasonable to build your own refresh logic upon these two functions: as soon as URL returned
236
- * by getCachedContentUrl() returns 40x status you should call getContentUrl() to refresh it.
237
- *
238
- * @returns {Promise<string>}
239
- */
240
- async getCachedContentUrl() {
241
- if (this.state.contentDirectUrl) {
242
- return Promise.resolve(this.state.contentDirectUrl);
243
- }
244
- return await this.getContentUrl();
245
- }
246
- _update(data) {
247
- var _a, _b, _c, _d;
248
- this.state = {
249
- sid: data.sid,
250
- serviceSid: data.service_sid,
251
- channelSid: data.channel_sid,
252
- messageSid: data.message_sid,
253
- dateCreated: data.date_created ? new Date(data.date_created) : null,
254
- dateUploadUpdated: data.date_upload_updated
255
- ? new Date(data.date_upload_updated)
256
- : null,
257
- dateUpdated: data.date_updated ? new Date(data.date_updated) : null,
258
- size: data.size,
259
- contentType: data.content_type,
260
- author: data.author,
261
- url: data.url,
262
- contentUrl: data.links.content,
263
- contentDirectUrl: (_a = data.links.content_direct_temporary) !== null && _a !== void 0 ? _a : null,
264
- filename: (_b = data.filename) !== null && _b !== void 0 ? _b : null,
265
- category: (_c = data.category) !== null && _c !== void 0 ? _c : "media",
266
- isMultipartUpstream: (_d = data.is_multipart_upstream) !== null && _d !== void 0 ? _d : false,
267
- };
268
- }
269
- }
270
-
271
- class TransportError extends Error {
272
- constructor(message, code, body, status, headers) {
273
- super(message);
274
- this.code = code;
275
- this.body = body;
276
- this.status = status;
277
- this.headers = headers;
278
- }
279
- }
280
-
281
- // eslint-disable-next-line
282
- const XHR = global["XMLHttpRequest"] || {};
283
- function parseResponseHeaders(headerString) {
284
- if (!headerString) {
285
- return {};
286
- }
287
- return headerString
288
- .split("\u000d\u000a")
289
- .map((el) => el.split("\u003a\u0020"))
290
- .filter((el) => el.length === 2 && el[1].length > 0)
291
- .reduce((prev, curr) => {
292
- prev[curr[0]] = curr[1];
293
- return prev;
294
- }, {});
295
- }
296
- function extractBody(xhr) {
297
- const contentType = xhr.getResponseHeader("Content-Type");
298
- if (!contentType ||
299
- contentType.indexOf("application/json") !== 0 ||
300
- xhr.responseText.length === 0) {
301
- return xhr.responseText;
302
- }
303
- try {
304
- return JSON.parse(xhr.responseText);
305
- }
306
- catch (e) {
307
- return xhr.responseText;
308
- }
309
- }
310
- /**
311
- * Provides generic network interface
312
- */
313
- class Transport {
314
- static async request(method, url, headers, body) {
315
- return new Promise((resolve, reject) => {
316
- const xhr = new XHR();
317
- xhr.open(method, url, true);
318
- xhr.onreadystatechange = function onreadystatechange() {
319
- var _a;
320
- if (xhr.readyState !== 4) {
321
- return;
322
- }
323
- const headers = parseResponseHeaders(xhr.getAllResponseHeaders());
324
- const body = extractBody(xhr);
325
- if (200 <= xhr.status && xhr.status < 300) {
326
- resolve({ status: xhr.status, headers, body });
327
- }
328
- else {
329
- const status = (_a = xhr.statusText) !== null && _a !== void 0 ? _a : "NONE";
330
- let bodyRepresentation;
331
- if (typeof body === "string") {
332
- bodyRepresentation =
333
- body && body.split("\n", 2).length === 1 ? body : "";
334
- }
335
- else {
336
- bodyRepresentation = JSON.stringify(body);
337
- }
338
- const message = `${xhr.status}: [${status}] ${bodyRepresentation}`;
339
- reject(new TransportError(message, xhr.status, body, status, headers));
340
- }
341
- };
342
- for (const headerName in headers) {
343
- xhr.setRequestHeader(headerName, headers[headerName]);
344
- if (headerName === "Content-Type" &&
345
- headers[headerName] === "application/json") {
346
- body = JSON.stringify(body);
347
- }
348
- }
349
- xhr.send(body);
350
- });
351
- }
352
- /**
353
- * Make a GET request by given URL
354
- */
355
- async get(url, headers) {
356
- return Transport.request("GET", url, headers);
357
- }
358
- /**
359
- * Make a POST request by given URL
360
- */
361
- async post(url, headers, body) {
362
- return Transport.request("POST", url, headers, body);
363
- }
364
- }
365
-
366
- const log$1 = Logger.scope("Network");
367
- class Network {
368
- constructor(config, transport) {
369
- this.config = config;
370
- this.transport = transport;
371
- }
372
- backoffConfig() {
373
- return Object.assign(Configuration.backoffConfigDefault, this.config.backoffConfigOverride);
374
- }
375
- retryWhenThrottled() {
376
- var _a, _b;
377
- return ((_b = (_a = this.config.retryWhenThrottledOverride) !== null && _a !== void 0 ? _a : Configuration.retryWhenThrottledDefault) !== null && _b !== void 0 ? _b : false);
378
- }
379
- async executeWithRetry(request, retryWhenThrottled) {
380
- return new Promise((resolve, reject) => {
381
- const codesToRetryOn = [502, 503, 504];
382
- if (retryWhenThrottled) {
383
- codesToRetryOn.push(429);
384
- }
385
- const retrier = new operationRetrier.Retrier(this.backoffConfig());
386
- retrier.on("attempt", async () => {
387
- try {
388
- const result = await request();
389
- retrier.succeeded(result);
390
- }
391
- catch (err) {
392
- if (codesToRetryOn.indexOf(err.status) > -1) {
393
- retrier.failed(err);
394
- }
395
- else if (err.message === "Twilsock disconnected") {
396
- // Ugly hack. We must make a proper exceptions for twilsock
397
- retrier.failed(err);
398
- }
399
- else {
400
- // Fatal error
401
- retrier.removeAllListeners();
402
- retrier.cancel();
403
- reject(err);
404
- }
405
- }
406
- });
407
- retrier.on("succeeded", (result) => {
408
- resolve(result);
409
- });
410
- retrier.on("cancelled", (err) => reject(err));
411
- retrier.on("failed", (err) => reject(err));
412
- retrier.start();
413
- });
414
- }
415
- async get(url) {
416
- const headers = { "X-Twilio-Token": this.config.token };
417
- log$1.trace("sending GET request to ", url, " headers ", headers);
418
- try {
419
- const response = await this.executeWithRetry(() => this.transport.get(url, headers), this.retryWhenThrottled());
420
- log$1.trace("response", response);
421
- return response;
422
- }
423
- catch (err) {
424
- log$1.debug(`get() error ${err}`);
425
- throw err;
426
- }
427
- }
428
- async post(url, category, media, contentType, filename) {
429
- const headers = {
430
- "X-Twilio-Token": this.config.token,
431
- };
432
- if ((typeof FormData === "undefined" || !(media instanceof FormData)) &&
433
- contentType) {
434
- Object.assign(headers, {
435
- "Content-Type": contentType,
436
- });
437
- }
438
- const fullUrl = new URL(url);
439
- if (category) {
440
- fullUrl.searchParams.append("Category", category);
441
- }
442
- if (filename) {
443
- fullUrl.searchParams.append("Filename", filename);
444
- }
445
- let response;
446
- log$1.trace(`sending POST request to ${url} with headers ${headers}`);
447
- try {
448
- response = await this.transport.post(fullUrl.href, headers, media);
449
- }
450
- catch (err) {
451
- // If global["XMLHttpRequest"] is undefined, it means that the code is
452
- // not being executed in the browser.
453
- if (global["XMLHttpRequest"] === undefined && media instanceof FormData) {
454
- throw new TypeError("Posting FormData supported only with browser engine's FormData");
455
- }
456
- log$1.debug(`post() error ${err}`);
457
- throw err;
458
- }
459
- log$1.trace("response", response);
460
- return response;
461
- }
462
- }
463
-
464
- var version = "0.5.2-rc.2";
465
-
466
- const log = Logger.scope("");
467
- /**
468
- * @classdesc A Client provides an interface for Media Content Service
469
- */
470
- exports['default'] = class Client {
471
- /**
472
- * Base URLs must be full URLs with host. If host is not provided it will be generated from a default configuration
473
- * template using options.region.
474
- *
475
- * @param {String} token - Access token
476
- * @param {String} baseUrl - Base URL for Media Content Service Media resource, i.e. /v1/Services/{serviceSid}/Media
477
- * @param {String} baseSetUrl - Base URL for Media Content Service MediaSet resource, i.e. /v1/Services/{serviceSid}/MediaSet
478
- * @param {Client#ClientOptions} [options] - Options to customize the Client
479
- */
480
- constructor(token, baseUrl, baseSetUrl, options = {}) {
481
- var _a, _b;
482
- this.options = options;
483
- this.options.logLevel = (_a = this.options.logLevel) !== null && _a !== void 0 ? _a : "silent";
484
- this.config = new Configuration(token, baseUrl, baseSetUrl, this.options);
485
- log.setLevel(this.options.logLevel);
486
- this.options.transport = (_b = this.options.transport) !== null && _b !== void 0 ? _b : new Transport();
487
- this.transport = this.options.transport;
488
- this.network = new Network(this.config, this.transport);
489
- }
490
- /**
491
- * These options can be passed to Client constructor
492
- * @typedef {Object} Client#ClientOptions
493
- * @property {String} [logLevel='silent'] - The level of logging to enable. Valid options
494
- * (from strictest to broadest): ['silent', 'error', 'warn', 'info', 'debug', 'trace']
495
- */
496
- /**
497
- * Update the token used for Client operations
498
- * @param {String} token - The JWT string of the new token
499
- * @returns {void}
500
- */
501
- updateToken(token) {
502
- log.info("updateToken");
503
- this.config.updateToken(token);
504
- }
505
- /**
506
- * Gets media from media service
507
- * @param {String} sid - Media's SID
508
- * @returns {Promise<Media>}
509
- */
510
- async get(sid) {
511
- const response = await this.network.get(`${this.config.mediaUrl}/${sid}`);
512
- return new Media(this.config, this.network, response.body);
513
- }
514
- /**
515
- * Posts raw content to media service
516
- * @param {String} contentType - content type of media
517
- * @param {String|Buffer|Blob} media - content to post
518
- * @param {MediaCategory|null} category - category for the media
519
- * @returns {Promise<Media>}
520
- */
521
- async post(contentType, media, category, filename) {
522
- const response = await this.network.post(this.config.mediaUrl, category !== null && category !== void 0 ? category : "media", media, contentType, filename);
523
- return new Media(this.config, this.network, response.body);
524
- }
525
- /**
526
- * Posts FormData to media service. Can be used only with browser engine's FormData.
527
- * In non-browser FormData case the method will do promise reject with
528
- * new TypeError("Posting FormData supported only with browser engine's FormData")
529
- * @param {FormData} formData - form data to post
530
- * @param {MediaCategory|null} category - category for the media
531
- * @returns {Promise<Media>}
532
- */
533
- async postFormData(formData, category) {
534
- const response = await this.network.post(this.config.mediaUrl, category !== null && category !== void 0 ? category : "media", formData);
535
- return new Media(this.config, this.network, response.body);
536
- }
537
- /**
538
- * Retrieve information about multiple media SIDs at the same time.
539
- * @param mediaSids Array of Media SIDs to get information from.
540
- */
541
- async mediaSetGet(mediaSids) {
542
- const query = {
543
- command: "get",
544
- list: mediaSids.map((sid) => ({ media_sid: sid })),
545
- };
546
- const response = (await this.network.post(`${this.config.mediaSetUrl}`, null, JSON.stringify(query), "application/json"));
547
- return response.map((item) => {
548
- if (item.code !== 200) {
549
- throw new Error(`Failed to obtain detailed information about Media items (failed SID ${item.media_record.sid})`);
550
- }
551
- return new Media(this.config, this.network, item.media_record);
552
- });
553
- }
554
- };
555
- exports['default'].version = version;
556
- __decorate([
557
- declarativeTypeValidator.validateTypes(declarativeTypeValidator.nonEmptyString),
558
- __metadata("design:type", Function),
559
- __metadata("design:paramtypes", [String]),
560
- __metadata("design:returntype", void 0)
561
- ], exports['default'].prototype, "updateToken", null);
562
- __decorate([
563
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
564
- __metadata("design:type", Function),
565
- __metadata("design:paramtypes", [String]),
566
- __metadata("design:returntype", Promise)
567
- ], exports['default'].prototype, "get", null);
568
- exports['default'] = __decorate([
569
- declarativeTypeValidator.validateConstructorTypes(declarativeTypeValidator.nonEmptyString, declarativeTypeValidator.nonEmptyString, [
570
- declarativeTypeValidator.nonEmptyString,
571
- declarativeTypeValidator.literal(null),
572
- ], [
573
- declarativeTypeValidator.pureObject,
574
- 'undefined',
575
- ]),
576
- __metadata("design:paramtypes", [String, String, Object, Object])
577
- ], exports['default']);
578
-
579
- exports.Client = exports['default'];
580
- exports.McsClient = exports['default'];
581
- exports.McsMedia = Media;
582
- exports.Media = Media;
583
- exports.default = exports['default'];
584
- //# sourceMappingURL=react-native.js.map