Socket
Socket
Sign inDemoInstall

twilio-sync

Package Overview
Dependencies
Maintainers
2
Versions
608
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

twilio-sync - npm Package Compare versions

Comparing version 0.4.2-test.3 to 0.5.0-dev.1

.vscode/settings.json

335

browser/client.js
"use strict";
var _regenerator = require("babel-runtime/regenerator");
var _regenerator2 = _interopRequireDefault(_regenerator);
var _stringify = require("babel-runtime/core-js/json/stringify");

@@ -7,6 +11,2 @@

var _regenerator = require("babel-runtime/regenerator");
var _regenerator2 = _interopRequireDefault(_regenerator);
var _getPrototypeOf = require("babel-runtime/core-js/object/get-prototype-of");

@@ -63,2 +63,3 @@

var events_1 = require("events");
var xxhashjs_1 = require("xxhashjs");
var Twilsock = require("twilsock");

@@ -104,4 +105,3 @@ var twilio_transport_1 = require("twilio-transport");

mode: arg.mode,
optimistic: arg.optimistic
};
optimistic: !!arg.optimistic };
}

@@ -136,3 +136,2 @@ /**

}
_this.serviceSid = null;
var productId = options.productId = options.productId || SYNC_PRODUCT_ID;

@@ -145,5 +144,6 @@ var twilsock = options.twilsockClient = options.twilsockClient || new Twilsock(fpaToken, options);

var network = new network_1.Network(productId, new clientInfo_1.ClientInfo(SDK_VERSION), config, transport);
_this.localStorageId = null;
_this.fpaToken = fpaToken;
emsClient.setToken(fpaToken).then(function (response) {
return _this.services.config.updateToken(response.token);
return _this.handleEmsResponse(response);
});

@@ -171,4 +171,13 @@ twilsock.connect();

(0, _createClass3.default)(SyncClient, [{
key: "ensureReady",
key: "handleEmsResponse",
value: function handleEmsResponse(response) {
this.services.config.updateToken(response.token);
try {
var identity = response.identity;
var serviceSid = response.serviceSids['data_sync'];
this.localStorageId = xxhashjs_1.h64().update("TW::" + identity + "::" + serviceSid).digest().toString(16);
} catch (e) {
logger_1.default.error('Failed to initialize persistent storage', e);
}
}
/**

@@ -178,2 +187,5 @@ * Returns promise which resolves when library is correctly initialized

*/
}, {
key: "ensureReady",
value: function ensureReady() {

@@ -194,6 +206,27 @@ var _this2 = this;

}, {
key: "storeInSessionCache",
value: function storeInSessionCache(type, id, value) {
try {
var dataToStore = (0, _stringify2.default)(value);
sessionStorage.setItem(this.localStorageId + '::' + type + '::' + id, dataToStore);
} catch (e) {}
}
}, {
key: "readFromSessionCache",
value: function readFromSessionCache(type, id) {
try {
var storedData = sessionStorage.getItem(this.localStorageId + '::' + type + '::' + id);
if (storedData) {
return JSON.parse(storedData);
}
} catch (e) {}
return null;
}
}, {
key: "_get",
value: function _get(baseUri, id) {
var optimistic = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee() {
var uri, response, objects, result;
var uri, response;
return _regenerator2.default.wrap(function _callee$(_context) {

@@ -211,18 +244,26 @@ while (1) {

case 2:
uri = new utils_1.UriBuilder(baseUri).arg('Deep', true).arg('Id', id).build();
_context.next = 5;
uri = new utils_1.UriBuilder(baseUri).path(id).arg('Include', optimistic ? 'items' : undefined).build();
_context.prev = 3;
_context.next = 6;
return this.services.network.get(uri);
case 5:
case 6:
response = _context.sent;
objects = response.body.documents || response.body.lists || response.body.maps || [];
result = objects.length === 0 ? null : objects[0];
// Hacky optimization - here we learn the service sid
return _context.abrupt("return", response.body);
if (result && result.service_sid && !this.serviceSid) {
this.serviceSid = result.service_sid;
case 10:
_context.prev = 10;
_context.t0 = _context["catch"](3);
if (!(_context.t0.status === 404)) {
_context.next = 14;
break;
}
return _context.abrupt("return", { root: result, items: [] });
case 10:
return _context.abrupt("return", null);
case 14:
throw _context.t0;
case 15:
case "end":

@@ -232,3 +273,3 @@ return _context.stop();

}
}, _callee, this);
}, _callee, this, [[3, 10]]);
}));

@@ -247,9 +288,16 @@ }

