relution-sdk
Version:
Relution Software Development Kit for TypeScript and JavaScript
1,396 lines (1,379 loc) • 3.03 MB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Relution = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/*
* @file connector/connector.ts
* Relution SDK
*
* Created by Thomas Beckmann on 03.05.2016
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module connector
*/
/** */
"use strict";
var web = require('../web');
/**
* endpoint URL of connectors REST API set up by CLI project generation by default.
*
* @type {string}
*/
var connectorsUrl = 'api/v1/connectors';
/**
* provides per-user connection properties to be stored as part of the session,
* such as credentials for a given connection.
*
* <p>
* All parameters in properties are copied to the transient session store,
* overwriting any already existing values. To delete a previously stored
* parameter, provide an empty value explicitly.
* </p>
*
* @param name of connection.
* @param properties to store in session.
* @returns promise of async execution.
*/
function configureSession(name, properties) {
return web.post(connectorsUrl + '/' + name, properties);
}
exports.configureSession = configureSession;
/**
* executes a call on a connection.
*
* @param name of connection.
* @param call name.
* @param input data, i.e. an instance of a model or object compatible to the
* model in terms of attributes defined.
* @returns promise providing output/error.
*/
function runCall(name, call, input) {
return web.post(connectorsUrl + '/' + name + '/' + call, input);
}
exports.runCall = runCall;
},{"../web":41}],2:[function(require,module,exports){
/*
* @file connector/index.ts
* Relution SDK
*
* Created by Thomas Beckmann on 03.05.2016
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module connector
* @preferred
*/
/** */
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require('./connector'));
},{"./connector":1}],3:[function(require,module,exports){
(function (Buffer){
/*
* @file core/cipher.ts
* Relution SDK
*
* Created by Thomas Beckmann on 01.07.2016
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module core
*/
/** */
"use strict";
var crypto = require('crypto');
var Q = require('q');
var _ = require('lodash');
// key generation parameters
var pbkdf2SaltLen = 64;
var pbkdf2Iterations = 6911;
var pbkdf2KeyLen = 192 / 8;
var pbkdf2Digest = 'sha256';
// see https://tools.ietf.org/html/rfc5084
// console.log((<any>crypto).getCiphers());
var cipherAlgorithm = 'aes-192-gcm';
var cipherIvLen = 12;
// promised variants
var randomBytes = Q.denodeify(crypto.randomBytes);
var pbkdf2 = Q.denodeify(crypto.pbkdf2);
/**
* encrypts a JSON object using a user-provided password.
*
* This method is suitable for human-entered passwords and not appropriate for machine generated
* passwords. Make sure to read regarding pbkdf2.
*
* @param password of a human.
* @param json to encode.
* @return encoded json data.
*
* @internal Not part of public API, exported for library use only.
*/
function encryptJson(password, json) {
return Q.all([
randomBytes(pbkdf2SaltLen),
randomBytes(cipherIvLen)
]).spread(function (salt, iv) {
return pbkdf2(password, salt, pbkdf2Iterations, pbkdf2KeyLen, pbkdf2Digest).then(function (key) {
var cipher = crypto.createCipheriv(cipherAlgorithm, key, iv);
var value = cipher.update(JSON.stringify(json), 'utf8', 'base64');
value += cipher.final('base64');
var data = {
salt: salt.toString('base64'),
iv: iv.toString('base64'),
value: value
};
var tag = cipher.getAuthTag();
if (tag) {
data.tag = tag.toString('base64');
}
return data;
});
});
}
exports.encryptJson = encryptJson;
/**
* decrypts some encoded json data.
*
* @param password of a human.
* @param data encoded json data.
* @return json to decoded.
*
* @internal Not part of public API, exported for library use only.
*/
function decryptJson(password, data) {
var salt = new Buffer(data.salt, 'base64');
return pbkdf2(password, salt, pbkdf2Iterations, pbkdf2KeyLen, pbkdf2Digest).then(function (key) {
var iv = new Buffer(data.iv, 'base64');
var decipher = crypto.createDecipheriv(cipherAlgorithm, key, iv);
var tag = data.tag;
if (tag) {
decipher.setAuthTag(new Buffer(tag, 'base64'));
}
var value = decipher.update(data.value, 'base64', 'utf8');
value += decipher.final('utf8');
return value;
}).then(JSON.parse);
}
exports.decryptJson = decryptJson;
/**
* computes a hash of some JSON object synchronously.
*
* Prefer the async variant if possible.
*
* @param data to hash.
* @param algorithm of choice.
* @return hash value.
*
* @internal Not part of public API, exported for library use only.
*/
function hashJsonSync(data, algorithm) {
var hash = crypto.createHash(algorithm);
(function feed(val) {
var keys = _.keys(val).sort();
if (keys.length) {
hash.update(JSON.stringify(keys), 'utf8');
_.forEach(keys, function (key) {
var value = val[key];
if (!_.isUndefined(value)) {
if (!_.isObject(value)) {
hash.update(JSON.stringify(value), 'utf8');
}
else {
feed(value);
}
}
});
}
})(JSON.parse(JSON.stringify(data)));
return hash.digest();
}
exports.hashJsonSync = hashJsonSync;
/**
* computes a hash of some JSON object synchronously.
*
* @param data to hash.
* @param algorithm of choice.
* @return hash value.
*
* @internal Not part of public API, exported for library use only.
*/
function hashJson(data, algorithm) {
return Q.Promise(function (resolve, reject) {
try {
resolve(hashJsonSync(data, algorithm));
}
catch (error) {
reject(error);
}
});
}
exports.hashJson = hashJson;
}).call(this,require("buffer").Buffer)
},{"buffer":109,"crypto":120,"lodash":213,"q":250}],4:[function(require,module,exports){
(function (process,global){
"use strict";
/*
* @file core/device.ts
* Relution SDK
*
* Created by Thomas Beckmann on 07.07.2016
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module core
*/
/** */
var Q = require('q');
var diag = require('./diag');
/**
* resolves to Information object as soon as the device is ready.
*
* @internal SDK client code is required to use init() to obtain the Information.
*/
exports.ready = (function () {
// must be extracted from global scope object as otherwise we get ReferenceError in node.js
var document = global['document'];
var window = global['window'];
var resolveDocument;
var callback = function () {
document.removeEventListener('load', callback);
document.removeEventListener('DOMContentLoaded', callback);
return resolveDocument(document);
};
return Q.Promise(function (resolve, reject) {
// resolves to document once the DOM is loaded
try {
if (!document || document.readyState === 'complete') {
resolve(document);
return;
}
resolveDocument = resolve;
document.addEventListener('DOMContentLoaded', callback, false);
document.addEventListener('load', callback, false); // fallback
}
catch (error) {
reject(error);
}
}).then(function () {
// resolves to window once the device is ready
return Q.Promise(function (resolve, reject) {
try {
if (!window || !('cordova' in window ||
'PhoneGap' in window || 'phonegap' in window ||
'forge' in window)) {
resolve(window);
return;
}
// see https://cordova.apache.org/docs/en/latest/cordova/events/events.html#deviceready
document.addEventListener('deviceready', function () {
document.removeEventListener('deviceready', callback);
resolve(window);
}, false);
}
catch (error) {
reject(error);
}
});
}).then(function () {
var navigator = window && window.navigator;
var userAgent = navigator && navigator.userAgent;
var appVersion = navigator && navigator.appVersion;
var device = window && window['device'];
var platformName = device && device.platform || userAgent || process.platform;
var platformVersion = device && device.version || process.version || appVersion;
var platformId;
if (/Android/i.test(platformName)) {
platformId = 'android';
}
else if (/iOS|iPhone|iPad|iPod/i.test(platformName)) {
platformId = 'ios';
}
else if (/Windows Phone/i.test(platformName) || device &&
/WinCE|Win32NT/i.test(platformName)) {
// see https://github.com/apache/cordova-plugin-device regarding Windows Phone 7/8 Quirks
diag.debug.assert(function () { return !/WinCE/i.test(platformName); }, 'WindowsCE devices like Windows Phone 7 and below are not officially supported!');
platformId = 'windowsphone';
}
else if (/BlackBerry/i.test(platformName)) {
platformId = 'blackberry';
}
else if (navigator || process['browser']) {
platformId = 'browser';
}
else if (process && require) {
platformId = 'node';
}
else {
diag.debug.assert(!!platformId, 'unknown platform: ' + platformName);
}
return {
uuid: device && device.uuid,
serial: device && device.serial,
language: navigator && (navigator.language || navigator['userLanguage']),
platform: {
id: platformId,
name: platformName,
version: platformVersion
},
device: device
};
});
})();
// output diagnostics to the console
exports.ready.done(function (info) {
diag.debug.debug('device information: ', info);
});
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./diag":5,"_process":242,"q":250}],5:[function(require,module,exports){
(function (process){
/*
* @file core/diag.ts
* Relution SDK
*
* Created by Pascal Brewing, Thomas Beckmann
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module core
*/
/** */
"use strict";
var _ = require('lodash');
var assert = require('assert');
/**
* console featuring coloring, fontSize and enabled state.
*/
var Diagnostics = (function () {
function Diagnostics(enabled, fontSize) {
if (enabled === void 0) { enabled = false; }
if (fontSize === void 0) { fontSize = '12px'; }
this.enabled_ = enabled;
this.fontSize_ = fontSize;
this.reset();
}
Diagnostics.STUB = function () {
// empty by intention
};
Diagnostics.prototype.reset = function () {
// uses bound functions to avoid browsers outputting incorrect line numbers
if (this.enabled_) {
if (!process || 'browser' in process) {
// browser
this.log = _.bind(console.log, console, '%c%s');
this.trace = _.bind(console.trace, console, '%c%s', "color: #378c13; font-size: " + this.fontSize_ + ";font-weight: normal;");
this.debug = _.bind(console.info, console, '%c%s', "color: #008c13; font-size: " + this.fontSize_ + ";font-weight: normal;");
this.info = _.bind(console.info, console, '%c%s', "color: #00f; font-size: " + this.fontSize_ + ";font-weight: normal;");
this.warn = _.bind(console.warn, console, '%c%s', "color: #e69138; font-size: " + this.fontSize_ + ";font-weight: normal;");
this.error = _.bind(console.error, console, '%c%s', "color: #f00; font-size: " + this.fontSize_ + ";font-weight: normal;");
}
else {
// node
this.log = _.bind(console.log, console, '\u001b[15m LOG\u001b[00m %s');
this.trace = _.bind(console.trace, console, '\u001b[34mTRACE\u001b[00m %s');
this.debug = _.bind(console.info, console, '\u001b[35mDEBUG\u001b[00m %s');
this.info = _.bind(console.info, console, '\u001b[32m INFO\u001b[00m %s');
this.warn = _.bind(console.warn, console, '\u001b[36m WARN\u001b[00m %s');
this.error = _.bind(console.error, console, '\u001b[31mERROR\u001b[00m %s');
}
}
else {
this.log = Diagnostics.STUB;
this.trace = Diagnostics.STUB;
this.debug = Diagnostics.STUB;
this.info = Diagnostics.STUB;
this.warn = Diagnostics.STUB;
this.error = Diagnostics.STUB;
}
this.warning = this.warn; // alias only
};
Object.defineProperty(Diagnostics.prototype, "enabled", {
get: function () {
return this.enabled_;
},
set: function (enabled) {
if (this.enabled_ !== enabled) {
this.enabled_ = enabled;
this.reset();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Diagnostics.prototype, "fontSize", {
get: function () {
return this.fontSize_;
},
set: function (fontSize) {
if (this.fontSize_ !== fontSize) {
this.fontSize_ = fontSize;
this.reset();
}
},
enumerable: true,
configurable: true
});
/**
* uses toSource() if available, falling back to toString() otherwise.
*
* @param func to generate source of.
* @return {string} of func.
*/
Diagnostics.toSource = function (func) {
var anything = func; // must not type-check as name and toSource() might not exist
return anything.name ||
(typeof anything.toSource === 'function' ? anything.toSource() : func.toString());
};
/**
* evaluates given check expression as a strong invariant never ever violated.
*
* <p>
* Use assert to ensure an assumption at runtime. When running with assertions enabled, the
* check expression is evaluated immediately. A check expression evaluating to false signals a
* violation of invariant that should never happen. If it does, a hard error is output
* unconditionally to the console and an AssertionError is thrown.
* </p>
* <p>
* Do not use assertions as a means of ordinary error checking. Here are some valid examples of
* assertions:
* <pre>
* assert(() => Date.now() > 0, 'current time millis can not be before 1970 start of time!');
* assert(() => total_price >= item_price,
* 'total is sum of individual prices and thus can not be less than each one!');
* assert(() => num*num >= 0, 'squared num is less than zero!');
* </pre>
* </p>
*
* @param check expression validating an assumption of the calling code, typically an
* arrow-function expression.
* @param message optional explanation of disaster.
*/
Diagnostics.prototype.assert = function (check, message) {
var debugMode = this.enabled;
if (exports.assertions === undefined ? debugMode : exports.assertions) {
try {
if (_.isFunction(check)) {
assert(check(), message || Diagnostics.toSource(check));
}
else {
assert(check, message);
}
}
catch (error) {
if (debugMode) {
this.error('Assertion failed: ' + error.message, error);
debugger; // so you can inspect what causes the problem
}
else {
console.error('Assertion failed: ' + error.message, error);
}
throw error;
}
}
};
/**
* used in catch-blocks or Promise rejection callbacks to ensure the caught value is an Error.
*
* @param error to check.
* @param message of disaster.
* @return {any} value evaluating to true stating error is an instance of Error.
*/
Diagnostics.prototype.assertIsError = function (error, message) {
this.assert(function () { return _.isError(error); }, message);
return error;
};
return Diagnostics;
}());
exports.Diagnostics = Diagnostics;
exports.debug = new Diagnostics(true);
}).call(this,require('_process'))
},{"_process":242,"assert":68,"lodash":213}],6:[function(require,module,exports){
/*
* @file core/domain.ts
* Relution SDK
*
* Created by Thomas Beckmann on 28.04.2016
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module core
*/
/** */
"use strict";
/**
* turns the object deeply immutable.
*
* @param self to freeze.
* @return {T} self for convenience.
*
* @internal for library use only.
*/
function freeze(self) {
var anything = self;
if (anything.aclEntries) {
anything.aclEntries = Object.freeze(anything.aclEntries);
}
if (anything.createdDate) {
anything.createdDate = Object.freeze(new Date(+anything.createdDate));
}
if (anything.modifiedDate) {
anything.modifiedDate = Object.freeze(new Date(+anything.modifiedDate));
}
return Object.freeze(anything);
}
exports.freeze = freeze;
/**
* extracts the uuid of a Referenceable.
*
* @param referenceable or string uuid.
* @return {string} uuid of referenceable.
*/
function uuidOf(referenceable) {
if (_.isString(referenceable)) {
return referenceable;
}
else if (referenceable) {
return referenceable.uuid;
}
}
exports.uuidOf = uuidOf;
},{}],7:[function(require,module,exports){
/*
* @file core/index.ts
* Relution SDK
*
* Created by Thomas Beckmann on 28.04.2016
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module core
* @preferred
*/
/** */
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require('./diag'));
__export(require('./init'));
__export(require('./device'));
__export(require('./domain'));
},{"./device":4,"./diag":5,"./domain":6,"./init":8}],8:[function(require,module,exports){
(function (process){
/*
* @file core/init.ts
* Relution SDK
*
* Created by Thomas Beckmann on 28.04.2016
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module core
*/
/** */
"use strict";
var _ = require('lodash');
var Q = require('q');
var url = require('url');
var diag = require('./diag');
var device = require('./device');
// workaround Q promises being inherently incompatible with zone.js used by angular2
Q.nextTick = (function detectNextTick() {
// requires use of Q's nextTick(cb)
Q.stopUnhandledRejectionTracking();
// Q's nextTick(cb) is not compatible with thread-locals,
// returned function must not be bound as zone.js reassigns global variables
if (process && !('browser' in process) && process.nextTick) {
return function (cb) { return process.nextTick(cb); };
}
else if (typeof 'setImmediate' === 'function') {
return function (cb) { return setImmediate(cb); };
}
else {
return function (cb) { return setTimeout(cb, 0); };
}
})();
// initialize to go in sync with init() call
Q.longStackSupport = diag.debug.enabled;
/**
* creates a deeply independent copy of some [[ServerInitOptions]].
*
* @param serverInitOptions to clone.
* @return {ServerInitOptions} cloned object.
*/
function cloneServerInitOptions(serverInitOptions) {
var result = {
serverUrl: serverInitOptions.serverUrl,
application: serverInitOptions.application,
clientApp: serverInitOptions.clientApp,
tenantOrga: serverInitOptions.tenantOrga,
logonCallback: serverInitOptions.logonCallback,
};
if (result.serverUrl && result.serverUrl[result.serverUrl.length - 1] !== '/') {
result.serverUrl += '/';
}
if (serverInitOptions.clientCertificate) {
result.clientCertificate = _.clone(serverInitOptions.clientCertificate);
}
if (serverInitOptions.agentOptions) {
result.agentOptions = _.clone(serverInitOptions.agentOptions);
}
return result;
}
exports.cloneServerInitOptions = cloneServerInitOptions;
/**
* copy of options the SDK was initialized with using [[init]] function serving as defaults.
*
* @internal for SDK internal use only!
*/
exports.initOptions = {};
/**
* (re)initializes the SDK providing global configuration parameters.
*
* @param options of configuration, often these are hardcoded values of the mobile client app.
* @return promise resolving to Information object as soon as the device is ready.
*/
function init(options) {
if (options === void 0) { options = {}; }
if ('debug' in options) {
diag.debug.enabled = options.debug;
Q.longStackSupport = options.debug;
}
if ('serverUrl' in options) {
var myURL = url.parse(options.serverUrl);
if (!myURL.protocol && !myURL.host) {
return Q.reject(new Error(options.serverUrl + " is not an accepted Url, please add a Host and a Protocol."));
}
}
_.assignWith(exports.initOptions, cloneServerInitOptions(options), function (left, right) { return _.isUndefined(right) ? left : right; });
if ('push' in options) {
exports.initOptions.push = _.cloneDeep(options.push);
}
return device.ready;
}
exports.init = init;
}).call(this,require('_process'))
},{"./device":4,"./diag":5,"_process":242,"lodash":213,"q":250,"url":339}],9:[function(require,module,exports){
/*
* @file core/objectid.ts
* Relution SDK
*
* Created by Thomas Beckmann on 04.07.2016
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module core
*/
/** */
"use strict";
var machineId = parseInt('' + (Math.random() * Math.pow(16, 6)));
var processId = parseInt('' + (Math.random() * Math.pow(16, 4)));
var counter = parseInt('' + (Math.random() * Math.pow(16, 6)));
function hexString(len, num) {
var str = num.toString(16);
while (str.length < len) {
str = '0' + str;
}
return str.substr(0, len);
}
// random-based impl of Mongo ObjectID
function makeObjectID() {
return hexString(8, Date.now() / 1000) +
hexString(6, machineId) +
hexString(4, processId) +
hexString(6, counter++); // a 3-byte counter, starting with a random value.
}
exports.makeObjectID = makeObjectID;
},{}],10:[function(require,module,exports){
/*
* @file index.lazy.ts
* Relution SDK
*
* Created by Thomas Beckmann on 22.07.2016
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module Relution
*/
/** */
"use strict";
var core = require('./core');
/**
* lazy loads modules at runtime.
*
* An instance of Relution is set as prototype on the module exports. When a get property accessor
* of an exposed member is read, a require statement is executed loading the actual implementation
* code and the property is redefined to the resultant value.
*
* For supporting diagnostics, the core module is an exception and must be loaded eagerly.
*/
var Relution = (function () {
function Relution() {
// aliases
this.init = core.init;
this.debug = core.debug;
// core module
this.core = core;
}
Relution.resetProperty = function (property, value) {
Object.defineProperty(exports, property, {
value: value
});
return value;
};
;
Object.defineProperty(Relution.prototype, "version", {
// version
get: function () {
core.debug.debug('lazy loading Relution.version...');
var pkgjson = require('../package.json');
return Relution.resetProperty('version', pkgjson.version);
},
enumerable: true,
configurable: true
});
;
Object.defineProperty(Relution.prototype, "model", {
// model module
get: function () {
core.debug.debug('lazy loading Relution.model...');
return Relution.resetProperty('model', require('./model'));
},
enumerable: true,
configurable: true
});
Object.defineProperty(Relution.prototype, "query", {
// query module
get: function () {
core.debug.debug('lazy loading Relution.query...');
return Relution.resetProperty('query', require('./query'));
},
enumerable: true,
configurable: true
});
Object.defineProperty(Relution.prototype, "security", {
// security module
get: function () {
core.debug.debug('lazy loading Relution.security...');
return Relution.resetProperty('security', require('./security'));
},
enumerable: true,
configurable: true
});
Object.defineProperty(Relution.prototype, "web", {
// web module
get: function () {
core.debug.debug('lazy loading Relution.web...');
return Relution.resetProperty('web', require('./web'));
},
enumerable: true,
configurable: true
});
Object.defineProperty(Relution.prototype, "push", {
// push module
get: function () {
core.debug.debug('lazy loading Relution.push...');
return Relution.resetProperty('push', require('./push'));
},
enumerable: true,
configurable: true
});
Object.defineProperty(Relution.prototype, "connector", {
// connector module
get: function () {
core.debug.debug('lazy loading Relution.connector ...');
return Relution.resetProperty('connector', require('./connector'));
},
enumerable: true,
configurable: true
});
Object.defineProperty(Relution.prototype, "livedata", {
// livedata module
get: function () {
core.debug.debug('lazy loading Relution.livedata ...');
return Relution.resetProperty('livedata', require('./livedata'));
},
enumerable: true,
configurable: true
});
return Relution;
}());
;
Object.setPrototypeOf(exports, new Relution());
},{"../package.json":348,"./connector":2,"./core":7,"./livedata":20,"./model":24,"./push":26,"./query":35,"./security":37,"./web":41}],11:[function(require,module,exports){
/*
* @file livedata/Collection.ts
* Relution SDK
*
* Created by M-Way on 27.06.2016
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module livedata
*/
/** */
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Backbone = require('backbone');
var _ = require('lodash');
var url = require('url');
var diag = require('../core/diag');
var Model_1 = require('./Model');
var Q = require('q');
var rest_1 = require('./rest');
/**
* tests whether a given object is a Collection.
*
* @param {object} object to check.
* @return {boolean} whether object is a Collection.
*/
function isCollection(object) {
if (!object || typeof object !== 'object') {
return false;
}
else if ('isCollection' in object) {
diag.debug.assert(function () { return object.isCollection === Collection.prototype.isPrototypeOf(object); });
return object.isCollection;
}
else {
return Collection.prototype.isPrototypeOf(object);
}
}
exports.isCollection = isCollection;
/**
* extension of a backbone.js Collection.
*
* The Relution.livedata.Collection can be used like a Backbone Collection,
* but there are some enhancements to fetch, save and delete the
* contained models from or to other "data stores".
*
* see WebSqlStore or SyncStore for examples
*/
var Collection = (function (_super) {
__extends(Collection, _super);
function Collection(models, options) {
_super.call(this, models, options);
if (this.url && this.url.charAt(this.url.length - 1) !== '/') {
this.url += '/';
}
this.init(models, options);
}
/**
* sets up prototype properties when defining a Collection subclass.
*
* @param {CollectionProps} properties of prototype to set.
*/
Collection.defaults = function (properties) {
return _super['extend'].call(this, properties);
};
Collection.prototype.init = function (models, options) {
options = options || {};
this.store = options.store || this.store || (this.model ? this.model.prototype.store : null);
this.entity = options.entity || this.entity || (this.model ? this.model.prototype.entity : null);
this.options = options.options || this.options;
this.entity = this.entity || this._entityFromUrl(this.getUrl());
this._updateUrl();
if (this.store && _.isFunction(this.store.initCollection)) {
this.store.initCollection(this, options);
}
};
Collection.prototype.ajax = function (options) {
return rest_1.ajax.apply(this, arguments);
};
Collection.prototype.sync = function (method, model, options) {
return rest_1.sync.apply(this, arguments);
};
Collection.prototype._entityFromUrl = function (urlStr) {
if (urlStr) {
var urlObj = url.parse(urlStr);
// extract last path part as entity name
var parts = urlObj.pathname.match(/([^\/]+)\/?$/);
if (parts && parts.length > 1) {
return parts[-1];
}
}
};
Collection.prototype.destroy = function (options) {
options = options || {};
var success = options.success;
if (this.length > 0) {
options.success = function () {
if (this.length === 0 && success) {
success();
}
};
var model;
while ((model = this.first())) {
this.sync('delete', model, options);
this.remove(model);
}
}
else if (success) {
success();
}
};
/**
* save all containing models
*/
Collection.prototype.save = function () {
this.each(function (model) {
model.save();
});
};
Collection.prototype.applyFilter = function (callback) {
this.trigger('filter', this.filter(callback));
};
Collection.prototype.getUrlParams = function (url) {
url = url || this.getUrl();
var m = url.match(/\?([^#]*)/);
var params = {};
if (m && m.length > 1) {
_.each(m[1].split('&'), function (p) {
var a = p.split('=');
params[a[0]] = a[1];
});
}
return params;
};
Collection.prototype.getUrl = function () {
return (_.isFunction(this.url) ? this.url() : this.url) || '';
};
Collection.prototype.getUrlRoot = function () {
var url = this.getUrl();
return url.indexOf('?') >= 0 ? url.substr(0, url.indexOf('?')) : url;
};
Collection.prototype._updateUrl = function () {
if (this.options) {
var params = this.getUrlParams();
this.url = this.getUrlRoot();
if (this.options.query) {
params.query = encodeURIComponent(JSON.stringify(this.options.query));
}
if (this.options.fields) {
params.fields = encodeURIComponent(JSON.stringify(this.options.fields));
}
if (this.options.sort) {
params.sort = encodeURIComponent(JSON.stringify(this.options.sort));
}
if (!_.isEmpty(params)) {
this.url += '?';
var a = [];
for (var k in params) {
a.push(k + (params[k] ? '=' + params[k] : ''));
}
this.url += a.join('&');
}
}
};
/**
* reads an additional page of data into this collection.
*
* A fetch() must have been performed loading the initial set of data. This method is intended for infinite scrolling
* implementation.
*
* When async processing is done, a more attribute is set on the options object in case additional data might be
* available which can be loaded by calling this method again. Likewise an end attribute is set if the data is
* fully loaded.
*
* @param {object} options such as pageSize to retrieve.
* @return {Promise} promise of the load operation.
*
* @see SyncContext#fetchMore()
*/
Collection.prototype.fetchMore = function (options) {
if (!this.syncContext) {
return Q.reject(new Error('no context'));
}
return this.syncContext.fetchMore(this, options);
};
/**
* reads the next page of data into this collection.
*
* A fetch() must have been performed loading the initial set of data. This method is intended for paging
* implementation.
*
* When async processing is done, a next/prev attribute is set on the options object in case additional pages might be
* available which can be loaded by calling the corresponding method.
*
* @param {object} options such as pageSize to retrieve.
* @return {Promise} promise of the load operation.
*
* @see SyncContext#fetchNext()
*/
Collection.prototype.fetchNext = function (options) {
if (!this.syncContext) {
return Q.reject(new Error('no context'));
}
return this.syncContext.fetchNext(this, options);
};
/**
* reads the previous page of data into this collection.
*
* A fetch() must have been performed loading the initial set of data. This method is intended for paging
* implementation.
*
* When async processing is done, a next/prev attribute is set on the options object in case additional pages might be
* available which can be loaded by calling the corresponding method.
*
* @param {object} options such as pageSize to retrieve.
* @return {Promise} promise of the load operation.
*
* @see SyncContext#fetchPrev()
*/
Collection.prototype.fetchPrev = function (options) {
if (!this.syncContext) {
return Q.reject(new Error('no context'));
}
return this.syncContext.fetchPrev(this, options);
};
return Collection;
}(Backbone.Collection));
exports.Collection = Collection;
// mixins
var collection = _.extend(Collection.prototype, {
_type: 'Relution.livedata.Collection',
isModel: false,
isCollection: true,
isStore: false,
// default model type unless overwritten
model: Model_1.Model
});
diag.debug.assert(function () { return isCollection(Object.create(collection)); });
},{"../core/diag":5,"./Model":14,"./rest":21,"backbone":72,"lodash":213,"q":250,"url":339}],12:[function(require,module,exports){
/*
* @file livedata/LiveDataMessage.ts
* Relution SDK
*
* Created by Thomas Beckmann on 07.12.2015
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module livedata
*/
/** */
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var _ = require('lodash');
var Model_1 = require('./Model');
var diag = require('../core/diag');
/**
* message packed into a Model.
*
* @module Relution.livedata.LiveDataMessage
*
* @type {*}
*/
var LiveDataMessageModel = (function (_super) {
__extends(LiveDataMessageModel, _super);
function LiveDataMessageModel() {
_super.apply(this, arguments);
}
return LiveDataMessageModel;
}(Model_1.Model));
exports.LiveDataMessageModel = LiveDataMessageModel;
// mixins
var msgmodel = _.extend(LiveDataMessageModel.prototype, {
_type: 'Relution.livedata.LiveDataMessageModel',
entity: '__msg__',
idAttribute: '_id'
});
diag.debug.assert(function () { return LiveDataMessageModel.prototype.isPrototypeOf(Object.create(msgmodel)); });
diag.debug.assert(function () { return new LiveDataMessageModel({ _id: 'check' }).id === 'check'; });
},{"../core/diag":5,"./Model":14,"lodash":213}],13:[function(require,module,exports){
/*
* @file livedata/LiveDataTimestamp.ts
* Relution SDK
*
* Created by Thomas Beckmann on 07.12.2015
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module livedata
*/
/** */
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var _ = require('lodash');
var Model_1 = require('./Model');
var diag = require('../core/diag');
/**
* timestamp packed into a Model.
*
* @module Relution.livedata.LiveDataTimestamp
*
* @type {*}
*/
var LiveDataTimestampModel = (function (_super) {
__extends(LiveDataTimestampModel, _super);
function LiveDataTimestampModel() {
_super.apply(this, arguments);
}
return LiveDataTimestampModel;
}(Model_1.Model));
exports.LiveDataTimestampModel = LiveDataTimestampModel;
// mixins
var timestampmodel = _.extend(LiveDataTimestampModel.prototype, {
_type: 'Relution.livedata.LiveDataTimestampModel',
entity: '__timestamp__',
idAttribute: 'channel'
});
diag.debug.assert(function () { return LiveDataTimestampModel.prototype.isPrototypeOf(Object.create(timestampmodel)); });
diag.debug.assert(function () { return new LiveDataTimestampModel({ channel: 'check' }).id === 'check'; });
},{"../core/diag":5,"./Model":14,"lodash":213}],14:[function(require,module,exports){
/*
* @file livedata/Model.ts
* Relution SDK
*
* Created by M-Way on 27.06.2016
* Copyright 2016 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module livedata
*/
/** */
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Backbone = require('backbone');
var _ = require('lodash');
var diag = require('../core/diag');
var rest_1 = require('./rest');
/**
* tests whether a given object is a Model.
*
* @param {object} object to check.
* @return {boolean} whether object is a Model.
*/
function isModel(object) {
if (!object || typeof object !== 'object') {
return false;
}
else if ('isModel' in object) {
diag.debug.assert(function () { return object.isModel === Model.prototype.isPrototypeOf(object); });
return object.isModel;
}
else {
return Model.prototype.isPrototypeOf(object);
}
}
exports.isModel = isModel;
/**
* extension of a backbone.js Model.
*/
var Model /*<AttributesType extends Object>*/ = (function (_super) {
__extends(Model /*<AttributesType extends Object>*/, _super);
function Model /*<AttributesType extends Object>*/(attributes, options) {
_super.call(this, attributes, options);
this.changedSinceSync = {};
if (this.urlRoot && typeof this.urlRoot === 'string') {
if (this.urlRoot.charAt(this.urlRoot.length - 1) !== '/') {
this.urlRoot += '/';
}
}
this.init(attributes, options);
}
/**
* sets up prototype properties when defining a Model subclass.
*
* @param {ModelProps} properties of prototype to set.
*/
Model /*<AttributesType extends Object>*/.defaults = function (properties) {
return _super['extend'].call(this, properties);
};
Model /*<AttributesType extends Object>*/.prototype.init = function (attributes, options) {
options = options || {};
this.collection = options.collection || this.collection;
this.idAttribute = options.idAttribute || this.idAttribute;
this.store = this.store || (this.collection ? this.collection.store : null) || options.store;
if (this.store && _.isFunction(this.store.initModel)) {
this.store.initModel(this, options);
}
this.entity = this.entity || (this.collection ? this.collection.entity : null) || options.entity;
this.credentials = this.credentials || (this.collection ? this.collection.credentials : null) || options.credentials;
this.on('change', this.onChange, this);
this.on('sync', this.onSync, this);
};
Model /*<AttributesType extends Object>*/.prototype.ajax = function (options) {
return rest_1.