value: function _getDocument(id) {
var cachedRoot = this.getRoot(id, 'document');
if (cachedRoot) {
return _promise2.default.resolve(cachedRoot);
}
return this._get(this.services.config.documentsUri, id).then(function (body) {
return body ? body.root : null;
});
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee2() {
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt("return", this.readFromSessionCache(syncdocument_1.SyncDocument.type, id) || this._get(this.services.config.documentsUri, id));
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
}

@@ -267,9 +315,16 @@ }, {

value: function _getList(id) {
var cachedRoot = this.getRoot(id, 'list');
if (cachedRoot) {
return _promise2.default.resolve(cachedRoot);
}
return this._get(this.services.config.listsUri, id).then(function (body) {
return body ? body.root : null;
});
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee3() {
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
return _context3.abrupt("return", this.readFromSessionCache(synclist_1.SyncList.type, id) || this._get(this.services.config.listsUri, id));
case 1:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
}

@@ -281,3 +336,3 @@ }, {

return this.services.network.post(this.services.config.mapsUri, payload).then(function (response) {
return { root: response.body, items: [] };
return response.body;
});

@@ -290,54 +345,15 @@ }

return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee2() {
var url, response, cachedRoot;
return _regenerator2.default.wrap(function _callee2$(_context2) {
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee4() {
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context2.prev = _context2.next) {
switch (_context4.prev = _context4.next) {
case 0:
if (id) {
_context2.next = 2;
break;
}
return _context4.abrupt("return", this.readFromSessionCache(syncmap_1.SyncMap.type, id) || this._get(this.services.config.mapsUri, id, optimistic));
return _context2.abrupt("return", null);
case 2:
if (!(optimistic && this.serviceSid)) {
_context2.next = 14;
break;
}
_context2.prev = 3;
url = new utils_1.UriBuilder(this.services.config.baseUri).path('v3').path('Services').path(this.serviceSid).path('Maps').path(id).path('Items').arg('Metadata', 'map').build();
_context2.next = 7;
return this.services.network.get(url);
case 7:
response = _context2.sent;
return _context2.abrupt("return", { root: response.body.map, items: response.body.items });
case 11:
_context2.prev = 11;
_context2.t0 = _context2["catch"](3);
return _context2.abrupt("return", null);
case 14:
cachedRoot = this.getRoot(id, 'map');
if (!cachedRoot) {
_context2.next = 17;
break;
}
return _context2.abrupt("return", { root: cachedRoot, items: [] });
case 17:
return _context2.abrupt("return", this._get(this.services.config.mapsUri, id));
case 18:
case 1:
case "end":
return _context2.stop();
return _context4.stop();
}
}
}, _callee2, this, [[3, 11]]);
}, _callee4, this);
}));

@@ -365,3 +381,3 @@ }

value: function document(arg) {
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee3() {
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee5() {
var _this3 = this;

@@ -371,7 +387,7 @@

return _regenerator2.default.wrap(function _callee3$(_context3) {
return _regenerator2.default.wrap(function _callee5$(_context5) {
while (1) {
switch (_context3.prev = _context3.next) {
switch (_context5.prev = _context5.next) {
case 0:
_context3.next = 2;
_context5.next = 2;
return this.ensureReady();

@@ -381,3 +397,3 @@

_decompose = decompose(arg), id = _decompose.id, purpose = _decompose.purpose, data = _decompose.data, mode = _decompose.mode;
return _context3.abrupt("return", this.getCached(id, 'document') || this._getDocument(id).then(function (body) {
return _context5.abrupt("return", this.getCached(id, 'document') || this._getDocument(id).then(function (body) {
if (body) {

@@ -390,3 +406,3 @@ return body;

}).then(function (body) {
_this3.storeRoot(id, 'document', body);
_this3.storeInSessionCache(syncdocument_1.SyncDocument.type, id, body);
return new syncdocument_1.SyncDocument(_this3.services, body, function (sid) {

@@ -401,6 +417,6 @@ return _this3.removeFromCache(sid);

case "end":
return _context3.stop();
return _context5.stop();
}
}
}, _callee3, this);
}, _callee5, this);
}));

@@ -418,12 +434,12 @@ }

value: function map(arg) {
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee4() {
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee6() {
var _this4 = this;
var _decompose2, id, purpose, context, mode, optimistic, cachedMap, map;
var _decompose2, id, purpose, context, mode, optimistic;
return _regenerator2.default.wrap(function _callee4$(_context4) {
return _regenerator2.default.wrap(function _callee6$(_context6) {
while (1) {
switch (_context4.prev = _context4.next) {
switch (_context6.prev = _context6.next) {
case 0:
_context4.next = 2;
_context6.next = 2;
return this.ensureReady();

@@ -433,44 +449,24 @@

_decompose2 = decompose(arg), id = _decompose2.id, purpose = _decompose2.purpose, context = _decompose2.context, mode = _decompose2.mode, optimistic = _decompose2.optimistic;
cachedMap = this.getCached(id, 'map');
if (!cachedMap) {
_context4.next = 6;
break;
}
return _context4.abrupt("return", cachedMap);
case 6:
console.log('----------xxxx1');
_context4.next = 9;
return this._getMap(id, optimistic).then(function (body) {
console.log('----------xxxx1', body);
if (body.root) {
return _context6.abrupt("return", this.getCached(id, 'map') || this._getMap(id, optimistic).then(function (body) {
if (body) {
return body;
} else if (mode !== 'open') {
return _this4._createMap(id, purpose, context);
}
if (mode === 'open') {
throw new syncerror_1.default('Not found', 404);
}
console.log('Creating');
return _this4._createMap(id, purpose, context);
}).then(function (map) {
_this4.storeRoot(id, 'map', map.root);
return new syncmap_1.SyncMap(_this4.services, map.root, map.items, function (sid) {
throw new syncerror_1.default('Not found', 404);
}).then(function (body) {
_this4.storeInSessionCache(syncmap_1.SyncMap.type, id, body);
return new syncmap_1.SyncMap(_this4.services, body, function (sid) {
return _this4.removeFromCache(sid);
});
});
}).then(function (entity) {
return _this4.entities.store(entity);
}).then(subscribe));
case 9:
map = _context4.sent;
this.entities.store(map);
subscribe(map);
return _context4.abrupt("return", map);
case 13:
case 4:
case "end":
return _context4.stop();
return _context6.stop();
}
}
}, _callee4, this);
}, _callee6, this);
}));

@@ -488,3 +484,3 @@ }

value: function list(arg) {
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee5() {
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee7() {
var _this5 = this;

@@ -494,7 +490,7 @@

return _regenerator2.default.wrap(function _callee5$(_context5) {
return _regenerator2.default.wrap(function _callee7$(_context7) {
while (1) {
switch (_context5.prev = _context5.next) {
switch (_context7.prev = _context7.next) {
case 0:
_context5.next = 2;
_context7.next = 2;
return this.ensureReady();

@@ -504,3 +500,3 @@

_decompose3 = decompose(arg), id = _decompose3.id, purpose = _decompose3.purpose, context = _decompose3.context, mode = _decompose3.mode;
return _context5.abrupt("return", this.getCached(id, 'list') || this._getList(id).then(function (body) {
return _context7.abrupt("return", this.getCached(id, 'list') || this._getList(id).then(function (body) {
if (body) {

@@ -513,3 +509,3 @@ return body;

}).then(function (body) {
_this5.storeRoot(id, 'list', body);
_this5.storeInSessionCache(synclist_1.SyncList.type, id, body);
return new synclist_1.SyncList(_this5.services, body, function (sid) {

@@ -524,6 +520,6 @@ return _this5.removeFromCache(sid);

case "end":
return _context5.stop();
return _context7.stop();
}
}
}, _callee5, this);
}, _callee7, this);
}));

@@ -541,12 +537,12 @@ }

value: function shutdown() {
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee6() {
return _regenerator2.default.wrap(function _callee6$(_context6) {
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee8() {
return _regenerator2.default.wrap(function _callee8$(_context8) {
while (1) {
switch (_context6.prev = _context6.next) {
switch (_context8.prev = _context8.next) {
case 0:
_context6.next = 2;
_context8.next = 2;
return this.services.subscriptions.shutdown();
case 2:
_context6.next = 4;
_context8.next = 4;
return this.services.twilsock.disconnect();

@@ -556,6 +552,6 @@

case "end":
return _context6.stop();
return _context8.stop();
}
}
}, _callee6, this);
}, _callee8, this);
}));

@@ -573,44 +569,29 @@ }

value: function updateToken(fpaToken) {
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee7() {
return _regenerator2.default.wrap(function _callee7$(_context7) {
return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee9() {
var response;
return _regenerator2.default.wrap(function _callee9$(_context9) {
while (1) {
switch (_context7.prev = _context7.next) {
switch (_context9.prev = _context9.next) {
case 0:
_context9.next = 2;
return this.services.emsClient.setToken(fpaToken);
case 2:
response = _context9.sent;
this.services.config.updateToken(response.token);
_context9.next = 6;
return _promise2.default.all([this.services.notifications.updateToken(fpaToken), this.services.twilsock.updateToken(fpaToken)]);
case 6:
this.fpaToken = fpaToken;
_context7.next = 3;
return _promise2.default.all([this.services.config.updateToken(fpaToken), this.services.notifications.updateToken(fpaToken), this.services.twilsock.updateToken(fpaToken)]);
case 3:
case 7:
case "end":
return _context7.stop();
return _context9.stop();
}
}
}, _callee7, this);
}, _callee9, this);
}));
}
}, {
key: "storeRoot",
value: function storeRoot(id, type, object) {
try {
if (sessionStorage) {
var entryId = type + '::' + id;
sessionStorage.setItem(entryId, (0, _stringify2.default)(object));
}
} catch (e) {}
}
}, {
key: "getRoot",
value: function getRoot(id, type) {
try {
if (sessionStorage) {
var entryId = type + '::' + id;
var data = sessionStorage.getItem(entryId);
if (data) {
return JSON.parse(data);
}
}
} catch (e) {}
return null;
}
}, {
key: "connectionState",

@@ -617,0 +598,0 @@ get: function get() {

@@ -33,3 +33,2 @@ "use strict";

this.settings = {
baseUri: baseUri,
subscriptionsUri: baseUri + SUBSCRIPTIONS_PATH,

@@ -53,7 +52,2 @@ documentsUri: baseUri + DOCUMENTS_PATH,

}, {
key: 'baseUri',
get: function get() {
return this.settings.baseUri;
}
}, {
key: 'subscriptionsUri',

@@ -60,0 +54,0 @@ get: function get() {

@@ -22,61 +22,59 @@ "use strict";

var MapItem = function () {
/**
* @private
* @constructor
* @param {Object} data Item descriptor
* @param {String} data.key Item identifier
* @param {String} data.uri Item URI
* @param {Object} data.value Item data
*/
function MapItem(descriptor) {
(0, _classCallCheck3.default)(this, MapItem);
this.descriptor = descriptor;
}
(0, _createClass3.default)(MapItem, [{
key: "update",
/**
* Update item data
* @param {Number} EventId Update event id
* @param {String} Revision Updated item revision
* @param {Object} Value Updated item data
* @private
* @constructor
* @param {Object} data Item descriptor
* @param {String} data.key Item identifier
* @param {String} data.uri Item URI
* @param {Object} data.value Item data
*/
function MapItem(data) {
(0, _classCallCheck3.default)(this, MapItem);
this.data = data;
value: function update(eventId, revision, value) {
this.descriptor.last_event_id = eventId;
this.descriptor.revision = revision;
this.descriptor.data = value;
return this;
}
(0, _createClass3.default)(MapItem, [{
key: "update",
/**
* Update item data
* @param {Number} EventId Update event id
* @param {String} Revision Updated item revision
* @param {Object} Value Updated item data
* @private
*/
value: function update(eventId, revision, value) {
if (eventId > this.data.last_event_id) {
this.data.last_event_id = eventId;
this.data.revision = revision;
this.data.data = value;
}
return this;
}
}, {
key: "uri",
get: function get() {
return this.data.url;
}
}, {
key: "revision",
get: function get() {
return this.data.revision;
}
}, {
key: "lastEventId",
get: function get() {
return this.data.last_event_id;
}
}, {
key: "key",
get: function get() {
return this.data.key;
}
}, {
key: "value",
get: function get() {
return this.data.data;
}
}]);
return MapItem;
}, {
key: "uri",
get: function get() {
return this.descriptor.url;
}
}, {
key: "revision",
get: function get() {
return this.descriptor.revision;
}
}, {
key: "lastEventId",
get: function get() {
return this.descriptor.last_event_id;
}
}, {
key: "key",
get: function get() {
return this.descriptor.key;
}
}, {
key: "value",
get: function get() {
return this.descriptor.data;
}
}]);
return MapItem;
}();

@@ -83,0 +81,0 @@

@@ -393,3 +393,3 @@ "use strict";

logger_1.default.debug("Failed an attempt to " + action + " subscriptions (c:" + correlationId + "); retrying", _context.t2);
this.backoff.backoff(_context.t2);
this.persist();
}

@@ -396,0 +396,0 @@

@@ -91,3 +91,3 @@ "use strict";

*/
function SyncMap(services, descriptor, items, onRemoveMap) {
function SyncMap(services, descriptor, onRemoveMap) {
(0, _classCallCheck3.default)(this, SyncMap);

@@ -97,3 +97,2 @@

console.log('Got descriptor', descriptor);
_this.actionQueue = new retryingqueue_1.RetryingQueue();

@@ -103,3 +102,7 @@ _this.cache = new cache_1.Cache();

_this.onRemoveMap = onRemoveMap;
_this.populateItems(items);
if (descriptor.items) {
descriptor.items.forEach(function (itemDescriptor) {
_this.cache.store(itemDescriptor.key, new mapitem_1.MapItem(itemDescriptor), itemDescriptor.last_event_id);
});
}
return _this;

@@ -109,11 +112,2 @@ }

(0, _createClass3.default)(SyncMap, [{
key: "populateItems",
value: function populateItems(items) {
var _this2 = this;
items.forEach(function (item) {
return _this2.cache.store(item.key, new mapitem_1.MapItem(item), item.last_event_id);
});
}
}, {
key: "_get",

@@ -146,3 +140,3 @@ value: function _get(key) {

return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee2() {
var _this3 = this;
var _this2 = this;

@@ -164,3 +158,3 @@ var _resolver;

_resolver = function _resolver(err) {
return __awaiter(_this3, void 0, void 0, _regenerator2.default.mark(function _callee() {
return __awaiter(_this2, void 0, void 0, _regenerator2.default.mark(function _callee() {
var item;

@@ -295,3 +289,3 @@ return _regenerator2.default.wrap(function _callee$(_context) {

return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee4() {
var _this4 = this;
var _this3 = this;

@@ -312,3 +306,3 @@ var uri, response;

response.body.events.forEach(function (ev) {
return _this4._update(ev);
return _this3._update(ev);
});

@@ -463,6 +457,6 @@ _context4.next = 12;

if (item) {
item.update(descriptor.last_event_id, descriptor.revision, descriptor.data);
if (item && descriptor.lastEventId > item.lastEventId) {
item.update(descriptor.lastEventId, descriptor.revision, descriptor.value);
} else if (!item) {
item = this.cache.store(key, new mapitem_1.MapItem(descriptor), descriptor.last_event_id);
item = this.cache.store(key, new mapitem_1.MapItem(descriptor), descriptor.lastEventId);
if (added) {

@@ -641,3 +635,3 @@ this.emit('itemAdded', item, true);

return __awaiter(this, void 0, void 0, _regenerator2.default.mark(function _callee12() {
var _this5 = this;
var _this4 = this;

@@ -657,7 +651,7 @@ var uri, response, items, meta;

items = response.body.items.map(function (el) {
return _this5.cache.store(el.key, new mapitem_1.MapItem(el), el.last_event_id);
return _this4.cache.store(el.key, new mapitem_1.MapItem(el), el.last_event_id);
});
meta = response.body.meta;
return _context12.abrupt("return", new paginator_1.Paginator(items, function (pageToken) {
return _this5.queryItems({ pageToken: pageToken });
return _this4.queryItems({ pageToken: pageToken });
}, meta.previous_token, meta.next_token));

@@ -761,3 +755,3 @@

value: function forEach(handler) {
var _this6 = this;
var _this5 = this;

@@ -775,3 +769,3 @@ return new _promise2.default(function (resolve, reject) {

}
_this6.queryItems().then(processPage).catch(reject);
_this5.queryItems().then(processPage).catch(reject);
});

@@ -831,5 +825,5 @@ }

key: "_handleItemAdded",
value: function _handleItemAdded(key, uri, eventId, revision, value) {
value: function _handleItemAdded(key, url, eventId, revision, value) {
if (!this.cache.has(key) && !this.shouldIgnoreEvent(key, eventId)) {
var item = new mapitem_1.MapItem({ key: key, url: uri, last_event_id: eventId, revision: revision, data: value });
var item = new mapitem_1.MapItem({ key: key, url: url, last_event_id: eventId, revision: revision, data: value });
this.cache.store(key, item, eventId);

@@ -847,6 +841,6 @@ this.emit('itemAdded', item, false);

key: "_handleItemUpdated",
value: function _handleItemUpdated(key, uri, eventId, revision, value) {
value: function _handleItemUpdated(key, url, eventId, revision, value) {
var item = this.cache.get(key);
if (!item && !this.shouldIgnoreEvent(key, eventId)) {
item = new mapitem_1.MapItem({ key: key, url: uri, last_event_id: eventId, revision: revision, data: value });
item = new mapitem_1.MapItem({ key: key, url: url, last_event_id: eventId, revision: revision, data: value });
this.cache.store(key, item, eventId);

@@ -853,0 +847,0 @@ this.emit('itemUpdated', item, false);

@@ -14,6 +14,6 @@ /// <reference types="node" />

declare class SyncClient extends EventEmitter {
private services;
private entities;
private readonly services;
private readonly entities;
private fpaToken;
private serviceSid;
private localStorageId;
constructor(fpaToken: string, options?: any);

@@ -28,2 +28,3 @@ /**

readonly connectionState: SyncClient.ConnectionState;
private handleEmsResponse(response);
/**

@@ -34,3 +35,5 @@ * Returns promise which resolves when library is correctly initialized

private ensureReady();
private _get(baseUri, id);
private storeInSessionCache(type, id, value);
private readFromSessionCache(type, id);
private _get(baseUri, id, optimistic?);
private _createDocument(id, purpose?, data?);

@@ -78,5 +81,3 @@ private _getDocument(id);

*/
updateToken(fpaToken: any): Promise<void>;
private storeRoot(id, type, object);
private getRoot(id, type);
updateToken(fpaToken: string): Promise<void>;
}

@@ -83,0 +84,0 @@ declare module SyncClient {

@@ -11,2 +11,3 @@ "use strict";

const events_1 = require("events");
const xxhashjs_1 = require("xxhashjs");
const Twilsock = require("twilsock");

@@ -52,4 +53,3 @@ const twilio_transport_1 = require("twilio-transport");

mode: arg.mode,
optimistic: arg.optimistic
};
optimistic: !!arg.optimistic };
}

@@ -77,3 +77,2 @@ /**

}
this.serviceSid = null;
let productId = options.productId = options.productId || SYNC_PRODUCT_ID;

@@ -86,4 +85,5 @@ let twilsock = options.twilsockClient = options.twilsockClient || new Twilsock(fpaToken, options);

let network = new network_1.Network(productId, new clientInfo_1.ClientInfo(SDK_VERSION), config, transport);
this.localStorageId = null;
this.fpaToken = fpaToken;
emsClient.setToken(fpaToken).then(response => this.services.config.updateToken(response.token));
emsClient.setToken(fpaToken).then(response => this.handleEmsResponse(response));
twilsock.connect();

@@ -108,2 +108,14 @@ this.services = { config, twilsock, notifications, network, emsClient, router: null, subscriptions: null };

get connectionState() { return this.services.notifications.connectionState; }
handleEmsResponse(response) {
this.services.config.updateToken(response.token);
try {
let identity = response.identity;
let serviceSid = response.serviceSids['data_sync'];
this.localStorageId = xxhashjs_1.h64().update(`TW::${identity}::${serviceSid}`)
.digest().toString(16);
}
catch (e) {
logger_1.default.error('Failed to initialize persistent storage', e);
}
}
/**

@@ -123,3 +135,20 @@ * Returns promise which resolves when library is correctly initialized

}
_get(baseUri, id) {
storeInSessionCache(type, id, value) {
try {
let dataToStore = JSON.stringify(value);
sessionStorage.setItem(this.localStorageId + '::' + type + '::' + id, dataToStore);
}
catch (e) { }
}
readFromSessionCache(type, id) {
try {
let storedData = sessionStorage.getItem(this.localStorageId + '::' + type + '::' + id);
if (storedData) {
return JSON.parse(storedData);
}
}
catch (e) { }
return null;
}
_get(baseUri, id, optimistic = false) {
return __awaiter(this, void 0, void 0, function* () {

@@ -129,11 +158,13 @@ if (!id) {

}
const uri = new utils_1.UriBuilder(baseUri).arg('Deep', true).arg('Id', id).build();
let response = yield this.services.network.get(uri);
let objects = (response.body.documents || response.body.lists || response.body.maps || []);
let result = objects.length === 0 ? null : objects[0];
// Hacky optimization - here we learn the service sid
if (result && result.service_sid && !this.serviceSid) {
this.serviceSid = result.service_sid;
const uri = new utils_1.UriBuilder(baseUri).path(id).arg('Include', optimistic ? 'items' : undefined).build();
try {
let response = yield this.services.network.get(uri);
return response.body;
}
return { root: result, items: [] };
catch (err) {
if (err.status === 404) {
return null;
}
throw err;
}
});

@@ -146,7 +177,5 @@ }

_getDocument(id) {
let cachedRoot = this.getRoot(id, 'document');
if (cachedRoot) {
return Promise.resolve(cachedRoot);
}
return this._get(this.services.config.documentsUri, id).then(body => body ? body.root : null);
return __awaiter(this, void 0, void 0, function* () {
return this.readFromSessionCache(syncdocument_1.SyncDocument.type, id) || this._get(this.services.config.documentsUri, id);
});
}

@@ -158,42 +187,13 @@ _createList(id, purpose, context) {

_getList(id) {
let cachedRoot = this.getRoot(id, 'list');
if (cachedRoot) {
return Promise.resolve(cachedRoot);
}
return this._get(this.services.config.listsUri, id).then(body => body ? body.root : null);
return __awaiter(this, void 0, void 0, function* () {
return this.readFromSessionCache(synclist_1.SyncList.type, id) || this._get(this.services.config.listsUri, id);
});
}
_createMap(id, purpose, context) {
let payload = createPayload(id, purpose, context);
return this.services.network.post(this.services.config.mapsUri, payload)
.then(response => ({ root: response.body, items: [] }));
return this.services.network.post(this.services.config.mapsUri, payload).then(response => response.body);
}
_getMap(id, optimistic = false) {
return __awaiter(this, void 0, void 0, function* () {
if (!id) {
return null;
}
if (optimistic && this.serviceSid) {
// Hacky optimization - here we use service sid
try {
let url = new utils_1.UriBuilder(this.services.config.baseUri)
.path('v3')
.path('Services')
.path(this.serviceSid)
.path('Maps')
.path(id)
.path('Items')
.arg('Metadata', 'map')
.build();
let response = yield this.services.network.get(url);
return { root: response.body.map, items: response.body.items };
}
catch (e) {
return null;
}
}
let cachedRoot = this.getRoot(id, 'map');
if (cachedRoot) {
return { root: cachedRoot, items: [] };
}
return this._get(this.services.config.mapsUri, id);
return this.readFromSessionCache(syncmap_1.SyncMap.type, id) || this._get(this.services.config.mapsUri, id, optimistic);
});

@@ -228,3 +228,3 @@ }

.then(body => {
this.storeRoot(id, 'document', body);
this.storeInSessionCache(syncdocument_1.SyncDocument.type, id, body);
return new syncdocument_1.SyncDocument(this.services, body, sid => this.removeFromCache(sid));

@@ -246,26 +246,18 @@ })

let { id, purpose, context, mode, optimistic } = decompose(arg);
let cachedMap = this.getCached(id, 'map');
if (cachedMap) {
return cachedMap;
}
console.log('----------xxxx1');
let map = yield this._getMap(id, optimistic)
return this.getCached(id, 'map') || this._getMap(id, optimistic)
.then(body => {
console.log('----------xxxx1', body);
if (body.root) {
if (body) {
return body;
}
if (mode === 'open') {
throw new syncerror_1.default('Not found', 404);
else if (mode !== 'open') {
return this._createMap(id, purpose, context);
}
console.log('Creating');
return this._createMap(id, purpose, context);
throw new syncerror_1.default('Not found', 404);
})
.then(map => {
this.storeRoot(id, 'map', map.root);
return new syncmap_1.SyncMap(this.services, map.root, map.items, sid => this.removeFromCache(sid));
});
this.entities.store(map);
subscribe(map);
return map;
.then(body => {
this.storeInSessionCache(syncmap_1.SyncMap.type, id, body);
return new syncmap_1.SyncMap(this.services, body, sid => this.removeFromCache(sid));
})
.then(entity => this.entities.store(entity))
.then(subscribe);
});

@@ -294,3 +286,3 @@ }

.then(body => {
this.storeRoot(id, 'list', body);
this.storeInSessionCache(synclist_1.SyncList.type, id, body);
return new synclist_1.SyncList(this.services, body, sid => this.removeFromCache(sid));

@@ -322,34 +314,11 @@ })

return __awaiter(this, void 0, void 0, function* () {
let response = yield this.services.emsClient.setToken(fpaToken);
this.services.config.updateToken(response.token),
yield Promise.all([
this.services.notifications.updateToken(fpaToken),
this.services.twilsock.updateToken(fpaToken)
]);
this.fpaToken = fpaToken;
yield Promise.all([
this.services.config.updateToken(fpaToken),
this.services.notifications.updateToken(fpaToken),
this.services.twilsock.updateToken(fpaToken)
]);
});
}
storeRoot(id, type, object) {
try {
if (sessionStorage) {
let entryId = type + '::' + id;
sessionStorage.setItem(entryId, JSON.stringify(object));
}
}
catch (e) {
}
}
getRoot(id, type) {
try {
if (sessionStorage) {
let entryId = type + '::' + id;
let data = sessionStorage.getItem(entryId);
if (data) {
return JSON.parse(data);
}
}
}
catch (e) {
}
return null;
}
}

@@ -356,0 +325,0 @@ exports.SyncClient = SyncClient;

@@ -12,3 +12,2 @@ /**

readonly token: string;
readonly baseUri: string;
readonly subscriptionsUri: string;

@@ -15,0 +14,0 @@ readonly documentsUri: string;

@@ -19,3 +19,2 @@ "use strict";

this.settings = {
baseUri: baseUri,
subscriptionsUri: baseUri + SUBSCRIPTIONS_PATH,

@@ -28,3 +27,2 @@ documentsUri: baseUri + DOCUMENTS_PATH,

get token() { return this._token; }
get baseUri() { return this.settings.baseUri; }
get subscriptionsUri() { return this.settings.subscriptionsUri; }

@@ -31,0 +29,0 @@ get documentsUri() { return this.settings.documentsUri; }

@@ -17,3 +17,3 @@ export interface MapItemDescriptor {

declare class MapItem {
data: MapItemDescriptor;
private descriptor;
/**

@@ -27,3 +27,3 @@ * @private

*/
constructor(data: MapItemDescriptor);
constructor(descriptor: MapItemDescriptor);
readonly uri: string;

@@ -30,0 +30,0 @@ readonly revision: string;

@@ -19,14 +19,14 @@ "use strict";

*/
constructor(data) {
this.data = data;
constructor(descriptor) {
this.descriptor = descriptor;
}
get uri() { return this.data.url; }
get uri() { return this.descriptor.url; }
;
get revision() { return this.data.revision; }
get revision() { return this.descriptor.revision; }
;
get lastEventId() { return this.data.last_event_id; }
get lastEventId() { return this.descriptor.last_event_id; }
;
get key() { return this.data.key; }
get key() { return this.descriptor.key; }
;
get value() { return this.data.data; }
get value() { return this.descriptor.data; }
;

@@ -41,7 +41,5 @@ /**

update(eventId, revision, value) {
if (eventId > this.data.last_event_id) {
this.data.last_event_id = eventId;
this.data.revision = revision;
this.data.data = value;
}
this.descriptor.last_event_id = eventId;
this.descriptor.revision = revision;
this.descriptor.data = value;
return this;

@@ -48,0 +46,0 @@ }

@@ -140,3 +140,3 @@ "use strict";

logger_1.default.debug(`Failed an attempt to ${action} subscriptions (c:${correlationId}); retrying`, e);
this.backoff.backoff(e);
this.persist();
}

@@ -143,0 +143,0 @@ }

import { SyncEntity, EntityServices } from './entity';
import { MapItem as Item, MapItemDescriptor } from './mapitem';
import { MapItemDescriptor, MapItem as Item } from './mapitem';
import { Paginator } from './paginator';

@@ -14,2 +14,3 @@ import { Mutator } from './interfaces/mutator';

unique_name: string;
items?: MapItemDescriptor[];
}

@@ -33,11 +34,11 @@ /**

export declare class SyncMap extends SyncEntity {
private descriptor;
private actionQueue;
private cache;
private readonly descriptor;
private readonly actionQueue;
private readonly cache;
private readonly onRemoveMap;
private context;
private onRemoveMap;
/**
* @private
*/
constructor(services: MapServices, descriptor: MapDescriptor, items: MapItemDescriptor[], onRemoveMap: any);
constructor(services: MapServices, descriptor: MapDescriptor, onRemoveMap: any);
readonly uri: string;

@@ -51,5 +52,4 @@ readonly links: any;

readonly type: string;
private populateItems(items);
_get(key: any): Promise<Item>;
__set(location: any, param: any): any;
_get(key: string): Promise<Item>;
__set(location: string, param: any): any;
/**

@@ -164,3 +164,3 @@ * Update known existing element

*/
protected _handleItemAdded(key: string, uri: string, eventId: number, revision: string, value: Object): void;
protected _handleItemAdded(key: string, url: string, eventId: number, revision: string, value: Object): void;
/**

@@ -170,3 +170,3 @@ * Handle new value of entity, coming from server

*/
protected _handleItemUpdated(key: any, uri: any, eventId: any, revision: any, value: any): void;
protected _handleItemUpdated(key: string, url: string, eventId: number, revision: string, value: Object): void;
/**

@@ -173,0 +173,0 @@ * @private

@@ -37,5 +37,4 @@ "use strict";

*/
constructor(services, descriptor, items, onRemoveMap) {
constructor(services, descriptor, onRemoveMap) {
super(services);
console.log('Got descriptor', descriptor);
this.actionQueue = new retryingqueue_1.RetryingQueue();

@@ -45,3 +44,7 @@ this.cache = new cache_1.Cache();

this.onRemoveMap = onRemoveMap;
this.populateItems(items);
if (descriptor.items) {
descriptor.items.forEach(itemDescriptor => {
this.cache.store(itemDescriptor.key, new mapitem_1.MapItem(itemDescriptor), itemDescriptor.last_event_id);
});
}
}

@@ -60,5 +63,2 @@ get uri() { return this.descriptor.url; }

get type() { return 'map'; }
populateItems(items) {
items.forEach(item => this.cache.store(item.key, new mapitem_1.MapItem(item), item.last_event_id));
}
_get(key) {

@@ -203,7 +203,7 @@ return this.queryItems({ key: key }).then(result => {

item = yield this.cache.get(key);
if (item) {
item.update(descriptor.last_event_id, descriptor.revision, descriptor.data);
if (item && descriptor.lastEventId > item.lastEventId) {
item.update(descriptor.lastEventId, descriptor.revision, descriptor.value);
}
else if (!item) {
item = this.cache.store(key, new mapitem_1.MapItem(descriptor), descriptor.last_event_id);
item = this.cache.store(key, new mapitem_1.MapItem(descriptor), descriptor.lastEventId);
if (added) {

@@ -399,5 +399,5 @@ this.emit('itemAdded', item, true);

*/
_handleItemAdded(key, uri, eventId, revision, value) {
_handleItemAdded(key, url, eventId, revision, value) {
if (!this.cache.has(key) && !this.shouldIgnoreEvent(key, eventId)) {
let item = new mapitem_1.MapItem({ key, url: uri, last_event_id: eventId, revision, data: value });
let item = new mapitem_1.MapItem({ key, url, last_event_id: eventId, revision, data: value });
this.cache.store(key, item, eventId);

@@ -412,6 +412,6 @@ this.emit('itemAdded', item, false);

*/
_handleItemUpdated(key, uri, eventId, revision, value) {
_handleItemUpdated(key, url, eventId, revision, value) {
let item = this.cache.get(key);
if (!item && !this.shouldIgnoreEvent(key, eventId)) {
item = new mapitem_1.MapItem({ key, url: uri, last_event_id: eventId, revision, data: value });
item = new mapitem_1.MapItem({ key, url, last_event_id: eventId, revision, data: value });
this.cache.store(key, item, eventId);

@@ -418,0 +418,0 @@ this.emit('itemUpdated', item, false);

{
"name": "twilio-sync",
"version": "0.4.2-test.3",
"version": "0.5.0-dev.1",
"description": "Twilio Sync client library",

@@ -14,3 +14,3 @@ "main": "lib/index.js",

"dependencies": {
"babel-runtime": "^6.22.0",
"babel-runtime": "^6.23.0",
"karibu": "^1.0.1",

@@ -20,7 +20,8 @@ "loglevel": "^1.4.1",

"rfc6902": "^1.3.0",
"twilio-ems-client": "^0.1.5-dev.2",
"twilio-notifications": "^0.3.0-dev.1",
"twilio-ems-client": "^0.2.0",
"twilio-notifications": "^0.4.0",
"twilio-transport": "^0.1.1",
"twilsock": "^0.2.1",
"uuid": "^3.0.1"
"twilsock": "^0.3.0",
"uuid": "^3.0.1",
"xxhashjs": "^0.2.1"
},

@@ -31,16 +32,16 @@ "devDependencies": {

"@types/loglevel": "^1.4.29",
"@types/mocha": "^2.2.38",
"@types/node": "^7.0.4",
"@types/sinon": "^1.16.34",
"@types/mocha": "^2.2.39",
"@types/node": "^7.0.5",
"@types/sinon": "^1.16.35",
"@types/sinon-as-promised": "^4.0.5",
"@types/sinon-chai": "^2.7.27",
"async-test-tools": "^1.0.6",
"babel-cli": "^6.22.2",
"babel-cli": "^6.23.0",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-transform-object-assign": "^6.22.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-es2015": "^6.22.0",
"babelify": "^7.3.0",
"backoff": "^2.5.0",
"browserify": "^14.0.0",
"browserify": "^14.1.0",
"chai": "^3.5.0",

@@ -61,3 +62,3 @@ "chai-as-promised": "^6.0.0",

"gulp-tap": "^0.1.3",
"gulp-tslint": "^7.0.1",
"gulp-tslint": "^7.1.0",
"gulp-typescript": "^3.1.4",

@@ -69,3 +70,3 @@ "gulp-uglify": "^2.0.1",

"jsdoc": "^3.4.3",
"jsonwebtoken": "^7.2.1",
"jsonwebtoken": "^7.3.0",
"karma": "^1.4.1",

@@ -80,6 +81,6 @@ "karma-browserify": "^5.1.1",

"sinon-chai": "^2.8.0",
"ts-node": "^2.0.0",
"ts-node": "^2.1.0",
"tslint": "^4.4.2",
"twilio": "^3.3.0-edge",
"typescript": "^2.1.5",
"typescript": "^2.1.6",
"underscore": "^1.8.3",

@@ -86,0 +87,0 @@ "vinyl-buffer": "^1.0.0",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc