code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
var isArray = Array.isArray; var isPathValue = require("./is-path-value"); var isJsonGraphEnvelope = require("./is-json-graph-envelope"); var isJsonEnvelope = require("./is-json-envelope"); var pathSyntax = require("falcor-path-syntax"); /** * * @param {Object} allowedInput - allowedInput is a map of input styles * that are allowed * @private */ module.exports = function validateInput(args, allowedInput, method) { for (var i = 0, len = args.length; i < len; ++i) { var arg = args[i]; var valid = false; // Path if (isArray(arg) && allowedInput.path) { valid = true; } // Path Syntax else if (typeof arg === "string" && allowedInput.pathSyntax) { valid = true; } // Path Value else if (isPathValue(arg) && allowedInput.pathValue) { arg.path = pathSyntax.fromPath(arg.path); valid = true; } // jsonGraph {jsonGraph: { ... }, paths: [ ... ]} else if (isJsonGraphEnvelope(arg) && allowedInput.jsonGraph) { valid = true; } // json env {json: {...}} else if (isJsonEnvelope(arg) && allowedInput.json) { valid = true; } // selector functions else if (typeof arg === "function" && i + 1 === len && allowedInput.selector) { valid = true; } if (!valid) { return new Error("Unrecognized argument " + (typeof arg) + " [" + String(arg) + "] " + "to Model#" + method + ""); } } return true; };
michaelbpaulson/falcor-1
lib/support/validate-input.js
JavaScript
apache-2.0
1,615
export type from 'test';
wcjohnson/babylon-lightscript
test/fixtures/experimental/export-extensions/default-type-without-flow/actual.js
JavaScript
mit
25
/** * Secure Hash Algorithm with a 1024-bit block size implementation. * * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For * SHA-256 (block size 512 bits), see sha256.js. * * See FIPS 180-4 for details. * * @author Dave Longley * * Copyright (c) 2014-2015 Digital Bazaar, Inc. */ (function() { /* ########## Begin module implementation ########## */ function initModule(forge) { var sha512 = forge.sha512 = forge.sha512 || {}; forge.md = forge.md || {}; forge.md.algorithms = forge.md.algorithms || {}; // SHA-512 forge.md.sha512 = forge.md.algorithms.sha512 = sha512; // SHA-384 var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {}; sha384.create = function() { return sha512.create('SHA-384'); }; forge.md.sha384 = forge.md.algorithms.sha384 = sha384; // SHA-512/256 forge.sha512.sha256 = forge.sha512.sha256 || { create: function() { return sha512.create('SHA-512/256'); } }; forge.md['sha512/256'] = forge.md.algorithms['sha512/256'] = forge.sha512.sha256; // SHA-512/224 forge.sha512.sha224 = forge.sha512.sha224 || { create: function() { return sha512.create('SHA-512/224'); } }; forge.md['sha512/224'] = forge.md.algorithms['sha512/224'] = forge.sha512.sha224; /** * Creates a SHA-2 message digest object. * * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224, * SHA-512/256). * * @return a message digest object. */ sha512.create = function(algorithm) { // do initialization as necessary if(!_initialized) { _init(); } if(typeof algorithm === 'undefined') { algorithm = 'SHA-512'; } if(!(algorithm in _states)) { throw new Error('Invalid SHA-512 algorithm: ' + algorithm); } // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints) var _state = _states[algorithm]; var _h = null; // input buffer var _input = forge.util.createBuffer(); // used for 64-bit word storage var _w = new Array(80); for(var wi = 0; wi < 80; ++wi) { _w[wi] = new Array(2); } // message digest object var md = { // SHA-512 => sha512 algorithm: algorithm.replace('-', '').toLowerCase(), blockLength: 128, digestLength: 64, // 56-bit length of message so far (does not including padding) messageLength: 0, // true message length fullMessageLength: null, // size of message length in bytes messageLengthSize: 16 }; /** * Starts the digest. * * @return this digest object. */ md.start = function() { // up to 56-bit message length for convenience md.messageLength = 0; // full message length (set md.messageLength128 for backwards-compatibility) md.fullMessageLength = md.messageLength128 = []; var int32s = md.messageLengthSize / 4; for(var i = 0; i < int32s; ++i) { md.fullMessageLength.push(0); } _input = forge.util.createBuffer(); _h = new Array(_state.length); for(var i = 0; i < _state.length; ++i) { _h[i] = _state[i].slice(0); } return md; }; // start digest automatically for first time md.start(); /** * Updates the digest with the given message input. The given input can * treated as raw input (no encoding will be applied) or an encoding of * 'utf8' maybe given to encode the input using UTF-8. * * @param msg the message input to update with. * @param encoding the encoding to use (default: 'raw', other: 'utf8'). * * @return this digest object. */ md.update = function(msg, encoding) { if(encoding === 'utf8') { msg = forge.util.encodeUtf8(msg); } // update message length var len = msg.length; md.messageLength += len; len = [(len / 0x100000000) >>> 0, len >>> 0]; for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { md.fullMessageLength[i] += len[1]; len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; len[0] = ((len[1] / 0x100000000) >>> 0); } // add bytes to input buffer _input.putBytes(msg); // process bytes _update(_h, _w, _input); // compact input buffer every 2K or if empty if(_input.read > 2048 || _input.length() === 0) { _input.compact(); } return md; }; /** * Produces the digest. * * @return a byte buffer containing the digest value. */ md.digest = function() { /* Note: Here we copy the remaining bytes in the input buffer and add the appropriate SHA-512 padding. Then we do the final update on a copy of the state so that if the user wants to get intermediate digests they can do so. */ /* Determine the number of bytes that must be added to the message to ensure its length is congruent to 896 mod 1024. In other words, the data to be digested must be a multiple of 1024 bits (or 128 bytes). This data includes the message, some padding, and the length of the message. Since the length of the message will be encoded as 16 bytes (128 bits), that means that the last segment of the data must have 112 bytes (896 bits) of message and padding. Therefore, the length of the message plus the padding must be congruent to 896 mod 1024 because 1024 - 128 = 896. In order to fill up the message length it must be filled with padding that begins with 1 bit followed by all 0 bits. Padding must *always* be present, so if the message length is already congruent to 896 mod 1024, then 1024 padding bits must be added. */ var finalBlock = forge.util.createBuffer(); finalBlock.putBytes(_input.bytes()); // compute remaining size to be digested (include message length size) var remaining = ( md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize); // add padding for overflow blockSize - overflow // _padding starts with 1 byte with first bit is set (byte value 128), then // there may be up to (blockSize - 1) other pad bytes var overflow = remaining & (md.blockLength - 1); finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); // serialize message length in bits in big-endian order; since length // is stored in bytes we multiply by 8 and add carry from next int var messageLength = forge.util.createBuffer(); var next, carry; var bits = md.fullMessageLength[0] * 8; for(var i = 0; i < md.fullMessageLength.length; ++i) { next = md.fullMessageLength[i + 1] * 8; carry = (next / 0x100000000) >>> 0; bits += carry; finalBlock.putInt32(bits >>> 0); bits = next; } var h = new Array(_h.length); for(var i = 0; i < _h.length; ++i) { h[i] = _h[i].slice(0); } _update(h, _w, finalBlock); var rval = forge.util.createBuffer(); var hlen; if(algorithm === 'SHA-512') { hlen = h.length; } else if(algorithm === 'SHA-384') { hlen = h.length - 2; } else { hlen = h.length - 4; } for(var i = 0; i < hlen; ++i) { rval.putInt32(h[i][0]); if(i !== hlen - 1 || algorithm !== 'SHA-512/224') { rval.putInt32(h[i][1]); } } return rval; }; return md; }; // sha-512 padding bytes not initialized yet var _padding = null; var _initialized = false; // table of constants var _k = null; // initial hash states var _states = null; /** * Initializes the constant tables. */ function _init() { // create padding _padding = String.fromCharCode(128); _padding += forge.util.fillString(String.fromCharCode(0x00), 128); // create K table for SHA-512 _k = [ [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd], [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc], [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019], [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118], [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe], [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2], [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1], [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694], [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3], [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65], [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483], [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5], [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210], [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4], [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725], [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70], [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926], [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df], [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8], [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b], [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001], [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30], [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910], [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8], [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53], [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8], [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb], [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3], [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60], [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec], [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9], [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b], [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207], [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178], [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6], [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b], [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493], [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c], [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a], [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817] ]; // initial hash states _states = {}; _states['SHA-512'] = [ [0x6a09e667, 0xf3bcc908], [0xbb67ae85, 0x84caa73b], [0x3c6ef372, 0xfe94f82b], [0xa54ff53a, 0x5f1d36f1], [0x510e527f, 0xade682d1], [0x9b05688c, 0x2b3e6c1f], [0x1f83d9ab, 0xfb41bd6b], [0x5be0cd19, 0x137e2179] ]; _states['SHA-384'] = [ [0xcbbb9d5d, 0xc1059ed8], [0x629a292a, 0x367cd507], [0x9159015a, 0x3070dd17], [0x152fecd8, 0xf70e5939], [0x67332667, 0xffc00b31], [0x8eb44a87, 0x68581511], [0xdb0c2e0d, 0x64f98fa7], [0x47b5481d, 0xbefa4fa4] ]; _states['SHA-512/256'] = [ [0x22312194, 0xFC2BF72C], [0x9F555FA3, 0xC84C64C2], [0x2393B86B, 0x6F53B151], [0x96387719, 0x5940EABD], [0x96283EE2, 0xA88EFFE3], [0xBE5E1E25, 0x53863992], [0x2B0199FC, 0x2C85B8AA], [0x0EB72DDC, 0x81C52CA2] ]; _states['SHA-512/224'] = [ [0x8C3D37C8, 0x19544DA2], [0x73E19966, 0x89DCD4D6], [0x1DFAB7AE, 0x32FF9C82], [0x679DD514, 0x582F9FCF], [0x0F6D2B69, 0x7BD44DA8], [0x77E36F73, 0x04C48942], [0x3F9D85A8, 0x6A1D36C8], [0x1112E6AD, 0x91D692A1] ]; // now initialized _initialized = true; } /** * Updates a SHA-512 state with the given byte buffer. * * @param s the SHA-512 state to update. * @param w the array to use to store words. * @param bytes the byte buffer to update with. */ function _update(s, w, bytes) { // consume 512 bit (128 byte) chunks var t1_hi, t1_lo; var t2_hi, t2_lo; var s0_hi, s0_lo; var s1_hi, s1_lo; var ch_hi, ch_lo; var maj_hi, maj_lo; var a_hi, a_lo; var b_hi, b_lo; var c_hi, c_lo; var d_hi, d_lo; var e_hi, e_lo; var f_hi, f_lo; var g_hi, g_lo; var h_hi, h_lo; var i, hi, lo, w2, w7, w15, w16; var len = bytes.length(); while(len >= 128) { // the w array will be populated with sixteen 64-bit big-endian words // and then extended into 64 64-bit words according to SHA-512 for(i = 0; i < 16; ++i) { w[i][0] = bytes.getInt32() >>> 0; w[i][1] = bytes.getInt32() >>> 0; } for(; i < 80; ++i) { // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x) w2 = w[i - 2]; hi = w2[0]; lo = w2[1]; // high bits t1_hi = ( ((hi >>> 19) | (lo << 13)) ^ // ROTR 19 ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29) (hi >>> 6)) >>> 0; // SHR 6 // low bits t1_lo = ( ((hi << 13) | (lo >>> 19)) ^ // ROTR 19 ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29) ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6 // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x) w15 = w[i - 15]; hi = w15[0]; lo = w15[1]; // high bits t2_hi = ( ((hi >>> 1) | (lo << 31)) ^ // ROTR 1 ((hi >>> 8) | (lo << 24)) ^ // ROTR 8 (hi >>> 7)) >>> 0; // SHR 7 // low bits t2_lo = ( ((hi << 31) | (lo >>> 1)) ^ // ROTR 1 ((hi << 24) | (lo >>> 8)) ^ // ROTR 8 ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7 // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow) w7 = w[i - 7]; w16 = w[i - 16]; lo = (t1_lo + w7[1] + t2_lo + w16[1]); w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] + ((lo / 0x100000000) >>> 0)) >>> 0; w[i][1] = lo >>> 0; } // initialize hash value for this chunk a_hi = s[0][0]; a_lo = s[0][1]; b_hi = s[1][0]; b_lo = s[1][1]; c_hi = s[2][0]; c_lo = s[2][1]; d_hi = s[3][0]; d_lo = s[3][1]; e_hi = s[4][0]; e_lo = s[4][1]; f_hi = s[5][0]; f_lo = s[5][1]; g_hi = s[6][0]; g_lo = s[6][1]; h_hi = s[7][0]; h_lo = s[7][1]; // round function for(i = 0; i < 80; ++i) { // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e) s1_hi = ( ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14 ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18 ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9) s1_lo = ( ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14 ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18 ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9) // Ch(e, f, g) (optimized the same way as SHA-1) ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0; ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0; // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a) s0_hi = ( ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28 ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2) ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7) s0_lo = ( ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28 ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2) ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7) // Maj(a, b, c) (optimized the same way as SHA-1) maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0; maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0; // main algorithm // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow) lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]); t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + ((lo / 0x100000000) >>> 0)) >>> 0; t1_lo = lo >>> 0; // t2 = s0 + maj modulo 2^64 (carry lo overflow) lo = s0_lo + maj_lo; t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0; t2_lo = lo >>> 0; h_hi = g_hi; h_lo = g_lo; g_hi = f_hi; g_lo = f_lo; f_hi = e_hi; f_lo = e_lo; // e = (d + t1) modulo 2^64 (carry lo overflow) lo = d_lo + t1_lo; e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0; e_lo = lo >>> 0; d_hi = c_hi; d_lo = c_lo; c_hi = b_hi; c_lo = b_lo; b_hi = a_hi; b_lo = a_lo; // a = (t1 + t2) modulo 2^64 (carry lo overflow) lo = t1_lo + t2_lo; a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0; a_lo = lo >>> 0; } // update hash state (additional modulo 2^64) lo = s[0][1] + a_lo; s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[0][1] = lo >>> 0; lo = s[1][1] + b_lo; s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[1][1] = lo >>> 0; lo = s[2][1] + c_lo; s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[2][1] = lo >>> 0; lo = s[3][1] + d_lo; s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[3][1] = lo >>> 0; lo = s[4][1] + e_lo; s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[4][1] = lo >>> 0; lo = s[5][1] + f_lo; s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[5][1] = lo >>> 0; lo = s[6][1] + g_lo; s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[6][1] = lo >>> 0; lo = s[7][1] + h_lo; s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[7][1] = lo >>> 0; len -= 128; } } } // end module implementation /* ########## Begin module wrapper ########## */ var name = 'sha512'; if(typeof define !== 'function') { // NodeJS -> AMD if(typeof module === 'object' && module.exports) { var nodeJS = true; define = function(ids, factory) { factory(require, module); }; } else { // <script> if(typeof forge === 'undefined') { forge = {}; } return initModule(forge); } } // AMD var deps; var defineFunc = function(require, module) { module.exports = function(forge) { var mods = deps.map(function(dep) { return require(dep); }).concat(initModule); // handle circular dependencies forge = forge || {}; forge.defined = forge.defined || {}; if(forge.defined[name]) { return forge[name]; } forge.defined[name] = true; for(var i = 0; i < mods.length; ++i) { mods[i](forge); } return forge[name]; }; }; var tmpDefine = define; define = function(ids, factory) { deps = (typeof ids === 'string') ? factory.slice(2) : ids.slice(2); if(nodeJS) { delete define; return tmpDefine.apply(null, Array.prototype.slice.call(arguments, 0)); } define = tmpDefine; return define.apply(null, Array.prototype.slice.call(arguments, 0)); }; define(['require', 'module', './util'], function() { defineFunc.apply(null, Array.prototype.slice.call(arguments, 0)); }); })();
unki/thallium
public/resources/forge/js/sha512.js
JavaScript
agpl-3.0
18,329
// // iWeb - navbar.js // Copyright (c) 2007-2008 Apple Inc. All rights reserved. // var NavBar=Class.create(Widget,{widgetIdentifier:"com-apple-iweb-widget-NavBar",initialize:function($super,instanceID,widgetPath,sharedPath,sitePath,preferences,runningInApp) {if(instanceID) {$super(instanceID,widgetPath,sharedPath,sitePath,preferences,runningInApp);if(!this.preferenceForKey("useStaticFeed")&&this.preferenceForKey("dotMacAccount")) {var depthPrefix=this.preferenceForKey("path-to-root");if(!depthPrefix||depthPrefix=="") depthPrefix="./";this.xml_feed=depthPrefix+"?webdav-method=truthget&depth=infinity&ns=iweb&filterby=in-navbar";} else {this.xml_feed="feed.xml";if(this.sitePath) {this.xml_feed=this.sitePath+"/"+this.xml_feed;}} this.changedPreferenceForKey("navbar-css");this.regenerate();}},regenerate:function() {new Ajax.Request(this.xml_feed,{method:'get',onSuccess:this.populateNavItems.bind(this)});return true;},getStyleElement:function(key) {if(!this.styleElement) {var head=document.getElementsByTagName("head")[0];if(head) {var newElement=document.createElement("style");newElement.type="text/css";head.appendChild(newElement);this.styleElement=newElement;}} return this.styleElement;},substWidgetPath:function(text) {var result=text.replace(/\$WIDGET_PATH/gm,this.widgetPath);return result;},addCSSSelectorPrefix:function(text) {var prefix="div#"+this.instanceID+" ";text=text.replace(/\/\*[^*]*\*+([^/][^*]*\*+)*\//gm,"");text=text.replace(/(^\s*|\}\s*)([^{]+)({[^}]*})/gm,function(match,beforeSelectorList,selectorList,propertyList){var result=beforeSelectorList;var selectors=selectorList.split(",");for(var i=0;i<selectors.length;i++){result+=prefix+selectors[i];if(i+1<selectors.length)result+=",";} result+=propertyList;return result;});return text;},changedPreferenceForKey:function(key) {if(key=="navbar-css") {var text=this.preferenceForKey(key);if(!text) {text="";} text=this.substWidgetPath(text);text=this.addCSSSelectorPrefix(text);var styleElement=this.getStyleElement();if(styleElement) {if(!windowsInternetExplorer) {var node=document.createTextNode(text);if(node) {while(styleElement.hasChildNodes()) {styleElement.removeChild(styleElement.firstChild);} styleElement.appendChild(node);}} else {styleElement.styleSheet.cssText=text;}}}},populateNavItems:function(req) {var items;var feedRoot=ajaxGetDocumentElement(req);if(feedRoot){var parsedFeed=this.getAtomFeedItems(feedRoot);var items=parsedFeed.resultArray;var currentPageGUID=null;var isCollectionPage="NO";var curPagePat=null;if(this.runningInApp) curPagePat=/\.#current#.$/;else {currentPageGUID=this.preferenceForKey("current-page-GUID");isCollectionPage=this.preferenceForKey("isCollectionPage");} var navDiv=this.div("navbar-list");var navBgDiv=navDiv.parentNode;$(navBgDiv).ensureHasLayoutForIE();while(navDiv.firstChild){navDiv.removeChild(navDiv.firstChild);} var depthPrefix=this.preferenceForKey("path-to-root");if(!depthPrefix||depthPrefix=="") depthPrefix="./";for(var x=0;x<items.length;x++){var navItem=document.createElement("li");var anchor=document.createElement("a");var title=items[x].title;var pageGUID=items[x].GUID;title=title.replace(/ /g,"\u00a0")+" ";var url=items[x].url;if(!this.runningInApp&&!url.match(/^http:/i)) url=depthPrefix+url;var inAppCurPage=this.runningInApp&&curPagePat.exec(unescape(new String(url)));if(inAppCurPage) {url=url.replace(curPagePat,"");} if(pageGUID==currentPageGUID||inAppCurPage){navItem.className='current-page';if(!this.runningInApp&&isCollectionPage!="YES"){url="";}} else navItem.className='noncurrent-page';anchor.setAttribute("href",url);anchor.appendChild(document.createTextNode(title));navItem.appendChild(anchor);navDiv.appendChild(navItem);} if(this.preferences&&this.preferences.postNotification){this.preferences.postNotification("BLWidgetIsSafeToDrawNotification",1);}}},getAtomFeedItems:function(feedNode) {var results=new Array;var pageOrder=new Array;if(feedNode) {var generator="";var generatorElt=getFirstElementByTagName(feedNode,"generator");if(generatorElt&&generatorElt.firstChild){generator=allData(generatorElt);} var pageGUIDs,pageGUIDsElt;for(var entryElt=feedNode.firstChild;entryElt;entryElt=entryElt.nextSibling){var isInNavbarElt=null;if(!pageGUIDs&&(pageGUIDsElt=findChild(entryElt,"site-navbar","urn:iweb:"))){pageGUIDs=allData(pageGUIDsElt).split(",");for(var x=0;x<pageGUIDs.length;x++){var pageGUID=pageGUIDs[x];pageOrder[""+pageGUID]=x;}} if(entryElt.nodeName=="entry"&&(isInNavbarElt=findChild(entryElt,"in-navbar","urn:iweb:"))){if(!isInNavbarElt) continue;var pageGUID="";if(isInNavbarElt.firstChild){pageGUID=""+allData(isInNavbarElt);}else{iWLog("no navBarElt child");} if(pageGUID=="navbar-sort") continue;var title="";var titleElt=findChild(entryElt,"title","urn:iweb:");if(!titleElt){iWLog("No iWeb title");titleElt=findChild(entryElt,"title");} if(titleElt&&titleElt.firstChild){title=allData(titleElt);} var linkElt=getFirstElementByTagName(entryElt,'link');url=linkElt.getAttribute("href");if(!url&&linkElement.firstChild){url=allData(linkElement);} results[results.length]={title:title,url:url,GUID:pageGUID};}}} if(pageGUIDs){results=$(results).reject(function(result){return(pageOrder[result.GUID]===undefined);});results.sort(function(lhs,rhs){return pageOrder[lhs.GUID]-pageOrder[rhs.GUID];});} return{resultArray:results};},onload:function() {},onunload:function() {}});function findChild(element,nodeName,namespace) {var child;for(child=element.firstChild;child;child=child.nextSibling){if(child.localName==nodeName||child.baseName==nodeName){if(!namespace){return child;} var childNameSpace=child.namespaceURI;if(childNameSpace==namespace){return child;}}} return null;} function getFirstElementByTagName(node,tag_name){var elements=node.getElementsByTagName(tag_name);if(elements.length){return elements[0];} else{return findChild(node,tag_name);}} function allData(node) {node=node.firstChild;var data=node.data;while((node=node.nextSibling)){data+=node.data;} return data;}
vrdmr/vrdmr.github.io
www/Scripts/Widgets/Navbar/navbar.js
JavaScript
mit
5,986
app.controller('LayersOverlaysMarkersNestedController', ['$scope', 'leafletData','$timeout', function ($scope, leafletData, $timeout) { var _map; leafletData.getMap().then(function(map){ _map = map; }); angular.extend($scope, { eraseMarkers: function(){ $scope.markers = { cars: { m1: { lat: 42.20133, lng: 2.19110, message: "I'm a car" } } }; //$scope.$apply(); leafletData.getMarkers().then(function(lmarkers) { $scope.hasM1 = _map.hasLayer(lmarkers.m1); $scope.hasM2 = _map.hasLayer(lmarkers.m2); }); $timeout(function(){ leafletData.getMarkers().then(function(lmarkers){ $scope.lMarkers = Object.keys(lmarkers); $scope.hasM1 = _map.hasLayer(lmarkers.m1); $scope.hasM2 = _map.hasLayer(lmarkers.m2); }); },1000); }, lMarkers:{}, ripoll: { lat: 42.20133, lng: 2.19110, zoom: 11 }, layers: { baselayers: { osm: { name: 'OpenStreetMap', type: 'xyz', url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', layerOptions: { subdomains: ['a', 'b', 'c'], attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', continuousWorld: true } }, cycle: { name: 'OpenCycleMap', type: 'xyz', url: 'http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', layerOptions: { subdomains: ['a', 'b', 'c'], attribution: '&copy; <a href="http://www.opencyclemap.org/copyright">OpenCycleMap</a> contributors - &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', continuousWorld: true } } }, overlays: { hillshade: { name: 'Hillshade Europa', type: 'wms', url: 'http://129.206.228.72/cached/hillshade', visible: true, layerOptions: { layers: 'europe_wms:hs_srtm_europa', format: 'image/png', opacity: 0.25, attribution: 'Hillshade layer by GIScience http://www.osm-wms.de', crs: L.CRS.EPSG900913 } }, fire: { name: 'OpenFireMap', type: 'xyz', url: 'http://openfiremap.org/hytiles/{z}/{x}/{y}.png', layerOptions: { attribution: '&copy; <a href="http://www.openfiremap.org">OpenFireMap</a> contributors - &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', continuousWorld: true } }, cars: { name: 'Cars', type: 'group', visible: true }, bikes: { name: 'Bicycles', type: 'group', visible: false }, runners:{ name: 'Runners', type: 'group', visible: false } } }, markers: { cars: { m1: { lat: 42.20133, lng: 2.19110, message: "I'm a car" }, m2: { lat: 42.21133, lng: 2.18110, message: "I'm a car" } }, bikes: { m3: { lat: 42.19133, lng: 2.18110, layer: 'bikes', message: 'A bike!!' }, m4: { lat: 42.3, lng: 2.16110, layer: 'bikes' } }, runners: { m5: { lat: 42.1, lng: 2.16910 }, m6: { lat: 42.15, lng: 2.17110 } } } }); }]);
ronnpang1/otocopy
www/lib/angular-leaflet-directive-master/examples/js/controllers/LayersOverlaysMarkersNestedController.js
JavaScript
mit
6,000
'use strict'; // TODO(matsko): use caching here to speed things up for detection // TODO(matsko): add documentation // by the time... var $$AnimateJsProvider = ['$animateProvider', /** @this */ function($animateProvider) { this.$get = ['$injector', '$$AnimateRunner', '$$jqLite', function($injector, $$AnimateRunner, $$jqLite) { var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); // $animateJs(element, 'enter'); return function(element, event, classes, options) { var animationClosed = false; // the `classes` argument is optional and if it is not used // then the classes will be resolved from the element's className // property as well as options.addClass/options.removeClass. if (arguments.length === 3 && isObject(classes)) { options = classes; classes = null; } options = prepareAnimationOptions(options); if (!classes) { classes = element.attr('class') || ''; if (options.addClass) { classes += ' ' + options.addClass; } if (options.removeClass) { classes += ' ' + options.removeClass; } } var classesToAdd = options.addClass; var classesToRemove = options.removeClass; // the lookupAnimations function returns a series of animation objects that are // matched up with one or more of the CSS classes. These animation objects are // defined via the module.animation factory function. If nothing is detected then // we don't return anything which then makes $animation query the next driver. var animations = lookupAnimations(classes); var before, after; if (animations.length) { var afterFn, beforeFn; if (event === 'leave') { beforeFn = 'leave'; afterFn = 'afterLeave'; // TODO(matsko): get rid of this } else { beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1); afterFn = event; } if (event !== 'enter' && event !== 'move') { before = packageAnimations(element, event, options, animations, beforeFn); } after = packageAnimations(element, event, options, animations, afterFn); } // no matching animations if (!before && !after) return; function applyOptions() { options.domOperation(); applyAnimationClasses(element, options); } function close() { animationClosed = true; applyOptions(); applyAnimationStyles(element, options); } var runner; return { $$willAnimate: true, end: function() { if (runner) { runner.end(); } else { close(); runner = new $$AnimateRunner(); runner.complete(true); } return runner; }, start: function() { if (runner) { return runner; } runner = new $$AnimateRunner(); var closeActiveAnimations; var chain = []; if (before) { chain.push(function(fn) { closeActiveAnimations = before(fn); }); } if (chain.length) { chain.push(function(fn) { applyOptions(); fn(true); }); } else { applyOptions(); } if (after) { chain.push(function(fn) { closeActiveAnimations = after(fn); }); } runner.setHost({ end: function() { endAnimations(); }, cancel: function() { endAnimations(true); } }); $$AnimateRunner.chain(chain, onComplete); return runner; function onComplete(success) { close(success); runner.complete(success); } function endAnimations(cancelled) { if (!animationClosed) { (closeActiveAnimations || noop)(cancelled); onComplete(cancelled); } } } }; function executeAnimationFn(fn, element, event, options, onDone) { var args; switch (event) { case 'animate': args = [element, options.from, options.to, onDone]; break; case 'setClass': args = [element, classesToAdd, classesToRemove, onDone]; break; case 'addClass': args = [element, classesToAdd, onDone]; break; case 'removeClass': args = [element, classesToRemove, onDone]; break; default: args = [element, onDone]; break; } args.push(options); var value = fn.apply(fn, args); if (value) { if (isFunction(value.start)) { value = value.start(); } if (value instanceof $$AnimateRunner) { value.done(onDone); } else if (isFunction(value)) { // optional onEnd / onCancel callback return value; } } return noop; } function groupEventedAnimations(element, event, options, animations, fnName) { var operations = []; forEach(animations, function(ani) { var animation = ani[fnName]; if (!animation) return; // note that all of these animations will run in parallel operations.push(function() { var runner; var endProgressCb; var resolved = false; var onAnimationComplete = function(rejected) { if (!resolved) { resolved = true; (endProgressCb || noop)(rejected); runner.complete(!rejected); } }; runner = new $$AnimateRunner({ end: function() { onAnimationComplete(); }, cancel: function() { onAnimationComplete(true); } }); endProgressCb = executeAnimationFn(animation, element, event, options, function(result) { var cancelled = result === false; onAnimationComplete(cancelled); }); return runner; }); }); return operations; } function packageAnimations(element, event, options, animations, fnName) { var operations = groupEventedAnimations(element, event, options, animations, fnName); if (operations.length === 0) { var a, b; if (fnName === 'beforeSetClass') { a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass'); b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass'); } else if (fnName === 'setClass') { a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass'); b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass'); } if (a) { operations = operations.concat(a); } if (b) { operations = operations.concat(b); } } if (operations.length === 0) return; // TODO(matsko): add documentation return function startAnimation(callback) { var runners = []; if (operations.length) { forEach(operations, function(animateFn) { runners.push(animateFn()); }); } if (runners.length) { $$AnimateRunner.all(runners, callback); } else { callback(); } return function endFn(reject) { forEach(runners, function(runner) { if (reject) { runner.cancel(); } else { runner.end(); } }); }; }; } }; function lookupAnimations(classes) { classes = isArray(classes) ? classes : classes.split(' '); var matches = [], flagMap = {}; for (var i = 0; i < classes.length; i++) { var klass = classes[i], animationFactory = $animateProvider.$$registeredAnimations[klass]; if (animationFactory && !flagMap[klass]) { matches.push($injector.get(animationFactory)); flagMap[klass] = true; } } return matches; } }]; }];
Aremyst/angular.js
src/ngAnimate/animateJs.js
JavaScript
mit
8,632
module.exports = { prefix: 'fas', iconName: 'align-justify', icon: [448, 512, [], "f039", "M0 84V44c0-8.837 7.163-16 16-16h416c8.837 0 16 7.163 16 16v40c0 8.837-7.163 16-16 16H16c-8.837 0-16-7.163-16-16zm16 144h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16zm0 256h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16zm0-128h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16z"] };
evepraisal/go-evepraisal
web/resources/static/thirdparty/fontawesome-free-5.0.8/advanced-options/use-with-node-js/fontawesome-free-solid/faAlignJustify.js
JavaScript
mit
551
module.exports = { prefix: 'fab', iconName: 'tumblr-square', icon: [448, 512, [], "f174", "M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zm-82.3 364.2c-8.5 9.1-31.2 19.8-60.9 19.8-75.5 0-91.9-55.5-91.9-87.9v-90h-29.7c-3.4 0-6.2-2.8-6.2-6.2v-42.5c0-4.5 2.8-8.5 7.1-10 38.8-13.7 50.9-47.5 52.7-73.2.5-6.9 4.1-10.2 10-10.2h44.3c3.4 0 6.2 2.8 6.2 6.2v72h51.9c3.4 0 6.2 2.8 6.2 6.2v51.1c0 3.4-2.8 6.2-6.2 6.2h-52.1V321c0 21.4 14.8 33.5 42.5 22.4 3-1.2 5.6-2 8-1.4 2.2.5 3.6 2.1 4.6 4.9l13.8 40.2c1 3.2 2 6.7-.3 9.1z"] };
evepraisal/go-evepraisal
web/resources/static/thirdparty/fontawesome-free-5.0.8/advanced-options/use-with-node-js/fontawesome-free-brands/faTumblrSquare.js
JavaScript
mit
573
'use strict'; module.exports.definition = { set: function (v) { this._setProperty('-webkit-border-fit', v); }, get: function () { return this.getPropertyValue('-webkit-border-fit'); }, enumerable: true, configurable: true };
ElvisLouis/code
work/js/node_modules/jsdom/node_modules/cssstyle/lib/properties/webkitBorderFit.js
JavaScript
gpl-2.0
266
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview A command is an abstraction of an action a user can do in the * UI. * * When the focus changes in the document for each command a canExecute event * is dispatched on the active element. By listening to this event you can * enable and disable the command by setting the event.canExecute property. * * When a command is executed a command event is dispatched on the active * element. Note that you should stop the propagation after you have handled the * command if there might be other command listeners higher up in the DOM tree. */ cr.define('cr.ui', function() { /** * This is used to identify keyboard shortcuts. * @param {string} shortcut The text used to describe the keys for this * keyboard shortcut. * @constructor */ function KeyboardShortcut(shortcut) { var mods = {}; var ident = ''; shortcut.split('-').forEach(function(part) { var partLc = part.toLowerCase(); switch (partLc) { case 'alt': case 'ctrl': case 'meta': case 'shift': mods[partLc + 'Key'] = true; break; default: if (ident) throw Error('Invalid shortcut'); ident = part; } }); this.ident_ = ident; this.mods_ = mods; } KeyboardShortcut.prototype = { /** * Whether the keyboard shortcut object matches a keyboard event. * @param {!Event} e The keyboard event object. * @return {boolean} Whether we found a match or not. */ matchesEvent: function(e) { if (e.keyIdentifier == this.ident_) { // All keyboard modifiers needs to match. var mods = this.mods_; return ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'].every(function(k) { return e[k] == !!mods[k]; }); } return false; } }; /** * Creates a new command element. * @constructor * @extends {HTMLElement} */ var Command = cr.ui.define('command'); Command.prototype = { __proto__: HTMLElement.prototype, /** * Initializes the command. */ decorate: function() { CommandManager.init(assert(this.ownerDocument)); if (this.hasAttribute('shortcut')) this.shortcut = this.getAttribute('shortcut'); }, /** * Executes the command by dispatching a command event on the given element. * If |element| isn't given, the active element is used instead. * If the command is {@code disabled} this does nothing. * @param {HTMLElement=} opt_element Optional element to dispatch event on. */ execute: function(opt_element) { if (this.disabled) return; var doc = this.ownerDocument; if (doc.activeElement) { var e = new Event('command', {bubbles: true}); e.command = this; (opt_element || doc.activeElement).dispatchEvent(e); } }, /** * Call this when there have been changes that might change whether the * command can be executed or not. * @param {Node=} opt_node Node for which to actuate command state. */ canExecuteChange: function(opt_node) { dispatchCanExecuteEvent(this, opt_node || this.ownerDocument.activeElement); }, /** * The keyboard shortcut that triggers the command. This is a string * consisting of a keyIdentifier (as reported by WebKit in keydown) as * well as optional key modifiers joinded with a '-'. * * Multiple keyboard shortcuts can be provided by separating them by * whitespace. * * For example: * "F1" * "U+0008-Meta" for Apple command backspace. * "U+0041-Ctrl" for Control A * "U+007F U+0008-Meta" for Delete and Command Backspace * * @type {string} */ shortcut_: '', get shortcut() { return this.shortcut_; }, set shortcut(shortcut) { var oldShortcut = this.shortcut_; if (shortcut !== oldShortcut) { this.keyboardShortcuts_ = shortcut.split(/\s+/).map(function(shortcut) { return new KeyboardShortcut(shortcut); }); // Set this after the keyboardShortcuts_ since that might throw. this.shortcut_ = shortcut; cr.dispatchPropertyChange(this, 'shortcut', this.shortcut_, oldShortcut); } }, /** * Whether the event object matches the shortcut for this command. * @param {!Event} e The key event object. * @return {boolean} Whether it matched or not. */ matchesEvent: function(e) { if (!this.keyboardShortcuts_) return false; return this.keyboardShortcuts_.some(function(keyboardShortcut) { return keyboardShortcut.matchesEvent(e); }); }, }; /** * The label of the command. */ cr.defineProperty(Command, 'label', cr.PropertyKind.ATTR); /** * Whether the command is disabled or not. */ cr.defineProperty(Command, 'disabled', cr.PropertyKind.BOOL_ATTR); /** * Whether the command is hidden or not. */ cr.defineProperty(Command, 'hidden', cr.PropertyKind.BOOL_ATTR); /** * Whether the command is checked or not. */ cr.defineProperty(Command, 'checked', cr.PropertyKind.BOOL_ATTR); /** * The flag that prevents the shortcut text from being displayed on menu. * * If false, the keyboard shortcut text (eg. "Ctrl+X" for the cut command) * is displayed in menu when the command is assosiated with a menu item. * Otherwise, no text is displayed. */ cr.defineProperty(Command, 'hideShortcutText', cr.PropertyKind.BOOL_ATTR); /** * Dispatches a canExecute event on the target. * @param {!cr.ui.Command} command The command that we are testing for. * @param {EventTarget} target The target element to dispatch the event on. */ function dispatchCanExecuteEvent(command, target) { var e = new CanExecuteEvent(command); target.dispatchEvent(e); command.disabled = !e.canExecute; } /** * The command managers for different documents. */ var commandManagers = {}; /** * Keeps track of the focused element and updates the commands when the focus * changes. * @param {!Document} doc The document that we are managing the commands for. * @constructor */ function CommandManager(doc) { doc.addEventListener('focus', this.handleFocus_.bind(this), true); // Make sure we add the listener to the bubbling phase so that elements can // prevent the command. doc.addEventListener('keydown', this.handleKeyDown_.bind(this), false); } /** * Initializes a command manager for the document as needed. * @param {!Document} doc The document to manage the commands for. */ CommandManager.init = function(doc) { var uid = cr.getUid(doc); if (!(uid in commandManagers)) { commandManagers[uid] = new CommandManager(doc); } }; CommandManager.prototype = { /** * Handles focus changes on the document. * @param {Event} e The focus event object. * @private * @suppress {checkTypes} * TODO(vitalyp): remove the suppression. */ handleFocus_: function(e) { var target = e.target; // Ignore focus on a menu button or command item. if (target.menu || target.command) return; var commands = Array.prototype.slice.call( target.ownerDocument.querySelectorAll('command')); commands.forEach(function(command) { dispatchCanExecuteEvent(command, target); }); }, /** * Handles the keydown event and routes it to the right command. * @param {!Event} e The keydown event. */ handleKeyDown_: function(e) { var target = e.target; var commands = Array.prototype.slice.call( target.ownerDocument.querySelectorAll('command')); for (var i = 0, command; command = commands[i]; i++) { if (command.matchesEvent(e)) { // When invoking a command via a shortcut, we have to manually check // if it can be executed, since focus might not have been changed // what would have updated the command's state. command.canExecuteChange(); if (!command.disabled) { e.preventDefault(); // We do not want any other element to handle this. e.stopPropagation(); command.execute(); return; } } } } }; /** * The event type used for canExecute events. * @param {!cr.ui.Command} command The command that we are evaluating. * @extends {Event} * @constructor * @class */ function CanExecuteEvent(command) { var e = new Event('canExecute', {bubbles: true, cancelable: true}); e.__proto__ = CanExecuteEvent.prototype; e.command = command; return e; } CanExecuteEvent.prototype = { __proto__: Event.prototype, /** * The current command * @type {cr.ui.Command} */ command: null, /** * Whether the target can execute the command. Setting this also stops the * propagation and prevents the default. Callers can tell if an event has * been handled via |this.defaultPrevented|. * @type {boolean} */ canExecute_: false, get canExecute() { return this.canExecute_; }, set canExecute(canExecute) { this.canExecute_ = !!canExecute; this.stopPropagation(); this.preventDefault(); } }; // Export return { Command: Command, CanExecuteEvent: CanExecuteEvent }; });
Chilledheart/chromium
ui/webui/resources/js/cr/ui/command.js
JavaScript
bsd-3-clause
9,731
L.Icon.Canvas=L.Icon.extend({options:{iconSize:new L.Point(20,20),className:"leaflet-canvas-icon"},createIcon:function(){var e=document.createElement("canvas");this._setIconStyles(e,"icon");var s=this.options.iconSize;return e.width=s.x,e.height=s.y,this.draw(e.getContext("2d"),s.x,s.y),e},createShadow:function(){return null},draw:function(canvas,width,height){}});
kiwi89/cdnjs
ajax/libs/leaflet-plugins/1.4.2/layer/Icon.Canvas.min.js
JavaScript
mit
367
'use strict'; /** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ const chalk = require('chalk'); module.exports = (str, start, end) => chalk.dim(str.slice(0, start)) + chalk.reset(str.slice(start, end)) + chalk.dim(str.slice(end));
akhilapnair/exercism-ecmascript
sum-of-multiples/node_modules/jest/node_modules/jest-cli/build/lib/colorize.js
JavaScript
mit
607
var Shader = require('./Shader'); /** * @class * @memberof PIXI * @extends PIXI.Shader * @param shaderManager {ShaderManager} The webgl shader manager this shader works for. * @param [vertexSrc] {string} The source of the vertex shader. * @param [fragmentSrc] {string} The source of the fragment shader. * @param [customUniforms] {object} Custom uniforms to use to augment the built-in ones. * @param [fragmentSrc] {string} The source of the fragment shader. */ function TextureShader(shaderManager, vertexSrc, fragmentSrc, customUniforms, customAttributes) { var uniforms = { uSampler: { type: 'sampler2D', value: 0 }, projectionMatrix: { type: 'mat3', value: new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]) } }; if (customUniforms) { for (var u in customUniforms) { uniforms[u] = customUniforms[u]; } } var attributes = { aVertexPosition: 0, aTextureCoord: 0, aColor: 0 }; if (customAttributes) { for (var a in customAttributes) { attributes[a] = customAttributes[a]; } } /** * The vertex shader. * @member {Array} */ vertexSrc = vertexSrc || TextureShader.defaultVertexSrc; /** * The fragment shader. * @member {Array} */ fragmentSrc = fragmentSrc || TextureShader.defaultFragmentSrc; Shader.call(this, shaderManager, vertexSrc, fragmentSrc, uniforms, attributes); } // constructor TextureShader.prototype = Object.create(Shader.prototype); TextureShader.prototype.constructor = TextureShader; module.exports = TextureShader; TextureShader.defaultVertexSrc = [ 'precision lowp float;', 'attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute vec4 aColor;', 'uniform mat3 projectionMatrix;', 'varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', '}' ].join('\n'); TextureShader.defaultFragmentSrc = [ 'precision lowp float;', 'varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'uniform sampler2D uSampler;', 'void main(void){', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', '}' ].join('\n');
nabettu/pixi.js
src/core/renderers/webgl/shaders/TextureShader.js
JavaScript
mit
2,615
(function() { var BINARY_EXTENSIONS, COMPRESSED_EXTENSIONS, IMAGE_EXTENSIONS, MARKDOWN_EXTENSIONS, Module, async, fs, fsPlus, isMoveTargetValid, isMoveTargetValidSync, isPathValid, lstatSyncNoException, mkdirp, path, rimraf, statSyncNoException, _, __slice = [].slice; fs = require('fs'); Module = require('module'); path = require('path'); _ = require('underscore-plus'); async = require('async'); mkdirp = require('mkdirp'); rimraf = require('rimraf'); fsPlus = { getHomeDirectory: function() { if (process.platform === 'win32') { return process.env.USERPROFILE; } else { return process.env.HOME; } }, absolute: function(relativePath) { var e, homeDir; if (relativePath == null) { return null; } homeDir = fsPlus.getHomeDirectory(); if (relativePath === '~') { relativePath = homeDir; } else if (relativePath.indexOf('~/') === 0) { relativePath = "" + homeDir + (relativePath.substring(1)); } try { return fs.realpathSync(relativePath); } catch (_error) { e = _error; return relativePath; } }, normalize: function(pathToNormalize) { var home, normalizedPath; if (pathToNormalize == null) { return null; } normalizedPath = path.normalize(pathToNormalize.toString()); if (home = fsPlus.getHomeDirectory()) { if (normalizedPath === '~') { normalizedPath = home; } else if (normalizedPath.indexOf("~" + path.sep) === 0) { normalizedPath = "" + home + (normalizedPath.substring(1)); } } return normalizedPath; }, getAppDataDirectory: function() { switch (process.platform) { case 'darwin': return fsPlus.absolute('~/Library/Application Support'); case 'linux': return '/var/lib'; case 'win32': return process.env.APPDATA; default: return null; } }, isAbsolute: function(pathToCheck) { if (pathToCheck == null) { pathToCheck = ''; } if (process.platform === 'win32') { if (pathToCheck[1] === ':') { return true; } if (pathToCheck[0] === '\\' && pathToCheck[1] === '\\') { return true; } } else { return pathToCheck[0] === '/'; } return false; }, existsSync: function(pathToCheck) { return isPathValid(pathToCheck) && (statSyncNoException(pathToCheck) !== false); }, isDirectorySync: function(directoryPath) { var stat; if (!isPathValid(directoryPath)) { return false; } if (stat = statSyncNoException(directoryPath)) { return stat.isDirectory(); } else { return false; } }, isDirectory: function(directoryPath, done) { if (!isPathValid(directoryPath)) { return done(false); } return fs.stat(directoryPath, function(error, stat) { if (error != null) { return done(false); } else { return done(stat.isDirectory()); } }); }, isFileSync: function(filePath) { var stat; if (!isPathValid(filePath)) { return false; } if (stat = statSyncNoException(filePath)) { return stat.isFile(); } else { return false; } }, isSymbolicLinkSync: function(symlinkPath) { var stat; if (!isPathValid(symlinkPath)) { return false; } if (stat = lstatSyncNoException(symlinkPath)) { return stat.isSymbolicLink(); } else { return false; } }, isSymbolicLink: function(symlinkPath, callback) { if (isPathValid(symlinkPath)) { return fs.lstat(symlinkPath, function(error, stat) { return typeof callback === "function" ? callback((stat != null) && stat.isSymbolicLink()) : void 0; }); } else { return process.nextTick(function() { return typeof callback === "function" ? callback(false) : void 0; }); } }, isExecutableSync: function(pathToCheck) { var stat; if (!isPathValid(pathToCheck)) { return false; } if (stat = statSyncNoException(pathToCheck)) { return (stat.mode & 0x1ff & 1) !== 0; } else { return false; } }, getSizeSync: function(pathToCheck) { var _ref; if (isPathValid(pathToCheck)) { return (_ref = statSyncNoException(pathToCheck).size) != null ? _ref : -1; } else { return -1; } }, listSync: function(rootPath, extensions) { var paths; if (!fsPlus.isDirectorySync(rootPath)) { return []; } paths = fs.readdirSync(rootPath); if (extensions) { paths = fsPlus.filterExtensions(paths, extensions); } paths = paths.sort(function(a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); }); paths = paths.map(function(childPath) { return path.join(rootPath, childPath); }); return paths; }, list: function() { var done, extensions, rest, rootPath; rootPath = arguments[0], rest = 2 <= arguments.length ? __slice.call(arguments, 1) : []; if (rest.length > 1) { extensions = rest.shift(); } done = rest.shift(); return fs.readdir(rootPath, function(error, paths) { if (error != null) { return done(error); } else { if (extensions) { paths = fsPlus.filterExtensions(paths, extensions); } paths = paths.sort(function(a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); }); paths = paths.map(function(childPath) { return path.join(rootPath, childPath); }); return done(null, paths); } }); }, filterExtensions: function(paths, extensions) { extensions = extensions.map(function(ext) { if (ext === '') { return ext; } else { return '.' + ext.replace(/^\./, ''); } }); return paths.filter(function(pathToCheck) { return _.include(extensions, path.extname(pathToCheck)); }); }, listTreeSync: function(rootPath) { var onPath, paths; paths = []; onPath = function(childPath) { paths.push(childPath); return true; }; fsPlus.traverseTreeSync(rootPath, onPath, onPath); return paths; }, move: function(source, target, callback) { return isMoveTargetValid(source, target, function(isMoveTargetValidErr, isTargetValid) { var error, targetParentPath; if (isMoveTargetValidErr) { callback(isMoveTargetValidErr); return; } if (!isTargetValid) { error = new Error("'" + target + "' already exists."); error.code = 'EEXIST'; callback(error); return; } targetParentPath = path.dirname(target); return fs.exists(targetParentPath, function(targetParentExists) { if (targetParentExists) { fs.rename(source, target, callback); return; } return fsPlus.makeTree(targetParentPath, function(makeTreeErr) { if (makeTreeErr) { callback(makeTreeErr); return; } return fs.rename(source, target, callback); }); }); }); }, moveSync: function(source, target) { var error, targetParentPath; if (!isMoveTargetValidSync(source, target)) { error = new Error("'" + target + "' already exists."); error.code = 'EEXIST'; throw error; } targetParentPath = path.dirname(target); if (!fs.existsSync(targetParentPath)) { fsPlus.makeTreeSync(targetParentPath); } return fs.renameSync(source, target); }, removeSync: function(pathToRemove) { return rimraf.sync(pathToRemove); }, remove: function(pathToRemove, callback) { return rimraf(pathToRemove, callback); }, writeFileSync: function(filePath, content, options) { mkdirp.sync(path.dirname(filePath)); return fs.writeFileSync(filePath, content, options); }, writeFile: function(filePath, content, options, callback) { callback = _.last(arguments); return mkdirp(path.dirname(filePath), function(error) { if (error != null) { return typeof callback === "function" ? callback(error) : void 0; } else { return fs.writeFile(filePath, content, options, callback); } }); }, copy: function(sourcePath, destinationPath, done) { return mkdirp(path.dirname(destinationPath), function(error) { var destinationStream, sourceStream; if (error != null) { if (typeof done === "function") { done(error); } return; } sourceStream = fs.createReadStream(sourcePath); sourceStream.on('error', function(error) { if (typeof done === "function") { done(error); } return done = null; }); destinationStream = fs.createWriteStream(destinationPath); destinationStream.on('error', function(error) { if (typeof done === "function") { done(error); } return done = null; }); destinationStream.on('close', function() { if (typeof done === "function") { done(); } return done = null; }); return sourceStream.pipe(destinationStream); }); }, copySync: function(sourcePath, destinationPath) { var content, destinationFilePath, source, sourceFilePath, sources, _i, _len, _results; sources = fs.readdirSync(sourcePath); mkdirp.sync(destinationPath); _results = []; for (_i = 0, _len = sources.length; _i < _len; _i++) { source = sources[_i]; sourceFilePath = path.join(sourcePath, source); destinationFilePath = path.join(destinationPath, source); if (fsPlus.isDirectorySync(sourceFilePath)) { _results.push(fsPlus.copySync(sourceFilePath, destinationFilePath)); } else { content = fs.readFileSync(sourceFilePath); _results.push(fs.writeFileSync(destinationFilePath, content)); } } return _results; }, makeTreeSync: function(directoryPath) { if (!fsPlus.isDirectorySync(directoryPath)) { return mkdirp.sync(directoryPath); } }, makeTree: function(directoryPath, callback) { return fsPlus.isDirectory(directoryPath, function(exists) { if (exists) { return typeof callback === "function" ? callback() : void 0; } return mkdirp(directoryPath, function(error) { return typeof callback === "function" ? callback(error) : void 0; }); }); }, traverseTreeSync: function(rootPath, onFile, onDirectory) { var traverse; if (onDirectory == null) { onDirectory = onFile; } if (!fsPlus.isDirectorySync(rootPath)) { return; } traverse = function(directoryPath, onFile, onDirectory) { var childPath, file, linkStats, stats, _i, _len, _ref; _ref = fs.readdirSync(directoryPath); for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; childPath = path.join(directoryPath, file); stats = fs.lstatSync(childPath); if (stats.isSymbolicLink()) { if (linkStats = statSyncNoException(childPath)) { stats = linkStats; } } if (stats.isDirectory()) { if (onDirectory(childPath)) { traverse(childPath, onFile, onDirectory); } } else if (stats.isFile()) { onFile(childPath); } } return void 0; }; return traverse(rootPath, onFile, onDirectory); }, traverseTree: function(rootPath, onFile, onDirectory, onDone) { return fs.readdir(rootPath, function(error, files) { var file, queue, _i, _len, _results; if (error) { return typeof onDone === "function" ? onDone() : void 0; } else { queue = async.queue(function(childPath, callback) { return fs.stat(childPath, function(error, stats) { if (error) { return callback(error); } else if (stats.isFile()) { onFile(childPath); return callback(); } else if (stats.isDirectory()) { if (onDirectory(childPath)) { return fs.readdir(childPath, function(error, files) { var file, _i, _len; if (error) { return callback(error); } else { for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; queue.unshift(path.join(childPath, file)); } return callback(); } }); } else { return callback(); } } else { return callback(); } }); }); queue.concurrency = 1; queue.drain = onDone; _results = []; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; _results.push(queue.push(path.join(rootPath, file))); } return _results; } }); }, md5ForPath: function(pathToDigest) { var contents; contents = fs.readFileSync(pathToDigest); return require('crypto').createHash('md5').update(contents).digest('hex'); }, resolve: function() { var args, candidatePath, extensions, loadPath, loadPaths, pathToResolve, resolvedPath, _i, _len, _ref; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; if (_.isArray(_.last(args))) { extensions = args.pop(); } pathToResolve = (_ref = args.pop()) != null ? _ref.toString() : void 0; loadPaths = args; if (!pathToResolve) { return void 0; } if (fsPlus.isAbsolute(pathToResolve)) { if (extensions && (resolvedPath = fsPlus.resolveExtension(pathToResolve, extensions))) { return resolvedPath; } else { if (fsPlus.existsSync(pathToResolve)) { return pathToResolve; } } } for (_i = 0, _len = loadPaths.length; _i < _len; _i++) { loadPath = loadPaths[_i]; candidatePath = path.join(loadPath, pathToResolve); if (extensions) { if (resolvedPath = fsPlus.resolveExtension(candidatePath, extensions)) { return resolvedPath; } } else { if (fsPlus.existsSync(candidatePath)) { return fsPlus.absolute(candidatePath); } } } return void 0; }, resolveOnLoadPath: function() { var args, loadPaths; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; loadPaths = Module.globalPaths.concat(module.paths); return fsPlus.resolve.apply(fsPlus, __slice.call(loadPaths).concat(__slice.call(args))); }, resolveExtension: function(pathToResolve, extensions) { var extension, pathWithExtension, _i, _len; for (_i = 0, _len = extensions.length; _i < _len; _i++) { extension = extensions[_i]; if (extension === "") { if (fsPlus.existsSync(pathToResolve)) { return fsPlus.absolute(pathToResolve); } } else { pathWithExtension = pathToResolve + "." + extension.replace(/^\./, ""); if (fsPlus.existsSync(pathWithExtension)) { return fsPlus.absolute(pathWithExtension); } } } return void 0; }, isCompressedExtension: function(ext) { return COMPRESSED_EXTENSIONS.hasOwnProperty(ext); }, isImageExtension: function(ext) { return IMAGE_EXTENSIONS.hasOwnProperty(ext); }, isPdfExtension: function(ext) { return ext === '.pdf'; }, isBinaryExtension: function(ext) { return BINARY_EXTENSIONS.hasOwnProperty(ext); }, isReadmePath: function(readmePath) { var base, extension; extension = path.extname(readmePath); base = path.basename(readmePath, extension).toLowerCase(); return base === 'readme' && (extension === '' || fsPlus.isMarkdownExtension(extension)); }, isMarkdownExtension: function(ext) { return MARKDOWN_EXTENSIONS.hasOwnProperty(ext); }, isCaseInsensitive: function() { var lowerCaseStat, upperCaseStat; if (fsPlus.caseInsensitiveFs == null) { lowerCaseStat = statSyncNoException(process.execPath.toLowerCase()); upperCaseStat = statSyncNoException(process.execPath.toUpperCase()); if (lowerCaseStat && upperCaseStat) { fsPlus.caseInsensitiveFs = lowerCaseStat.dev === upperCaseStat.dev && lowerCaseStat.ino === upperCaseStat.ino; } else { fsPlus.caseInsensitiveFs = false; } } return fsPlus.caseInsensitiveFs; }, isCaseSensitive: function() { return !fsPlus.isCaseInsensitive(); } }; statSyncNoException = fs.statSyncNoException, lstatSyncNoException = fs.lstatSyncNoException; if (statSyncNoException == null) { statSyncNoException = function() { var args, error; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; try { return fs.statSync.apply(fs, args); } catch (_error) { error = _error; return false; } }; } if (lstatSyncNoException == null) { lstatSyncNoException = function() { var args, error; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; try { return fs.lstatSync.apply(fs, args); } catch (_error) { error = _error; return false; } }; } BINARY_EXTENSIONS = { '.DS_Store': true, '.a': true, '.exe': true, '.o': true, '.pyc': true, '.pyo': true, '.so': true, '.woff': true }; COMPRESSED_EXTENSIONS = { '.bz2': true, '.egg': true, '.epub': true, '.gz': true, '.jar': true, '.lz': true, '.lzma': true, '.lzo': true, '.tar': true, '.tgz': true, '.war': true, '.whl': true, '.xpi': true, '.xz': true, '.z': true, '.zip': true }; IMAGE_EXTENSIONS = { '.gif': true, '.ico': true, '.jpeg': true, '.jpg': true, '.png': true, '.tiff': true, '.webp': true }; MARKDOWN_EXTENSIONS = { '.markdown': true, '.md': true, '.mdown': true, '.mkd': true, '.mkdown': true, '.rmd': true, '.ron': true }; isPathValid = function(pathToCheck) { return (pathToCheck != null) && typeof pathToCheck === 'string' && pathToCheck.length > 0; }; isMoveTargetValid = function(source, target, callback) { return fs.stat(source, function(oldErr, oldStat) { if (oldErr) { callback(oldErr); return; } return fs.stat(target, function(newErr, newStat) { if (newErr && newErr.code === 'ENOENT') { callback(void 0, true); return; } return callback(void 0, source.toLowerCase() === target.toLowerCase() && oldStat.dev === newStat.dev && oldStat.ino === newStat.ino); }); }); }; isMoveTargetValidSync = function(source, target) { var newStat, oldStat; oldStat = statSyncNoException(source); newStat = statSyncNoException(target); if (!(oldStat && newStat)) { return true; } return source.toLowerCase() === target.toLowerCase() && oldStat.dev === newStat.dev && oldStat.ino === newStat.ino; }; module.exports = _.extend({}, fs, fsPlus); }).call(this);
nlhuykhang/atom-config
packages/minimap/node_modules/fs-plus/lib/fs-plus.js
JavaScript
mit
20,254
//// [moduleElementsInWrongContext2.ts] function blah () { module M { } export namespace N { export interface I { } } namespace Q.K { } declare module "ambient" { } export = M; var v; function foo() { } export * from "ambient"; export { foo }; export { baz as b } from "ambient"; export default v; export default class C { } export function bee() { } import I = M; import I2 = require("foo"); import * as Foo from "ambient"; import bar from "ambient"; import { baz } from "ambient"; import "ambient"; } //// [moduleElementsInWrongContext2.js] function blah() { var v; function foo() { } __export(require("ambient")); exports["default"] = v; var C = (function () { function C() { } return C; })(); exports["default"] = C; function bee() { } exports.bee = bee; }
progre/TypeScript
tests/baselines/reference/moduleElementsInWrongContext2.js
JavaScript
apache-2.0
938
(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(_dereq_,module,exports){ var Core = _dereq_('./core'), CollectionGroup = _dereq_('../lib/CollectionGroup'), View = _dereq_('../lib/View'), Highchart = _dereq_('../lib/Highchart'), Persist = _dereq_('../lib/Persist'), Document = _dereq_('../lib/Document'), Overview = _dereq_('../lib/Overview'), Grid = _dereq_('../lib/Grid'), Rest = _dereq_('../lib/Rest'), Odm = _dereq_('../lib/Odm'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/CollectionGroup":6,"../lib/Document":10,"../lib/Grid":11,"../lib/Highchart":12,"../lib/Odm":27,"../lib/Overview":30,"../lib/Persist":32,"../lib/Rest":36,"../lib/View":40,"./core":2}],2:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":7,"../lib/Shim.IE8":39}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { var sortKey; this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; for (sortKey in orderBy) { if (orderBy.hasOwnProperty(sortKey)) { this._keyArr.push({ key: sortKey, dir: orderBy[sortKey] }); } } }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof obj[sortType.key]; if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.dir === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.dir === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += obj[sortType.key]; } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Shared":38}],4:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) { this._store = []; this._keys = []; if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { // Convert the index object to an array of key val objects this.keys(this.extractKeys(index)); } return this.$super.call(this, index); }); BinaryTree.prototype.extractKeys = function (obj) { var i, keys = []; for (i in obj) { if (obj.hasOwnProperty(i)) { keys.push({ key: i, val: obj[i] }); } } return keys; }; BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.val === 1) { result = this.sortAsc(a[indexData.key], b[indexData.key]); } else if (indexData.val === -1) { result = this.sortDesc(a[indexData.key], b[indexData.key]); } if (result !== 0) { return result; } } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.key]; } return hash;*/ return obj[this._keys[0].key]; }; BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (!this._data) { // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } if (result === -1) { // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } if (result === 1) { // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } return false; }; BinaryTree.prototype.lookup = function (data, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, resultArr); } } return resultArr; }; BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ BinaryTree.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(), indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = pathSolver.parseArr(this._index, { verbose: true }); queryArr = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":31,"./Shared":38}],5:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc, Overload, ReactorIO; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', keyName, {oldData: oldKey}); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = this.jStringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: updated }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Array} The items that were updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update); }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback(false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Array} An array of documents that were removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj); }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length) { if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } } // Check if all queues are complete if (!this.isProcessingQueue()) { this.emit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); self.chainSend('insert', doc, {index: index}); //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = this.jStringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = this.jStringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.apply(this, arguments); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; options = this.options(options); var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, //renameFieldMethod, //renameFieldPath, matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatch[joinMatchIndex].query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatch[joinMatchIndex].query; joinSearchQuery = self._resolveDynamicQuery(joinMatch[joinMatchIndex].query, resultArr[resultIndex]); } if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatch[joinMatchIndex]; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = new Path(query.substr(3, query.length - 3)).value(item); } else { pathResult = new Path(query).value(item); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } }; /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } }; /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; } // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pm])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var name = options.name; if (name) { if (!this._collection[name]) { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":8,"./IndexBinaryTree":13,"./IndexHashMap":14,"./KeyValueStore":15,"./Metrics":16,"./Overload":29,"./Path":31,"./ReactorIO":35,"./Shared":38}],6:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {Name=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { // Handle being passed an instance if (collectionGroupName instanceof CollectionGroup) { return collectionGroupName; } this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":5,"./Shared":38}],7:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = function () { return this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":9,"./Metrics.js":16,"./Overload":29,"./Shared":38}],8:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],9:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":16,"./Overload":29,"./Shared":38}],10:[function(_dereq_,module,exports){ "use strict"; // TODO: Remove the _update* methods because we are already mixing them // TODO: in now via Mixin.Updating and update autobind to extend the _update* // TODO: methods like we already do with collection var Shared, Collection, Db; Shared = _dereq_('./Shared'); /** * Creates a new Document instance. Documents allow you to create individual * objects that can have standard ForerunnerDB CRUD operations run against * them, as well as data-binding if the AutoBind module is included in your * project. * @name Document * @class Document * @constructor */ var FdbDocument = function () { this.init.apply(this, arguments); }; FdbDocument.prototype.init = function (name) { this._name = name; this._data = {}; }; Shared.addModule('Document', FdbDocument); Shared.mixin(FdbDocument.prototype, 'Mixin.Common'); Shared.mixin(FdbDocument.prototype, 'Mixin.Events'); Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor'); Shared.mixin(FdbDocument.prototype, 'Mixin.Constants'); Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers'); Shared.mixin(FdbDocument.prototype, 'Mixin.Matching'); Shared.mixin(FdbDocument.prototype, 'Mixin.Updating'); Shared.mixin(FdbDocument.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @func state * @memberof Document * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'state'); /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Document * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'db'); /** * Gets / sets the document name. * @func name * @memberof Document * @param {String=} val The name to assign * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'name'); /** * Sets the data for the document. * @func setData * @memberof Document * @param data * @param options * @returns {Document} */ FdbDocument.prototype.setData = function (data, options) { var i, $unset; if (data) { options = options || { $decouple: true }; if (options && options.$decouple === true) { data = this.decouple(data); } if (this._linked) { $unset = {}; // Remove keys that don't exist in the new data from the current object for (i in this._data) { if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) { // Check if existing data has key if (data[i] === undefined) { // Add property name to those to unset $unset[i] = 1; } } } data.$unset = $unset; // Now update the object with new data this.updateObject(this._data, data, {}); } else { // Straight data assignment this._data = data; } this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)}); } return this; }; /** * Gets the document's data returned as a single object. * @func find * @memberof Document * @param {Object} query The query object - currently unused, just * provide a blank object e.g. {} * @param {Object=} options An options object. * @returns {Object} The document's data object. */ FdbDocument.prototype.find = function (query, options) { var result; if (options && options.$decouple === false) { result = this._data; } else { result = this.decouple(this._data); } return result; }; /** * Modifies the document. This will update the document with the data held in 'update'. * @func update * @memberof Document * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ FdbDocument.prototype.update = function (query, update, options) { var result = this.updateObject(this._data, update, query, options); if (result) { this.deferEmit('change', {type: 'update', data: this.decouple(this._data)}); } }; /** * Internal method for document updating. * @func updateObject * @memberof Document * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ FdbDocument.prototype.updateObject = Collection.prototype.updateObject; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @func _isPositionalKey * @memberof Document * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ FdbDocument.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Updates a property on an object depending on if the collection is * currently running data-binding or not. * @func _updateProperty * @memberof Document * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ FdbDocument.prototype._updateProperty = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, val); if (this.debug()) { console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"'); } } else { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } } }; /** * Increments a value for a property on a document by the passed number. * @func _updateIncrement * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ FdbDocument.prototype._updateIncrement = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] + val); } else { doc[prop] += val; } }; /** * Changes the index of an item in the passed array. * @func _updateSpliceMove * @memberof Document * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) { if (this._linked) { window.jQuery.observable(arr).move(indexFrom, indexTo); if (this.debug()) { console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } } else { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } } }; /** * Inserts an item into the passed array at the specified index. * @func _updateSplicePush * @memberof Document * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updateSplicePush = function (arr, index, doc) { if (arr.length > index) { if (this._linked) { window.jQuery.observable(arr).insert(index, doc); } else { arr.splice(index, 0, doc); } } else { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } } }; /** * Inserts an item at the end of an array. * @func _updatePush * @memberof Document * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updatePush = function (arr, doc) { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } }; /** * Removes an item from the passed array. * @func _updatePull * @memberof Document * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ FdbDocument.prototype._updatePull = function (arr, index) { if (this._linked) { window.jQuery.observable(arr).remove(index); } else { arr.splice(index, 1); } }; /** * Multiplies a value for a property on a document by the passed number. * @func _updateMultiply * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ FdbDocument.prototype._updateMultiply = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] * val); } else { doc[prop] *= val; } }; /** * Renames a property on a document to the passed property. * @func _updateRename * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ FdbDocument.prototype._updateRename = function (doc, prop, val) { var existingVal = doc[prop]; if (this._linked) { window.jQuery.observable(doc).setProperty(val, existingVal); window.jQuery.observable(doc).removeProperty(prop); } else { doc[val] = existingVal; delete doc[prop]; } }; /** * Deletes a property on a document. * @func _updateUnset * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ FdbDocument.prototype._updateUnset = function (doc, prop) { if (this._linked) { window.jQuery.observable(doc).removeProperty(prop); } else { delete doc[prop]; } }; /** * Drops the document. * @func drop * @memberof Document * @returns {boolean} True if successful, false if not. */ FdbDocument.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._db && this._name) { if (this._db && this._db._document && this._db._document[this._name]) { this._state = 'dropped'; delete this._db._document[this._name]; delete this._data; this.emit('drop', this); if (callback) { callback(false, true); } return true; } } } else { return true; } return false; }; /** * Creates a new document instance. * @func document * @memberof Db * @param {String} documentName The name of the document to create. * @returns {*} */ Db.prototype.document = function (documentName) { if (documentName) { // Handle being passed an instance if (documentName instanceof FdbDocument) { if (documentName.state() !== 'droppped') { return documentName; } else { documentName = documentName.name(); } } this._document = this._document || {}; this._document[documentName] = this._document[documentName] || new FdbDocument(documentName).db(this); return this._document[documentName]; } else { // Return an object of document data return this._document; } }; /** * Returns an array of documents the DB currently has. * @func documents * @memberof Db * @returns {Array} An array of objects containing details of each document * the database is currently managing. */ Db.prototype.documents = function () { var arr = [], item, i; for (i in this._document) { if (this._document.hasOwnProperty(i)) { item = this._document[i]; arr.push({ name: i, linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Document'); module.exports = FdbDocument; },{"./Collection":5,"./Shared":38}],11:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, View, CollectionInit, DbInit, ReactorIO; //Shared = ForerunnerDB.shared; Shared = _dereq_('./Shared'); /** * Creates a new grid instance. * @name Grid * @class Grid * @param {String} selector jQuery selector. * @param {String} template The template selector. * @param {Object=} options The options object to apply to the grid. * @constructor */ var Grid = function (selector, template, options) { this.init.apply(this, arguments); }; Grid.prototype.init = function (selector, template, options) { var self = this; this._selector = selector; this._template = template; this._options = options || {}; this._debug = {}; this._id = this.objectId(); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; }; Shared.addModule('Grid', Grid); Shared.mixin(Grid.prototype, 'Mixin.Common'); Shared.mixin(Grid.prototype, 'Mixin.ChainReactor'); Shared.mixin(Grid.prototype, 'Mixin.Constants'); Shared.mixin(Grid.prototype, 'Mixin.Triggers'); Shared.mixin(Grid.prototype, 'Mixin.Events'); Shared.mixin(Grid.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); View = _dereq_('./View'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @func state * @memberof Grid * @param {String=} val The name of the state to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'state'); /** * Gets / sets the current name. * @func name * @memberof Grid * @param {String=} val The name to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'name'); /** * Executes an insert against the grid's underlying data-source. * @func insert * @memberof Grid */ Grid.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the grid's underlying data-source. * @func update * @memberof Grid */ Grid.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the grid's underlying data-source. * @func updateById * @memberof Grid */ Grid.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the grid's underlying data-source. * @func remove * @memberof Grid */ Grid.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Sets the collection from which the grid will assemble its data. * @func from * @memberof Grid * @param {Collection} collection The collection to use to assemble grid data. * @returns {Grid} */ Grid.prototype.from = function (collection) { //var self = this; if (collection !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); } if (typeof(collection) === 'string') { collection = this._db.collection(collection); } this._from = collection; this._from.on('drop', this._collectionDroppedWrap); this.refresh(); } return this; }; /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Grid * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Grid.prototype, 'db', function (db) { if (db) { // Apply the same debug settings this.debug(db.debug()); } return this.$super.apply(this, arguments); }); Grid.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from grid delete this._from; } }; /** * Drops a grid and all it's stored data from the database. * @func drop * @memberof Grid * @returns {boolean} True on success, false on failure. */ Grid.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { // Remove data-binding this._from.unlink(this._selector, this.template()); // Kill listeners and references this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping grid ' + this._selector); } this._state = 'dropped'; if (this._db && this._selector) { delete this._db._grid[this._selector]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._selector; delete this._template; delete this._from; delete this._db; return true; } } else { return true; } return false; }; /** * Gets / sets the grid's HTML template to use when rendering. * @func template * @memberof Grid * @param {Selector} template The template's jQuery selector. * @returns {*} */ Grid.prototype.template = function (template) { if (template !== undefined) { this._template = template; return this; } return this._template; }; Grid.prototype._sortGridClick = function (e) { var elem = window.jQuery(e.currentTarget), sortColText = elem.attr('data-grid-sort') || '', sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1, sortCols = sortColText.split(','), sortObj = {}, i; // Remove all grid sort tags from the grid window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir'); // Flip the sort direction elem.attr('data-grid-dir', sortColDir); for (i = 0; i < sortCols.length; i++) { sortObj[sortCols] = sortColDir; } Shared.mixin(sortObj, this._options.$orderBy); this._from.orderBy(sortObj); this.emit('sort', sortObj); }; /** * Refreshes the grid data such as ordering etc. * @func refresh * @memberof Grid */ Grid.prototype.refresh = function () { if (this._from) { if (this._from.link) { var self = this, elem = window.jQuery(this._selector), sortClickListener = function () { self._sortGridClick.apply(self, arguments); }; // Clear the container elem.html(''); if (self._from.orderBy) { // Remove listeners elem.off('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Remove listeners elem.off('click', '[data-grid-filter]', sortClickListener ); } // Set wrap name if none is provided self._options.$wrap = self._options.$wrap || 'gridRow'; // Auto-bind the data to the grid template self._from.link(self._selector, self.template(), self._options); // Check if the data source (collection or view) has an // orderBy method (usually only views) and if so activate // the sorting system if (self._from.orderBy) { // Listen for sort requests elem.on('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Listen for filter requests var queryObj = {}; elem.find('[data-grid-filter]').each(function (index, filterElem) { filterElem = window.jQuery(filterElem); var filterField = filterElem.attr('data-grid-filter'), filterVarType = filterElem.attr('data-grid-vartype'), filterSort = {}, title = filterElem.html(), dropDownButton, dropDownMenu, template, filterQuery, filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField); filterSort[filterField] = 1; filterQuery = { $distinct: filterSort }; filterView .query(filterQuery) .orderBy(filterSort) .from(self._from._from); template = [ '<div class="dropdown" id="' + self._id + '_' + filterField + '">', '<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">', title + ' <span class="caret"></span>', '</button>', '</div>' ]; dropDownButton = window.jQuery(template.join('')); dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>'); dropDownButton.append(dropDownMenu); filterElem.html(dropDownButton); // Data-link the underlying data to the grid filter drop-down filterView.link(dropDownMenu, { template: [ '<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">', '<input type="search" class="form-control gridFilterSearch" placeholder="Search...">', '<span class="input-group-btn">', '<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>', '</span>', '</li>', '<li role="presentation" class="divider"></li>', '<li role="presentation" data-val="$all">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox" checked>&nbsp;All', '</a>', '</li>', '<li role="presentation" class="divider"></li>', '{^{for options}}', '<li role="presentation" data-link="data-val{:' + filterField + '}">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox">&nbsp;{^{:' + filterField + '}}', '</a>', '</li>', '{{/for}}' ].join('') }, { $wrap: 'options' }); elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) { var elem = window.jQuery(this), query = filterView.query(), search = elem.val(); if (search) { query[filterField] = new RegExp(search, 'gi'); } else { delete query[filterField]; } filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) { // Clear search text box window.jQuery(this).parents('li').find('.gridFilterSearch').val(''); // Clear view query var query = filterView.query(); delete query[filterField]; filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) { e.stopPropagation(); var fieldValue, elem = $(this), checkbox = elem.find('input[type="checkbox"]'), checked, addMode = true, fieldInArr, liElem, i; // If the checkbox is not the one clicked on if (!window.jQuery(e.target).is('input')) { // Set checkbox to opposite of current value checkbox.prop('checked', !checkbox.prop('checked')); checked = checkbox.is(':checked'); } else { checkbox.prop('checked', checkbox.prop('checked')); checked = checkbox.is(':checked'); } liElem = window.jQuery(this); fieldValue = liElem.attr('data-val'); // Check if the selection is the "all" option if (fieldValue === '$all') { // Remove the field from the query delete queryObj[filterField]; // Clear all other checkboxes liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false); } else { // Clear the "all" checkbox liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false); // Check if the type needs casting switch (filterVarType) { case 'integer': fieldValue = parseInt(fieldValue, 10); break; case 'float': fieldValue = parseFloat(fieldValue); break; default: } // Check if the item exists already queryObj[filterField] = queryObj[filterField] || { $in: [] }; fieldInArr = queryObj[filterField].$in; for (i = 0; i < fieldInArr.length; i++) { if (fieldInArr[i] === fieldValue) { // Item already exists if (checked === false) { // Remove the item fieldInArr.splice(i, 1); } addMode = false; break; } } if (addMode && checked) { fieldInArr.push(fieldValue); } if (!fieldInArr.length) { // Remove the field from the query delete queryObj[filterField]; } } // Set the view query self._from.queryData(queryObj); if (self._from.pageFirst) { self._from.pageFirst(); } }); }); } self.emit('refresh'); } else { throw('Grid requires the AutoBind module in order to operate!'); } } return this; }; /** * Returns the number of documents currently in the grid. * @func count * @memberof Grid * @returns {Number} */ Grid.prototype.count = function () { return this._from.count(); }; /** * Creates a grid and assigns the collection as its data source. * @func grid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.grid = View.prototype.grid = function (selector, template, options) { if (this._db && this._db._grid ) { if (selector !== undefined) { if (template !== undefined) { if (!this._db._grid[selector]) { var grid = new Grid(selector, template, options) .db(this._db) .from(this); this._grid = this._grid || []; this._grid.push(grid); this._db._grid[selector] = grid; return grid; } else { throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector); } } return this._db._grid[selector]; } return this._db._grid; } }; /** * Removes a grid safely from the DOM. Must be called when grid is * no longer required / is being removed from DOM otherwise references * will stick around and cause memory leaks. * @func unGrid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) { var i, grid; if (this._db && this._db._grid ) { if (selector && template) { if (this._db._grid[selector]) { grid = this._db._grid[selector]; delete this._db._grid[selector]; return grid.drop(); } else { throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name); } } else { // No parameters passed, remove all grids from this module for (i in this._db._grid) { if (this._db._grid.hasOwnProperty(i)) { grid = this._db._grid[i]; delete this._db._grid[i]; grid.drop(); if (this.debug()) { console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"'); } } } this._db._grid = {}; } } }; /** * Adds a grid to the internal grid lookup. * @func _addGrid * @memberof Collection * @param {Grid} grid The grid to add. * @returns {Collection} * @private */ Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) { if (grid !== undefined) { this._grid = this._grid || []; this._grid.push(grid); } return this; }; /** * Removes a grid from the internal grid lookup. * @func _removeGrid * @memberof Collection * @param {Grid} grid The grid to remove. * @returns {Collection} * @private */ Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) { if (grid !== undefined && this._grid) { var index = this._grid.indexOf(grid); if (index > -1) { this._grid.splice(index, 1); } } return this; }; // Extend DB with grids init Db.prototype.init = function () { this._grid = {}; DbInit.apply(this, arguments); }; /** * Determine if a grid with the passed name already exists. * @func gridExists * @memberof Db * @param {String} selector The jQuery selector to bind the grid to. * @returns {boolean} */ Db.prototype.gridExists = function (selector) { return Boolean(this._grid[selector]); }; /** * Creates a grid based on the passed arguments. * @func grid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.grid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Removes a grid based on the passed arguments. * @func unGrid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.unGrid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Returns an array of grids the DB currently has. * @func grids * @memberof Db * @returns {Array} An array of objects containing details of each grid * the database is currently managing. */ Db.prototype.grids = function () { var arr = [], item, i; for (i in this._grid) { if (this._grid.hasOwnProperty(i)) { item = this._grid[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Grid'); module.exports = Grid; },{"./Collection":5,"./CollectionGroup":6,"./ReactorIO":35,"./Shared":38,"./View":40}],12:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Collection, CollectionInit, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The constructor. * * @constructor */ var Highchart = function (collection, options) { this.init.apply(this, arguments); }; Highchart.prototype.init = function (collection, options) { this._options = options; this._selector = window.jQuery(this._options.selector); if (!this._selector[0]) { throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector); } this._listeners = {}; this._collection = collection; // Setup the chart this._options.series = []; // Disable attribution on highcharts options.chartOptions = options.chartOptions || {}; options.chartOptions.credits = false; // Set the data for the chart var data, seriesObj, chartData; switch (this._options.type) { case 'pie': // Create chart from data this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); // Generate graph data from collection data data = this._collection.find(); seriesObj = { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)', style: { color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black' } } }; chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField); window.jQuery.extend(seriesObj, this._options.seriesOptions); window.jQuery.extend(seriesObj, { name: this._options.seriesName, data: chartData }); this._chart.addSeries(seriesObj, true, true); break; case 'line': case 'area': case 'column': case 'bar': // Generate graph data from collection data chartData = this.seriesDataFromCollectionData( this._options.seriesField, this._options.keyField, this._options.valField, this._options.orderBy, this._options ); this._options.chartOptions.xAxis = chartData.xAxis; this._options.chartOptions.series = chartData.series; this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); break; default: throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type); } // Hook the collection events to auto-update the chart this._hookEvents(); }; Shared.addModule('Highchart', Highchart); Collection = Shared.modules.Collection; CollectionInit = Collection.prototype.init; Shared.mixin(Highchart.prototype, 'Mixin.Common'); Shared.mixin(Highchart.prototype, 'Mixin.Events'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Highchart.prototype, 'state'); /** * Generate pie-chart series data from the given collection data array. * @param data * @param keyField * @param valField * @returns {Array} */ Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) { var graphData = [], i; for (i = 0; i < data.length; i++) { graphData.push([data[i][keyField], data[i][valField]]); } return graphData; }; /** * Generate line-chart series data from the given collection data array. * @param seriesField * @param keyField * @param valField * @param orderBy */ Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy, options) { var data = this._collection.distinct(seriesField), seriesData = [], xAxis = options && options.chartOptions && options.chartOptions.xAxis ? options.chartOptions.xAxis : { categories: [] }, seriesName, query, dataSearch, seriesValues, sData, i, k; // What we WANT to output: /*series: [{ name: 'Responses', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] }]*/ // Loop keys for (i = 0; i < data.length; i++) { seriesName = data[i]; query = {}; query[seriesField] = seriesName; seriesValues = []; dataSearch = this._collection.find(query, { orderBy: orderBy }); // Loop the keySearch data and grab the value for each item for (k = 0; k < dataSearch.length; k++) { if (xAxis.categories) { xAxis.categories.push(dataSearch[k][keyField]); seriesValues.push(dataSearch[k][valField]); } else { seriesValues.push([dataSearch[k][keyField], dataSearch[k][valField]]); } } sData = { name: seriesName, data: seriesValues }; if (options.seriesOptions) { for (k in options.seriesOptions) { if (options.seriesOptions.hasOwnProperty(k)) { sData[k] = options.seriesOptions[k]; } } } seriesData.push(sData); } return { xAxis: xAxis, series: seriesData }; }; /** * Hook the events the chart needs to know about from the internal collection. * @private */ Highchart.prototype._hookEvents = function () { var self = this; self._collection.on('change', function () { self._changeListener.apply(self, arguments); }); // If the collection is dropped, clean up after ourselves self._collection.on('drop', function () { self.drop.apply(self); }); }; /** * Handles changes to the collection data that the chart is reading from and then * updates the data in the chart display. * @private */ Highchart.prototype._changeListener = function () { var self = this; // Update the series data on the chart if (typeof self._collection !== 'undefined' && self._chart) { var data = self._collection.find(), i; switch (self._options.type) { case 'pie': self._chart.series[0].setData( self.pieDataFromCollectionData( data, self._options.keyField, self._options.valField ), true, true ); break; case 'bar': case 'line': case 'area': case 'column': var seriesData = self.seriesDataFromCollectionData( self._options.seriesField, self._options.keyField, self._options.valField, self._options.orderBy, self._options ); if (seriesData.xAxis.categories) { self._chart.xAxis[0].setCategories( seriesData.xAxis.categories ); } for (i = 0; i < seriesData.series.length; i++) { if (self._chart.series[i]) { // Series exists, set it's data self._chart.series[i].setData( seriesData.series[i].data, true, true ); } else { // Series data does not yet exist, add a new series self._chart.addSeries( seriesData.series[i], true, true ); } } break; default: break; } } }; /** * Destroys the chart and all internal references. * @returns {Boolean} */ Highchart.prototype.drop = function (callback) { if (!this.isDropped()) { this._state = 'dropped'; if (this._chart) { this._chart.destroy(); } if (this._collection) { this._collection.off('change', this._changeListener); this._collection.off('drop', this.drop); if (this._collection._highcharts) { delete this._collection._highcharts[this._options.selector]; } } delete this._chart; delete this._options; delete this._collection; this.emit('drop', this); if (callback) { callback(false, true); } return true; } else { return true; } }; // Extend collection with highchart init Collection.prototype.init = function () { this._highcharts = {}; CollectionInit.apply(this, arguments); }; /** * Creates a pie chart from the collection. * @type {Overload} */ Collection.prototype.pieChart = new Overload({ /** * Chart via options object. * @func pieChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'pie'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'pie'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func pieChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {String} seriesName The name of the series to display on the chart. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) { options = options || {}; options.selector = selector; options.keyField = keyField; options.valField = valField; options.seriesName = seriesName; // Call the main chart method this.pieChart(options); } }); /** * Creates a line chart from the collection. * @type {Overload} */ Collection.prototype.lineChart = new Overload({ /** * Chart via selector. * @func lineChart * @memberof Highchart * @param {String} selector The chart selector. * @returns {*} */ 'string': function (selector) { return this._highcharts[selector]; }, /** * Chart via options object. * @func lineChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'line'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'line'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func lineChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.lineChart(options); } }); /** * Creates an area chart from the collection. * @type {Overload} */ Collection.prototype.areaChart = new Overload({ /** * Chart via options object. * @func areaChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'area'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'area'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func areaChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.areaChart(options); } }); /** * Creates a column chart from the collection. * @type {Overload} */ Collection.prototype.columnChart = new Overload({ /** * Chart via options object. * @func columnChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'column'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'column'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func columnChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.columnChart(options); } }); /** * Creates a bar chart from the collection. * @type {Overload} */ Collection.prototype.barChart = new Overload({ /** * Chart via options object. * @func barChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func barChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.barChart(options); } }); /** * Creates a stacked bar chart from the collection. * @type {Overload} */ Collection.prototype.stackedBarChart = new Overload({ /** * Chart via options object. * @func stackedBarChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; options.plotOptions = options.plotOptions || {}; options.plotOptions.series = options.plotOptions.series || {}; options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func stackedBarChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.stackedBarChart(options); } }); /** * Removes a chart from the page by it's selector. * @memberof Collection * @param {String} selector The chart selector. */ Collection.prototype.dropChart = function (selector) { if (this._highcharts && this._highcharts[selector]) { this._highcharts[selector].drop(); } }; Shared.finishModule('Highchart'); module.exports = Highchart; },{"./Overload":29,"./Shared":38}],13:[function(_dereq_,module,exports){ "use strict"; /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), treeInstance = new BinaryTree(), btree = function () {}; treeInstance.inOrder('hash'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree = new (btree.create(2, this.sortAsc))(); if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":4,"./Path":31,"./Shared":38}],14:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":31,"./Shared":38}],15:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":38}],16:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":28,"./Shared":38}],17:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],18:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } arrItem.chainReceive(this, type, data, options); } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],19:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined) { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return serialiser.parse(data); //return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return serialiser.stringify(data); //return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":29,"./Serialiser":37}],20:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":29}],22:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check we have a database object to work from if (!this.db()) { throw('Cannot operate a ' + key + ' sub-query on an anonymous collection (one with no db set)!'); } // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; } }; module.exports = Matching; },{}],23:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],24:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],25:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":29}],26:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],27:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Collection; Shared = _dereq_('./Shared'); var Odm = function () { this.init.apply(this, arguments); }; Odm.prototype.init = function (from, name) { var self = this; self.name(name); self._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; self.from(from); }; Shared.addModule('Odm', Odm); Shared.mixin(Odm.prototype, 'Mixin.Common'); Shared.mixin(Odm.prototype, 'Mixin.ChainReactor'); Shared.mixin(Odm.prototype, 'Mixin.Constants'); Shared.mixin(Odm.prototype, 'Mixin.Events'); Collection = _dereq_('./Collection'); Shared.synthesize(Odm.prototype, 'name'); Shared.synthesize(Odm.prototype, 'state'); Shared.synthesize(Odm.prototype, 'parent'); Shared.synthesize(Odm.prototype, 'query'); Shared.synthesize(Odm.prototype, 'from', function (val) { if (val !== undefined) { val.chain(this); val.on('drop', this._collectionDroppedWrap); } return this.$super(val); }); Odm.prototype._collectionDropped = function (collection) { this.drop(); }; Odm.prototype._chainHandler = function (chainPacket) { switch (chainPacket.type) { case 'setData': case 'insert': case 'update': case 'remove': //this._refresh(); break; default: break; } }; Odm.prototype.drop = function () { if (!this.isDropped()) { this.state('dropped'); this.emit('drop', this); if (this._from) { delete this._from._odm; } delete this._name; } return true; }; /** * Queries the current object and returns a result that can * also be queried in the same way. * @param {String} prop The property to delve into. * @param {Object=} query Optional query that limits the returned documents. * @returns {Odm} */ Odm.prototype.$ = function (prop, query) { var data, tmpQuery, tmpColl, tmpOdm; if (prop === this._from.primaryKey()) { // Query is against a specific PK id tmpQuery = {}; tmpQuery[prop] = query; data = this._from.find(tmpQuery, {$decouple: false}); tmpColl = new Collection(); tmpColl.setData(data, {$decouple: false}); tmpColl._linked = this._from._linked; } else { // Query is against an array of sub-documents tmpColl = new Collection(); data = this._from.find({}, {$decouple: false}); if (data[0] && data[0][prop]) { // Set the temp collection data to the array property tmpColl.setData(data[0][prop], {$decouple: false}); // Check if we need to filter this array further if (query) { data = tmpColl.find(query, {$decouple: false}); tmpColl.setData(data, {$decouple: false}); } } tmpColl._linked = this._from._linked; } tmpOdm = new Odm(tmpColl); tmpOdm.parent(this); tmpOdm.query(query); return tmpOdm; }; /** * Gets / sets a property on the current ODM document. * @param {String} prop The name of the property. * @param {*} val Optional value to set. * @returns {*} */ Odm.prototype.prop = function (prop, val) { var tmpQuery; if (prop !== undefined) { if (val !== undefined) { tmpQuery = {}; tmpQuery[prop] = val; return this._from.update({}, tmpQuery); } if (this._from._data[0]) { return this._from._data[0][prop]; } } return undefined; }; /** * Get the ODM instance for this collection. * @returns {Odm} */ Collection.prototype.odm = function (name) { if (!this._odm) { this._odm = new Odm(this, name); } return this._odm; }; Shared.finishModule('Odm'); module.exports = Odm; },{"./Collection":5,"./Shared":38}],28:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":31,"./Shared":38}],29:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload: ', def); throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],30:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, DbDocument; Shared = _dereq_('./Shared'); var Overview = function () { this.init.apply(this, arguments); }; Overview.prototype.init = function (name) { var self = this; this._name = name; this._data = new DbDocument('__FDB__dc_data_' + this._name); this._collData = new Collection(); this._sources = []; this._sourceDroppedWrap = function () { self._sourceDropped.apply(self, arguments); }; }; Shared.addModule('Overview', Overview); Shared.mixin(Overview.prototype, 'Mixin.Common'); Shared.mixin(Overview.prototype, 'Mixin.ChainReactor'); Shared.mixin(Overview.prototype, 'Mixin.Constants'); Shared.mixin(Overview.prototype, 'Mixin.Triggers'); Shared.mixin(Overview.prototype, 'Mixin.Events'); Shared.mixin(Overview.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); DbDocument = _dereq_('./Document'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Overview.prototype, 'state'); Shared.synthesize(Overview.prototype, 'db'); Shared.synthesize(Overview.prototype, 'name'); Shared.synthesize(Overview.prototype, 'query', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'queryOptions', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'reduce', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Overview.prototype.from = function (source) { if (source !== undefined) { if (typeof(source) === 'string') { source = this._db.collection(source); } this._setFrom(source); return this; } return this._sources; }; Overview.prototype.find = function () { return this._collData.find.apply(this._collData, arguments); }; /** * Executes and returns the response from the current reduce method * assigned to the overview. * @returns {*} */ Overview.prototype.exec = function () { var reduceFunc = this.reduce(); return reduceFunc ? reduceFunc.apply(this) : undefined; }; Overview.prototype.count = function () { return this._collData.count.apply(this._collData, arguments); }; Overview.prototype._setFrom = function (source) { // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } this._addSource(source); return this; }; Overview.prototype._addSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } if (this._sources.indexOf(source) === -1) { this._sources.push(source); source.chain(this); source.on('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._removeSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } var sourceIndex = this._sources.indexOf(source); if (sourceIndex > -1) { this._sources.splice(source, 1); source.unChain(this); source.off('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._sourceDropped = function (source) { if (source) { // Source was dropped, remove from overview this._removeSource(source); } }; Overview.prototype._refresh = function () { if (!this.isDropped()) { if (this._sources && this._sources[0]) { this._collData.primaryKey(this._sources[0].primaryKey()); var tempArr = [], i; for (i = 0; i < this._sources.length; i++) { tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions)); } this._collData.setData(tempArr); } // Now execute the reduce method if (this._reduce) { var reducedData = this._reduce.apply(this); // Update the document with the newly returned data this._data.setData(reducedData); } } }; Overview.prototype._chainHandler = function (chainPacket) { switch (chainPacket.type) { case 'setData': case 'insert': case 'update': case 'remove': this._refresh(); break; default: break; } }; /** * Gets the module's internal data collection. * @returns {Collection} */ Overview.prototype.data = function () { return this._data; }; Overview.prototype.drop = function (callback) { if (!this.isDropped()) { this._state = 'dropped'; delete this._data; delete this._collData; // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } delete this._sources; if (this._db && this._name) { delete this._db._overview[this._name]; } delete this._name; this.emit('drop', this); if (callback) { callback(false, true); } } return true; }; Db.prototype.overview = function (overviewName) { if (overviewName) { // Handle being passed an instance if (overviewName instanceof Overview) { return overviewName; } this._overview = this._overview || {}; this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this); return this._overview[overviewName]; } else { // Return an object of collection data return this._overview || {}; } }; /** * Returns an array of overviews the DB currently has. * @returns {Array} An array of objects containing details of each overview * the database is currently managing. */ Db.prototype.overviews = function () { var arr = [], item, i; for (i in this._overview) { if (this._overview.hasOwnProperty(i)) { item = this._overview[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Overview'); module.exports = Overview; },{"./Collection":5,"./Document":10,"./Shared":38}],31:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; Path.prototype.valueOne = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.valueOne(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":38}],32:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared = _dereq_('./Shared'), async = _dereq_('async'), localforage = _dereq_('localforage'), FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line Db, Collection, CollectionDrop, CollectionGroup, CollectionInit, DbInit, DbDrop, Persist, Overload;//, //DataVersion = '2.0'; /** * The persistent storage class handles loading and saving data to browser * storage. * @constructor */ Persist = function () { this.init.apply(this, arguments); }; /** * The local forage library. */ Persist.prototype.localforage = localforage; /** * The init method that can be overridden or extended. * @param {Db} db The ForerunnerDB database instance. */ Persist.prototype.init = function (db) { var self = this; this._encodeSteps = [ function () { return self._encode.apply(self, arguments); } ]; this._decodeSteps = [ function () { return self._decode.apply(self, arguments); } ]; // Check environment if (db.isClient()) { if (window.Storage !== undefined) { this.mode('localforage'); localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE ], name: String(db.core().name()), storeName: 'FDB' }); } } }; Shared.addModule('Persist', Persist); Shared.mixin(Persist.prototype, 'Mixin.ChainReactor'); Shared.mixin(Persist.prototype, 'Mixin.Common'); Db = Shared.modules.Db; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; DbDrop = Db.prototype.drop; Overload = Shared.overload; /** * Gets / sets the persistent storage mode (the library used * to persist data to the browser - defaults to localForage). * @param {String} type The library to use for storage. Defaults * to localForage. * @returns {*} */ Persist.prototype.mode = function (type) { if (type !== undefined) { this._mode = type; return this; } return this._mode; }; /** * Gets / sets the driver used when persisting data. * @param {String} val Specify the driver type (LOCALSTORAGE, * WEBSQL or INDEXEDDB) * @returns {*} */ Persist.prototype.driver = function (val) { if (val !== undefined) { switch (val.toUpperCase()) { case 'LOCALSTORAGE': localforage.setDriver(localforage.LOCALSTORAGE); break; case 'WEBSQL': localforage.setDriver(localforage.WEBSQL); break; case 'INDEXEDDB': localforage.setDriver(localforage.INDEXEDDB); break; default: throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!'); } return this; } return localforage.driver(); }; /** * Starts a decode waterfall process. * @param {*} val The data to be decoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.decode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._decodeSteps), finished); }; /** * Starts an encode waterfall process. * @param {*} val The data to be encoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.encode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._encodeSteps), finished); }; Shared.synthesize(Persist.prototype, 'encodeSteps'); Shared.synthesize(Persist.prototype, 'decodeSteps'); /** * Adds an encode/decode step to the persistent storage system so * that you can add custom functionality. * @param {Function} encode The encode method called with the data from the * previous encode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the encoder will fail and throw an error. * @param {Function} decode The decode method called with the data from the * previous decode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the decoder will fail and throw an error. * @param {Number=} index Optional index to add the encoder step to. This * allows you to place a step before or after other existing steps. If not * provided your step is placed last in the list of steps. For instance if * you are providing an encryption step it makes sense to place this last * since all previous steps will then have their data encrypted by your * final step. */ Persist.prototype.addStep = new Overload({ 'object': function (obj) { this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0); }, 'function, function': function (encode, decode) { this.$main.call(this, encode, decode, 0); }, 'function, function, number': function (encode, decode, index) { this.$main.call(this, encode, decode, index); }, $main: function (encode, decode, index) { if (index === 0 || index === undefined) { this._encodeSteps.push(encode); this._decodeSteps.unshift(decode); } else { // Place encoder step at index then work out correct // index to place decoder step this._encodeSteps.splice(index, 0, encode); this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode); } } }); Persist.prototype.unwrap = function (dataStr) { var parts = dataStr.split('::fdb::'), data; switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } }; /** * Takes encoded data and decodes it for use as JS native objects and arrays. * @param {String} val The currently encoded string data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when decoding is * completed. * @private */ Persist.prototype._decode = function (val, meta, finished) { var parts, data; if (val) { parts = val.split('::fdb::'); switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } if (finished) { finished(false, data, meta); } } else { meta.foundData = false; meta.rowCount = 0; if (finished) { finished(false, val, meta); } } }; /** * Takes native JS data and encodes it for for storage as a string. * @param {Object} val The current un-encoded data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when encoding is * completed. * @private */ Persist.prototype._encode = function (val, meta, finished) { var data = val; if (typeof val === 'object') { val = 'json::fdb::' + this.jStringify(val); } else { val = 'raw::fdb::' + val; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } if (finished) { finished(false, val, meta); } }; /** * Encodes passed data and then stores it in the browser's persistent * storage layer. * @param {String} key The key to store the data under in the persistent * storage. * @param {Object} data The data to store under the key. * @param {Function=} callback The method to call when the save process * has completed. */ Persist.prototype.save = function (key, data, callback) { switch (this.mode()) { case 'localforage': this.encode(data, function (err, data, tableStats) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data, tableStats); } }, function (err) { if (callback) { callback(err); } }); }); break; default: if (callback) { callback('No data handler.'); } break; } }; /** * Loads and decodes data from the passed key. * @param {String} key The key to retrieve data from in the persistent * storage. * @param {Function=} callback The method to call when the load process * has completed. */ Persist.prototype.load = function (key, callback) { var self = this; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { self.decode(val, callback); }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; /** * Deletes data in persistent storage stored under the passed key. * @param {String} key The key to drop data for in the storage. * @param {Function=} callback The method to call when the data is dropped. */ Persist.prototype.drop = function (key, callback) { switch (this.mode()) { case 'localforage': localforage.removeItem(key).then(function () { if (callback) { callback(false); } }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; // Extend the Collection prototype with persist methods Collection.prototype.drop = new Overload({ /** * Drop collection and persistent storage. */ '': function () { if (!this.isDropped()) { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (!this.isDropped()) { this.drop(true, callback); } }, /** * Drop collection and optionally drop persistent storage. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. */ 'boolean': function (removePersistent) { if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name); this._db.persist.drop(this._db._name + '-' + this._name + '-metaData'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.call(this); } }, /** * Drop collections and optionally drop persistent storage with callback. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. * @param {Function} callback Callback method. */ 'boolean, function': function (removePersistent, callback) { var self = this; if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name, function () { self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback); }); return CollectionDrop.call(this); } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } } else { // Call the original method return CollectionDrop.call(this, callback); } } } }); /** * Saves an entire collection's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Collection.prototype.save = function (callback) { var self = this, processSave; if (self._name) { if (self._db) { processSave = function () { // Save the collection data self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) { if (!err) { self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) { if (callback) { callback(err, data, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads an entire collection's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Collection.prototype.load = function (callback) { var self = this; if (self._name) { if (self._db) { // Load the collection data self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); //self.setData(data); } // Now load the collection's metadata self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); } } if (callback) { callback(err, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; /** * Gets the data that represents this collection for easy storage using * a third-party method / plugin instead of using the standard persistent * storage system. * @param {Function} callback The method to call with the data response. */ Collection.prototype.saveCustom = function (callback) { var self = this, myData = {}, processSave; if (self._name) { if (self._db) { processSave = function () { self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.data = { name: self._db._name + '-' + self._name, store: data, tableStats: tableStats }; self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.metaData = { name: self._db._name + '-' + self._name + '-metaData', store: data, tableStats: tableStats }; callback(false, myData); } else { callback(err); } }); } else { callback(err); } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads custom data loaded by a third-party plugin into the collection. * @param {Object} myData Data object previously saved by using saveCustom() * @param {Function} callback A callback method to receive notification when * data has loaded. */ Collection.prototype.loadCustom = function (myData, callback) { var self = this; if (self._name) { if (self._db) { if (myData.data && myData.data.store) { if (myData.metaData && myData.metaData.store) { self.decode(myData.data.store, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); self.decode(myData.metaData.store, function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); if (callback) { callback(err, tableStats, metaStats); } } } else { callback(err); } }); } } else { callback(err); } }); } else { callback('No "metaData" key found in passed object!'); } } else { callback('No "data" key found in passed object!'); } } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { DbInit.apply(this, arguments); this.persist = new Persist(this); }; Db.prototype.load = new Overload({ /** * Loads an entire database's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (myData, callback) { this.$main.call(this, myData, callback); }, '$main': function (myData, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, loadCallback, index; loadCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection load method if (!myData) { obj[index].load(loadCallback); } else { obj[index].loadCustom(myData, loadCallback); } } } } }); Db.prototype.save = new Overload({ /** * Saves an entire database's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (options, callback) { this.$main.call(this, options, callback); }, '$main': function (options, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, saveCallback, index; saveCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection save method if (!options.custom) { obj[index].save(saveCallback); } else { obj[index].saveCustom(saveCallback); } } } } }); Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":33,"./PersistCrypto":34,"./Shared":38,"async":41,"localforage":77}],33:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), pako = _dereq_('pako'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); Plugin.prototype.encode = function (val, meta, finished) { var wrapper = { data: val, type: 'fdbCompress', enabled: false }, before, after, compressedVal; // Compress the data before = val.length; compressedVal = pako.deflate(val, {to: 'string'}); after = compressedVal.length; // If the compressed version is smaller than the original, use it! if (after < before) { wrapper.data = compressedVal; wrapper.enabled = true; } meta.compression = { enabled: wrapper.enabled, compressedBytes: after, uncompressedBytes: before, effect: Math.round((100 / before) * after) + '%' }; finished(false, this.jStringify(wrapper), meta); }; Plugin.prototype.decode = function (wrapper, meta, finished) { var compressionEnabled = false, data; if (wrapper) { wrapper = this.jParse(wrapper); // Check if we need to decompress the string if (wrapper.enabled) { data = pako.inflate(wrapper.data, {to: 'string'}); compressionEnabled = true; } else { data = wrapper.data; compressionEnabled = false; } meta.compression = { enabled: compressionEnabled }; if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, data, meta); } } }; // Register this plugin with the persistent storage class Shared.plugins.FdbCompress = Plugin; module.exports = Plugin; },{"./Shared":38,"pako":78}],34:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), CryptoJS = _dereq_('crypto-js'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { // Ensure at least a password is passed in options if (!options || !options.pass) { throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.'); } this._algo = options.algo || 'AES'; this._pass = options.pass; }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); /** * Gets / sets the current pass-phrase being used to encrypt / decrypt * data with the plugin. */ Shared.synthesize(Plugin.prototype, 'pass'); Plugin.prototype.stringify = function (cipherParams) { // create json object with ciphertext var jsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) }; // optionally add iv and salt if (cipherParams.iv) { jsonObj.iv = cipherParams.iv.toString(); } if (cipherParams.salt) { jsonObj.s = cipherParams.salt.toString(); } // stringify json object return this.jStringify(jsonObj); }; Plugin.prototype.parse = function (jsonStr) { // parse json string var jsonObj = this.jParse(jsonStr); // extract ciphertext from json object, and create cipher params object var cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct) }); // optionally extract iv and salt if (jsonObj.iv) { cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv); } if (jsonObj.s) { cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s); } return cipherParams; }; Plugin.prototype.encode = function (val, meta, finished) { var self = this, wrapper = { type: 'fdbCrypto' }, encryptedVal; // Encrypt the data encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }); wrapper.data = encryptedVal.toString(); wrapper.enabled = true; meta.encryption = { enabled: wrapper.enabled }; if (finished) { finished(false, this.jStringify(wrapper), meta); } }; Plugin.prototype.decode = function (wrapper, meta, finished) { var self = this, data; if (wrapper) { wrapper = this.jParse(wrapper); data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }).toString(CryptoJS.enc.Utf8); if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, wrapper, meta); } } }; // Register this plugin with the persistent storage class Shared.plugins.FdbCrypto = Plugin; module.exports = Plugin; },{"./Shared":38,"crypto-js":50}],35:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain || !reactorOut.chainReceive) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":38}],36:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), RestClient = _dereq_('rest'), mime = _dereq_('rest/interceptor/mime'), Db, Collection, CollectionDrop, CollectionGroup, CollectionInit, DbInit, Overload; var Rest = function () { this.init.apply(this, arguments); }; Rest.prototype.init = function (db) { this._endPoint = ''; this._client = RestClient.wrap(mime); }; /** * Convert a JSON object to url query parameter format. * @param {Object} obj The object to convert. * @returns {String} * @private */ Rest.prototype._params = function (obj) { var parts = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])); } } return parts.join('&'); }; Rest.prototype.get = function (path, data, callback) { var self= this, coll; path = path !== undefined ? path : ""; //console.log('Getting: ', this.endPoint() + path + '?' + this._params(data)); this._client({ method: 'get', path: this.endPoint() + path, params: data }).then(function (response) { if (response.entity && response.entity.error) { if (callback) { callback(response.entity.error, response.entity, response); } } else { // Check if we have a collection coll = self.collection(); if (coll) { // Upsert the records into the collection coll.upsert(response.entity); } if (callback) { callback(false, response.entity, response); } } }, function(response) { if (callback) { callback(true, response.entity, response); } }); }; Rest.prototype.post = function (path, data, callback) { this._client({ method: 'post', path: this.endPoint() + path, entity: data, headers: { 'Content-Type': 'application/json' } }).then(function (response) { if (response.entity && response.entity.error) { if (callback) { callback(response.entity.error, response.entity, response); } } else { if (callback) { callback(false, response.entity, response); } } }, function(response) { if (callback) { callback(true, response); } }); }; Shared.synthesize(Rest.prototype, 'sessionData'); Shared.synthesize(Rest.prototype, 'endPoint'); Shared.synthesize(Rest.prototype, 'collection'); Shared.addModule('Rest', Rest); Shared.mixin(Rest.prototype, 'Mixin.ChainReactor'); Db = Shared.modules.Db; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; Overload = Shared.overload; Collection.prototype.init = function () { this.rest = new Rest(); this.rest.collection(this); CollectionInit.apply(this, arguments); }; Db.prototype.init = function () { this.rest = new Rest(); DbInit.apply(this, arguments); }; Shared.finishModule('Rest'); module.exports = Rest; },{"./Collection":5,"./CollectionGroup":6,"./Shared":38,"rest":95,"rest/interceptor/mime":100}],37:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { this._encoder = []; this._decoder = {}; // Register our handlers this.registerEncoder('$date', function (data) { if (data instanceof Date) { return data.toISOString(); } }); this.registerDecoder('$date', function (data) { return new Date(data); }); }; /** * Register an encoder that can handle encoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. * @param {Function} method The encoder method. */ Serialiser.prototype.registerEncoder = function (handles, method) { this._encoder.push(function (data) { var methodVal = method(data), returnObj; if (methodVal !== undefined) { returnObj = {}; returnObj[handles] = methodVal; } return returnObj; }); }; /** * Register a decoder that can handle decoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. When an object * has a field matching this handler name then this decode will be invoked * to provide a decoded version of the data that was previously encoded by * it's counterpart encoder method. * @param {Function} method The decoder method. */ Serialiser.prototype.registerDecoder = function (handles, method) { this._decoder[handles] = method; }; /** * Loops the encoders and asks each one if it wants to handle encoding for * the passed data object. If no value is returned (undefined) then the data * will be passed to the next encoder and so on. If a value is returned the * loop will break and the encoded data will be used. * @param {Object} data The data object to handle. * @returns {*} The encoded data. * @private */ Serialiser.prototype._encode = function (data) { // Loop the encoders and if a return value is given by an encoder // the loop will exit and return that value. var count = this._encoder.length, retVal; while (count-- && !retVal) { retVal = this._encoder[count](data); } return retVal; }; /** * Converts a previously encoded string back into an object. * @param {String} data The string to convert to an object. * @returns {Object} The reconstituted object. */ Serialiser.prototype.parse = function (data) { return this._parse(JSON.parse(data)); }; /** * Handles restoring an object with special data markers back into * it's original format. * @param {Object} data The object to recurse. * @param {Object=} target The target object to restore data to. * @returns {Object} The final restored object. * @private */ Serialiser.prototype._parse = function (data, target) { var i; if (typeof data === 'object' && data !== null) { if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and handle // special object types and restore them for (i in data) { if (data.hasOwnProperty(i)) { if (i.substr(0, 1) === '$' && this._decoder[i]) { // This is a special object type and a handler // exists, restore it return this._decoder[i](data[i]); } // Not a special object or no handler, recurse as normal target[i] = this._parse(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; /** * Converts an object to a encoded string representation. * @param {Object} data The object to encode. */ Serialiser.prototype.stringify = function (data) { return JSON.stringify(this._stringify(data)); }; /** * Recurse down an object and encode special objects so they can be * stringified and later restored. * @param {Object} data The object to parse. * @param {Object=} target The target object to store converted data to. * @returns {Object} The converted object. * @private */ Serialiser.prototype._stringify = function (data, target) { var handledData, i; if (typeof data === 'object' && data !== null) { // Handle special object types so they can be encoded with // a special marker and later restored by a decoder counterpart handledData = this._encode(data); if (handledData) { // An encoder handled this object type so return it now return handledData; } if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and serialise for (i in data) { if (data.hasOwnProperty(i)) { target[i] = this._stringify(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; module.exports = Serialiser; },{}],38:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.477', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @memberof Shared * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: new Overload({ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":17,"./Mixin.ChainReactor":18,"./Mixin.Common":19,"./Mixin.Constants":20,"./Mixin.Events":21,"./Mixin.Matching":22,"./Mixin.Sorting":23,"./Mixin.Tags":24,"./Mixin.Triggers":25,"./Mixin.Updating":26,"./Overload":29}],39:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}],40:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; View.prototype.init = function (name, query, options) { var self = this; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, false); this.queryOptions(options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._privateData = new Collection(this.name() + '_internalPrivate'); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this.publicData().find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this.publicData().findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this.publicData().findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this.publicData().findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.publicData().findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._privateData; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); delete this._from; } if (typeof(source) === 'string') { source = this._db.collection(source); } if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } this._from = source; this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's "from" source and determines how they should be interpreted by // this view. If the view does not have a query then this reactor IO will // simply pass along the chain packet without modifying it. this._io = new ReactorIO(source, this, function (chainPacket) { var data, diff, query, filteredData, doSend, pk, i; // Check that the state of the "self" object is not dropped if (self && !self.isDropped()) { // Check if we have a constraining query if (self._querySettings.query) { if (chainPacket.type === 'insert') { data = chainPacket.data; // Check if the data matches our query if (data instanceof Array) { filteredData = []; for (i = 0; i < data.length; i++) { if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData.push(data[i]); doSend = true; } } } else { if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData = data; doSend = true; } } if (doSend) { this.chainSend('insert', filteredData); } return true; } if (chainPacket.type === 'update') { // Do a DB diff between this view's data and the underlying collection it reads from // to see if something has changed diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options)); if (diff.insert.length || diff.remove.length) { // Now send out new chain packets for each operation if (diff.insert.length) { this.chainSend('insert', diff.insert); } if (diff.update.length) { pk = self._privateData.primaryKey(); for (i = 0; i < diff.update.length; i++) { query = {}; query[pk] = diff.update[i][pk]; this.chainSend('update', { query: query, update: diff.update[i] }); } } if (diff.remove.length) { pk = self._privateData.primaryKey(); var $or = [], removeQuery = { query: { $or: $or } }; for (i = 0; i < diff.remove.length; i++) { $or.push({_id: diff.remove[i][pk]}); } this.chainSend('remove', removeQuery); } // Return true to stop further propagation of the chain packet return true; } else { // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } } } } // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); var collData = source.find(this._querySettings.query, this._querySettings.options); this._privateData.primaryKey(source.primaryKey()); this._privateData.setData(collData, {}, callback); if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._privateData.ensureIndex.apply(this._privateData, arguments); }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data'); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._privateData.setData(collData); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Make sure we are working with an array if (!(chainPacket.data instanceof Array)) { chainPacket.data = [chainPacket.data]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._privateData._insertHandle(chainPacket.data, insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._privateData._data.length; this._privateData._insertHandle(chainPacket.data, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"'); } primaryKey = this._privateData.primaryKey(); // Do the update updates = this._privateData.update( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._privateData._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"'); } this._privateData.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._privateData.on.apply(this._privateData, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._privateData.off.apply(this._privateData, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._privateData.emit.apply(this._privateData, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { var coll = this.publicData(); return coll.distinct.apply(coll, arguments); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this.publicData().primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._privateData) { this._privateData.drop(); } if (this._publicData && this._publicData !== this._privateData) { this._publicData.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._privateData; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this.privateData().db(db); this.publicData().db(db); // Apply the same debug settings this.debug(db.debug()); this.privateData().debug(db.debug()); this.publicData().debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = function (query, refresh) { if (query !== undefined) { this._querySettings.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings.query; }; /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { this.rebuildActiveBucket(options.$orderBy); } return this; } return this._querySettings.options; }; View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._privateData._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._privateData.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { if (this._from) { var pubData = this.publicData(), refreshResults; // Re-grab all the data for the view from the collection this._privateData.remove(); //pubData.remove(); refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); this._privateData.insert(refreshResults); this._privateData._data.$cursor = refreshResults.$cursor; pubData._data.$cursor = refreshResults.$cursor; /*if (pubData._linked) { // Update data and observers //var transformedData = this._privateData.find(); // TODO: Shouldn't this data get passed into a transformIn first? // TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data // TODO: Is this even required anymore? After commenting it all seems to work // TODO: Might be worth setting up a test to check transforms and linking then remove this if working? //jQuery.observable(pubData._data).refresh(transformedData); }*/ } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { if (this.publicData()) { return this.publicData().count.apply(this.publicData(), arguments); } return 0; }; // Call underlying View.prototype.subset = function () { return this.publicData().subset.apply(this._privateData, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var self = this; if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } if (this._transformEnabled) { // Check for / create the public data collection if (!this._publicData) { // Create the public data collection this._publicData = new Collection('__FDB__view_publicData_' + this._name); this._publicData.db(this._privateData._db); this._publicData.transform({ enabled: true, dataIn: this._transformIn, dataOut: this._transformOut }); // Create a chain reaction IO node to keep the private and // public data collections in sync this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) { var data = chainPacket.data; switch (chainPacket.type) { case 'primaryKey': self._publicData.primaryKey(data); this.chainSend('primaryKey', data); break; case 'setData': self._publicData.setData(data); this.chainSend('setData', data); break; case 'insert': self._publicData.insert(data); this.chainSend('insert', data); break; case 'update': // Do the update self._publicData.update( data.query, data.update, data.options ); this.chainSend('update', data); break; case 'remove': self._publicData.remove(data.query, chainPacket.options); this.chainSend('remove', data); break; default: break; } }); } // Set initial data and settings this._publicData.primaryKey(this.privateData().primaryKey()); this._publicData.setData(this.privateData().find()); } else { // Remove the public data collection if (this._publicData) { this._publicData.drop(); delete this._publicData; if (this._transformIo) { this._transformIo.drop(); delete this._transformIo; } } } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return (this.publicData()).filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.privateData = function () { return this._privateData; }; /** * Returns a data object representing the public data this view * contains. This can change depending on if transforms are being * applied to the view or not. * * If no transforms are applied then the public data will be the * same as the private data the view holds. If transforms are * applied then the public data will contain the transformed version * of the private data. * * The public data collection is also used by data binding to only * changes to the publicData will show in a data-bound element. */ View.prototype.publicData = function () { if (this._transformEnabled) { return this._publicData; } else { return this._privateData; } }; // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (viewName) { // Handle being passed an instance if (viewName instanceof View) { return viewName; } if (!this._view[viewName]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + viewName); } } this._view[viewName] = this._view[viewName] || new View(viewName).db(this); return this._view[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (viewName) { return Boolean(this._view[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./ReactorIO":35,"./Shared":38}],41:[function(_dereq_,module,exports){ (function (process,global){ /*! * async * https://github.com/caolan/async * * Copyright 2010-2014 Caolan McMahon * Released under the MIT license */ (function () { var async = {}; function noop() {} function identity(v) { return v; } function toBool(v) { return !!v; } function notId(v) { return !v; } // global on the server, window in the browser var previous_async; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self === 'object' && self.self === self && self || typeof global === 'object' && global.global === global && global || this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { return function() { if (fn === null) throw new Error("Callback was already called."); fn.apply(this, arguments); fn = null; }; } function _once(fn) { return function() { if (fn === null) return; fn.apply(this, arguments); fn = null; }; } //// cross-browser compatiblity functions //// var _toString = Object.prototype.toString; var _isArray = Array.isArray || function (obj) { return _toString.call(obj) === '[object Array]'; }; // Ported from underscore.js isObject var _isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; function _isArrayLike(arr) { return _isArray(arr) || ( // has a positive integer length property typeof arr.length === "number" && arr.length >= 0 && arr.length % 1 === 0 ); } function _arrayEach(arr, iterator) { var index = -1, length = arr.length; while (++index < length) { iterator(arr[index], index, arr); } } function _map(arr, iterator) { var index = -1, length = arr.length, result = Array(length); while (++index < length) { result[index] = iterator(arr[index], index, arr); } return result; } function _range(count) { return _map(Array(count), function (v, i) { return i; }); } function _reduce(arr, iterator, memo) { _arrayEach(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; } function _forEachOf(object, iterator) { _arrayEach(_keys(object), function (key) { iterator(object[key], key); }); } function _indexOf(arr, item) { for (var i = 0; i < arr.length; i++) { if (arr[i] === item) return i; } return -1; } var _keys = Object.keys || function (obj) { var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; function _keyIterator(coll) { var i = -1; var len; var keys; if (_isArrayLike(coll)) { len = coll.length; return function next() { i++; return i < len ? i : null; }; } else { keys = _keys(coll); len = keys.length; return function next() { i++; return i < len ? keys[i] : null; }; } } // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). function _restParam(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); for (var index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); } // Currently unused but handle cases outside of the switch statement: // var args = Array(startIndex + 1); // for (index = 0; index < startIndex; index++) { // args[index] = arguments[index]; // } // args[startIndex] = rest; // return func.apply(this, args); }; } function _withoutIndex(iterator) { return function (value, index, callback) { return iterator(value, callback); }; } //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// // capture the global reference to guard against fakeTimer mocks var _setImmediate = typeof setImmediate === 'function' && setImmediate; var _delay = _setImmediate ? function(fn) { // not a direct alias for IE10 compatibility _setImmediate(fn); } : function(fn) { setTimeout(fn, 0); }; if (typeof process === 'object' && typeof process.nextTick === 'function') { async.nextTick = process.nextTick; } else { async.nextTick = _delay; } async.setImmediate = _setImmediate ? _delay : async.nextTick; async.forEach = async.each = function (arr, iterator, callback) { return async.eachOf(arr, _withoutIndex(iterator), callback); }; async.forEachSeries = async.eachSeries = function (arr, iterator, callback) { return async.eachOfSeries(arr, _withoutIndex(iterator), callback); }; async.forEachLimit = async.eachLimit = function (arr, limit, iterator, callback) { return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); }; async.forEachOf = async.eachOf = function (object, iterator, callback) { callback = _once(callback || noop); object = object || []; var iter = _keyIterator(object); var key, completed = 0; while ((key = iter()) != null) { completed += 1; iterator(object[key], key, only_once(done)); } if (completed === 0) callback(null); function done(err) { completed--; if (err) { callback(err); } // Check key is null in case iterator isn't exhausted // and done resolved synchronously. else if (key === null && completed <= 0) { callback(null); } } }; async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); var key = nextKey(); function iterate() { var sync = true; if (key === null) { return callback(null); } iterator(obj[key], key, only_once(function (err) { if (err) { callback(err); } else { key = nextKey(); if (key === null) { return callback(null); } else { if (sync) { async.setImmediate(iterate); } else { iterate(); } } } })); sync = false; } iterate(); }; async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { _eachOfLimit(limit)(obj, iterator, callback); }; function _eachOfLimit(limit) { return function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); if (limit <= 0) { return callback(null); } var done = false; var running = 0; var errored = false; (function replenish () { if (done && running <= 0) { return callback(null); } while (running < limit && !errored) { var key = nextKey(); if (key === null) { done = true; if (running <= 0) { callback(null); } return; } running += 1; iterator(obj[key], key, only_once(function (err) { running -= 1; if (err) { callback(err); errored = true; } else { replenish(); } })); } })(); }; } function doParallel(fn) { return function (obj, iterator, callback) { return fn(async.eachOf, obj, iterator, callback); }; } function doParallelLimit(fn) { return function (obj, limit, iterator, callback) { return fn(_eachOfLimit(limit), obj, iterator, callback); }; } function doSeries(fn) { return function (obj, iterator, callback) { return fn(async.eachOfSeries, obj, iterator, callback); }; } function _asyncMap(eachfn, arr, iterator, callback) { callback = _once(callback || noop); arr = arr || []; var results = _isArrayLike(arr) ? [] : {}; eachfn(arr, function (value, index, callback) { iterator(value, function (err, v) { results[index] = v; callback(err); }); }, function (err) { callback(err, results); }); } async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = doParallelLimit(_asyncMap); // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.inject = async.foldl = async.reduce = function (arr, memo, iterator, callback) { async.eachOfSeries(arr, function (x, i, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; async.foldr = async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, identity).reverse(); async.reduce(reversed, memo, iterator, callback); }; async.transform = function (arr, memo, iterator, callback) { if (arguments.length === 3) { callback = iterator; iterator = memo; memo = _isArray(arr) ? [] : {}; } async.eachOf(arr, function(v, k, cb) { iterator(memo, v, k, cb); }, function(err) { callback(err, memo); }); }; function _filter(eachfn, arr, iterator, callback) { var results = []; eachfn(arr, function (x, index, callback) { iterator(x, function (v) { if (v) { results.push({index: index, value: x}); } callback(); }); }, function () { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); } async.select = async.filter = doParallel(_filter); async.selectLimit = async.filterLimit = doParallelLimit(_filter); async.selectSeries = async.filterSeries = doSeries(_filter); function _reject(eachfn, arr, iterator, callback) { _filter(eachfn, arr, function(value, cb) { iterator(value, function(v) { cb(!v); }); }, callback); } async.reject = doParallel(_reject); async.rejectLimit = doParallelLimit(_reject); async.rejectSeries = doSeries(_reject); function _createTester(eachfn, check, getResult) { return function(arr, limit, iterator, cb) { function done() { if (cb) cb(getResult(false, void 0)); } function iteratee(x, _, callback) { if (!cb) return callback(); iterator(x, function (v) { if (cb && check(v)) { cb(getResult(true, x)); cb = iterator = false; } callback(); }); } if (arguments.length > 3) { eachfn(arr, limit, iteratee, done); } else { cb = iterator; iterator = limit; eachfn(arr, iteratee, done); } }; } async.any = async.some = _createTester(async.eachOf, toBool, identity); async.someLimit = _createTester(async.eachOfLimit, toBool, identity); async.all = async.every = _createTester(async.eachOf, notId, notId); async.everyLimit = _createTester(async.eachOfLimit, notId, notId); function _findGetResult(v, x) { return x; } async.detect = _createTester(async.eachOf, identity, _findGetResult); async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { callback(null, _map(results.sort(comparator), function (x) { return x.value; })); } }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }; async.auto = function (tasks, concurrency, callback) { if (!callback) { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = _once(callback || noop); var keys = _keys(tasks); var remainingTasks = keys.length; if (!remainingTasks) { return callback(null); } if (!concurrency) { concurrency = remainingTasks; } var results = {}; var runningTasks = 0; var listeners = []; function addListener(fn) { listeners.unshift(fn); } function removeListener(fn) { var idx = _indexOf(listeners, fn); if (idx >= 0) listeners.splice(idx, 1); } function taskComplete() { remainingTasks--; _arrayEach(listeners.slice(0), function (fn) { fn(); }); } addListener(function () { if (!remainingTasks) { callback(null, results); } }); _arrayEach(keys, function (k) { var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; var taskCallback = _restParam(function(err, args) { runningTasks--; if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _forEachOf(results, function(val, rkey) { safeResults[rkey] = val; }); safeResults[k] = args; callback(err, safeResults); } else { results[k] = args; async.setImmediate(taskComplete); } }); var requires = task.slice(0, task.length - 1); // prevent dead-locks var len = requires.length; var dep; while (len--) { if (!(dep = tasks[requires[len]])) { throw new Error('Has inexistant dependency'); } if (_isArray(dep) && _indexOf(dep, k) >= 0) { throw new Error('Has cyclic dependencies'); } } function ready() { return runningTasks < concurrency && _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); } if (ready()) { runningTasks++; task[task.length - 1](taskCallback, results); } else { addListener(listener); } function listener() { if (ready()) { runningTasks++; removeListener(listener); task[task.length - 1](taskCallback, results); } } }); }; async.retry = function(times, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; var attempts = []; var opts = { times: DEFAULT_TIMES, interval: DEFAULT_INTERVAL }; function parseTimes(acc, t){ if(typeof t === 'number'){ acc.times = parseInt(t, 10) || DEFAULT_TIMES; } else if(typeof t === 'object'){ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; } else { throw new Error('Unsupported argument type for \'times\': ' + typeof t); } } var length = arguments.length; if (length < 1 || length > 3) { throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); } else if (length <= 2 && typeof times === 'function') { callback = task; task = times; } if (typeof times !== 'function') { parseTimes(opts, times); } opts.callback = callback; opts.task = task; function wrappedTask(wrappedCallback, wrappedResults) { function retryAttempt(task, finalAttempt) { return function(seriesCallback) { task(function(err, result){ seriesCallback(!err || finalAttempt, {err: err, result: result}); }, wrappedResults); }; } function retryInterval(interval){ return function(seriesCallback){ setTimeout(function(){ seriesCallback(null); }, interval); }; } while (opts.times) { var finalAttempt = !(opts.times-=1); attempts.push(retryAttempt(opts.task, finalAttempt)); if(!finalAttempt && opts.interval > 0){ attempts.push(retryInterval(opts.interval)); } } async.series(attempts, function(done, data){ data = data[data.length - 1]; (wrappedCallback || opts.callback)(data.err, data.result); }); } // If a callback is passed, run this as a controll flow return opts.callback ? wrappedTask() : wrappedTask; }; async.waterfall = function (tasks, callback) { callback = _once(callback || noop); if (!_isArray(tasks)) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } function wrapIterator(iterator) { return _restParam(function (err, args) { if (err) { callback.apply(null, [err].concat(args)); } else { var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } ensureAsync(iterator).apply(null, args); } }); } wrapIterator(async.iterator(tasks))(); }; function _parallel(eachfn, tasks, callback) { callback = callback || noop; var results = _isArrayLike(tasks) ? [] : {}; eachfn(tasks, function (task, key, callback) { task(_restParam(function (err, args) { if (args.length <= 1) { args = args[0]; } results[key] = args; callback(err); })); }, function (err) { callback(err, results); }); } async.parallel = function (tasks, callback) { _parallel(async.eachOf, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); }; async.series = function(tasks, callback) { _parallel(async.eachOfSeries, tasks, callback); }; async.iterator = function (tasks) { function makeCallback(index) { function fn() { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); } fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; } return makeCallback(0); }; async.apply = _restParam(function (fn, args) { return _restParam(function (callArgs) { return fn.apply( null, args.concat(callArgs) ); }); }); function _concat(eachfn, arr, fn, callback) { var result = []; eachfn(arr, function (x, index, cb) { fn(x, function (err, y) { result = result.concat(y || []); cb(err); }); }, function (err) { callback(err, result); }); } async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { callback = callback || noop; if (test()) { var next = _restParam(function(err, args) { if (err) { callback(err); } else if (test.apply(this, args)) { iterator(next); } else { callback(null); } }); iterator(next); } else { callback(null); } }; async.doWhilst = function (iterator, test, callback) { var calls = 0; return async.whilst(function() { return ++calls <= 1 || test.apply(this, arguments); }, iterator, callback); }; async.until = function (test, iterator, callback) { return async.whilst(function() { return !test.apply(this, arguments); }, iterator, callback); }; async.doUntil = function (iterator, test, callback) { return async.doWhilst(iterator, function() { return !test.apply(this, arguments); }, callback); }; async.during = function (test, iterator, callback) { callback = callback || noop; var next = _restParam(function(err, args) { if (err) { callback(err); } else { args.push(check); test.apply(this, args); } }); var check = function(err, truth) { if (err) { callback(err); } else if (truth) { iterator(next); } else { callback(null); } }; test(check); }; async.doDuring = function (iterator, test, callback) { var calls = 0; async.during(function(next) { if (calls++ < 1) { next(null, true); } else { test.apply(this, arguments); } }, iterator, callback); }; function _queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } function _insert(q, data, pos, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0 && q.idle()) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, callback: callback || noop }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.tasks.length === q.concurrency) { q.saturated(); } }); async.setImmediate(q.process); } function _next(q, tasks) { return function(){ workers -= 1; var removed = false; var args = arguments; _arrayEach(tasks, function (task) { _arrayEach(workersList, function (worker, index) { if (worker === task && !removed) { workersList.splice(index, 1); removed = true; } }); task.callback.apply(task, args); }); if (q.tasks.length + workers === 0) { q.drain(); } q.process(); }; } var workers = 0; var workersList = []; var q = { tasks: [], concurrency: concurrency, payload: payload, saturated: noop, empty: noop, drain: noop, started: false, paused: false, push: function (data, callback) { _insert(q, data, false, callback); }, kill: function () { q.drain = noop; q.tasks = []; }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { if (!q.paused && workers < q.concurrency && q.tasks.length) { while(workers < q.concurrency && q.tasks.length){ var tasks = q.payload ? q.tasks.splice(0, q.payload) : q.tasks.splice(0, q.tasks.length); var data = _map(tasks, function (task) { return task.data; }); if (q.tasks.length === 0) { q.empty(); } workers += 1; workersList.push(tasks[0]); var cb = only_once(_next(q, tasks)); worker(data, cb); } } }, length: function () { return q.tasks.length; }, running: function () { return workers; }, workersList: function () { return workersList; }, idle: function() { return q.tasks.length + workers === 0; }, pause: function () { q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; var resumeCount = Math.min(q.concurrency, q.tasks.length); // Need to call q.process once per concurrent // worker to preserve full concurrency after pause for (var w = 1; w <= resumeCount; w++) { async.setImmediate(q.process); } } }; return q; } async.queue = function (worker, concurrency) { var q = _queue(function (items, cb) { worker(items[0], cb); }, concurrency, 1); return q; }; async.priorityQueue = function (worker, concurrency) { function _compareTasks(a, b){ return a.priority - b.priority; } function _binarySearch(sequence, item, compare) { var beg = -1, end = sequence.length - 1; while (beg < end) { var mid = beg + ((end - beg + 1) >>> 1); if (compare(item, sequence[mid]) >= 0) { beg = mid; } else { end = mid - 1; } } return beg; } function _insert(q, data, priority, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, priority: priority, callback: typeof callback === 'function' ? callback : noop }; q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); if (q.tasks.length === q.concurrency) { q.saturated(); } async.setImmediate(q.process); }); } // Start with a normal queue var q = async.queue(worker, concurrency); // Override push to accept second parameter representing priority q.push = function (data, priority, callback) { _insert(q, data, priority, callback); }; // Remove unshift function delete q.unshift; return q; }; async.cargo = function (worker, payload) { return _queue(worker, 1, payload); }; function _console_fn(name) { return _restParam(function (fn, args) { fn.apply(null, args.concat([_restParam(function (err, args) { if (typeof console === 'object') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _arrayEach(args, function (x) { console[name](x); }); } } })])); }); } async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; hasher = hasher || identity; var memoized = _restParam(function memoized(args) { var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { async.setImmediate(function () { callback.apply(null, memo[key]); }); } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([_restParam(function (args) { memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })])); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; function _times(mapper) { return function (count, iterator, callback) { mapper(_range(count), iterator, callback); }; } async.times = _times(async.map); async.timesSeries = _times(async.mapSeries); async.timesLimit = function (count, limit, iterator, callback) { return async.mapLimit(_range(count), limit, iterator, callback); }; async.seq = function (/* functions... */) { var fns = arguments; return _restParam(function (args) { var that = this; var callback = args[args.length - 1]; if (typeof callback == 'function') { args.pop(); } else { callback = noop; } async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { cb(err, nextargs); })])); }, function (err, results) { callback.apply(that, [err].concat(results)); }); }); }; async.compose = function (/* functions... */) { return async.seq.apply(null, Array.prototype.reverse.call(arguments)); }; function _applyEach(eachfn) { return _restParam(function(fns, args) { var go = _restParam(function(args) { var that = this; var callback = args.pop(); return eachfn(fns, function (fn, _, cb) { fn.apply(that, args.concat([cb])); }, callback); }); if (args.length) { return go.apply(this, args); } else { return go; } }); } async.applyEach = _applyEach(async.eachOf); async.applyEachSeries = _applyEach(async.eachOfSeries); async.forever = function (fn, callback) { var done = only_once(callback || noop); var task = ensureAsync(fn); function next(err) { if (err) { return done(err); } task(next); } next(); }; function ensureAsync(fn) { return _restParam(function (args) { var callback = args.pop(); args.push(function () { var innerArgs = arguments; if (sync) { async.setImmediate(function () { callback.apply(null, innerArgs); }); } else { callback.apply(null, innerArgs); } }); var sync = true; fn.apply(this, args); sync = false; }); } async.ensureAsync = ensureAsync; async.constant = _restParam(function(values) { var args = [null].concat(values); return function (callback) { return callback.apply(this, args); }; }); async.wrapSync = async.asyncify = function asyncify(func) { return _restParam(function (args) { var callback = args.pop(); var result; try { result = func.apply(this, args); } catch (e) { return callback(e); } // if result is Promise object if (_isObject(result) && typeof result.then === "function") { result.then(function(value) { callback(null, value); })["catch"](function(err) { callback(err.message ? err : new Error(err)); }); } else { callback(null, result); } }); }; // Node.js if (typeof module === 'object' && module.exports) { module.exports = async; } // AMD / RequireJS else if (typeof define === 'function' && define.amd) { define([], function () { return async; }); } // included directly via <script> tag else { root.async = async; } }()); }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":76}],42:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Lookup tables var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; // Compute lookup tables (function () { // Compute double table var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = (i << 1) ^ 0x11b; } } // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100); SUB_MIX_0[x] = (t << 24) | (t >>> 8); SUB_MIX_1[x] = (t << 16) | (t >>> 16); SUB_MIX_2[x] = (t << 8) | (t >>> 24); SUB_MIX_3[x] = t; // Compute inv sub bytes, inv mix columns tables var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); INV_SUB_MIX_3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }()); // Precomputed Rcon lookup var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; /** * AES block cipher algorithm. */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds var nRounds = this._nRounds = keySize + 6 // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; // Compute key schedule var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { var t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { // Rot word t = (t << 8) | (t >>> 24); // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; // Mix Rcon t ^= RCON[(ksRow / keySize) | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } // Compute inv key schedule var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function (M, offset) { // Swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); // Inv swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { // Shortcut var nRounds = this._nRounds; // Get input, add round key var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; // Key schedule row counter var ksRow = 4; // Rounds for (var round = 1; round < nRounds; round++) { // Shift rows, sub bytes, mix columns, add round key var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; } // Shift rows, sub bytes, add round key var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; // Set output M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); */ C.AES = BlockCipher._createHelper(AES); }()); return CryptoJS.AES; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],43:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher core components. */ CryptoJS.lib.Cipher || (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; /** * Abstract base cipher template. * * @property {number} keySize This cipher's key size. Default: 4 (128 bits) * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. */ var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } this._mode = modeCreator.call(mode, this, iv && iv.words); }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":44}],44:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { function F() {} return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn F.prototype = this; var subtype = new F(); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init')) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],45:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":44}],46:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * UTF-16 BE encoding strategy. */ var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); } }; /** * UTF-16 LE encoding strategy. */ C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); } }()); return CryptoJS.enc.Utf16; })); },{"./core":44}],47:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); return CryptoJS.EvpKDF; })); },{"./core":44,"./hmac":49,"./sha1":68}],48:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }()); return CryptoJS.format.Hex; })); },{"./cipher-core":43,"./core":44}],49:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); })); },{"./core":44}],50:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory); } else { // Global (browser) root.CryptoJS = factory(root.CryptoJS); } }(this, function (CryptoJS) { return CryptoJS; })); },{"./aes":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],51:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Check if typed arrays are supported if (typeof ArrayBuffer != 'function') { return; } // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; // Reference original init var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays var subInit = WordArray.init = function (typedArray) { // Convert buffers to uint8 if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } // Convert other array views to uint8 if ( typedArray instanceof Int8Array || (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array ) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } // Handle Uint8Array if (typedArray instanceof Uint8Array) { // Shortcut var typedArrayByteLength = typedArray.byteLength; // Extract bytes var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); } // Initialize this word array superInit.call(this, words, typedArrayByteLength); } else { // Else call normal init superInit.apply(this, arguments); } }; subInit.prototype = WordArray; }()); return CryptoJS.lib.WordArray; })); },{"./core":44}],52:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); return CryptoJS.MD5; })); },{"./core":44}],53:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher Feedback block mode. */ CryptoJS.mode.CFB = (function () { var CFB = CryptoJS.lib.BlockCipherMode.extend(); CFB.Encryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); CFB.Decryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // This block becomes the previous block this._prevBlock = thisBlock; } }); function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { // Shortcut var iv = this._iv; // Generate keystream if (iv) { var keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } else { var keystream = this._prevBlock; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } return CFB; }()); return CryptoJS.mode.CFB; })); },{"./cipher-core":43,"./core":44}],54:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve * Counter block mode compatible with Dr Brian Gladman fileenc.c * derived from CryptoJS.mode.CTR * Jan Hruby [email protected] */ CryptoJS.mode.CTRGladman = (function () { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }()); return CryptoJS.mode.CTRGladman; })); },{"./cipher-core":43,"./core":44}],55:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Counter block mode. */ CryptoJS.mode.CTR = (function () { var CTR = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = CTR.Encryptor = CTR.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Increment counter counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTR.Decryptor = Encryptor; return CTR; }()); return CryptoJS.mode.CTR; })); },{"./cipher-core":43,"./core":44}],56:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Electronic Codebook block mode. */ CryptoJS.mode.ECB = (function () { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.encryptBlock(words, offset); } }); ECB.Decryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.decryptBlock(words, offset); } }); return ECB; }()); return CryptoJS.mode.ECB; })); },{"./cipher-core":43,"./core":44}],57:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Output Feedback block mode. */ CryptoJS.mode.OFB = (function () { var OFB = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = OFB.Encryptor = OFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var keystream = this._keystream; // Generate keystream if (iv) { keystream = this._keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); OFB.Decryptor = Encryptor; return OFB; }()); return CryptoJS.mode.OFB; })); },{"./cipher-core":43,"./core":44}],58:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ANSI X.923 padding strategy. */ CryptoJS.pad.AnsiX923 = { pad: function (data, blockSize) { // Shortcuts var dataSigBytes = data.sigBytes; var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; // Compute last byte position var lastBytePos = dataSigBytes + nPaddingBytes - 1; // Pad data.clamp(); data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); data.sigBytes += nPaddingBytes; }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Ansix923; })); },{"./cipher-core":43,"./core":44}],59:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO 10126 padding strategy. */ CryptoJS.pad.Iso10126 = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Pad data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Iso10126; })); },{"./cipher-core":43,"./core":44}],60:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO/IEC 9797-1 Padding Method 2. */ CryptoJS.pad.Iso97971 = { pad: function (data, blockSize) { // Add 0x80 byte data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); // Zero pad the rest CryptoJS.pad.ZeroPadding.pad(data, blockSize); }, unpad: function (data) { // Remove zero padding CryptoJS.pad.ZeroPadding.unpad(data); // Remove one more byte -- the 0x80 byte data.sigBytes--; } }; return CryptoJS.pad.Iso97971; })); },{"./cipher-core":43,"./core":44}],61:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":43,"./core":44}],62:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Zero padding strategy. */ CryptoJS.pad.ZeroPadding = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Pad data.clamp(); data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); }, unpad: function (data) { // Shortcut var dataWords = data.words; // Unpad var i = data.sigBytes - 1; while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { i--; } data.sigBytes = i + 1; } }; return CryptoJS.pad.ZeroPadding; })); },{"./cipher-core":43,"./core":44}],63:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA1 = C_algo.SHA1; var HMAC = C_algo.HMAC; /** * Password-Based Key Derivation Function 2 algorithm. */ var PBKDF2 = C_algo.PBKDF2 = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.PBKDF2(password, salt); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); */ C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; }()); return CryptoJS.PBKDF2; })); },{"./core":44,"./hmac":49,"./sha1":68}],64:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm. * * This is a legacy version that neglected to convert the key to little-endian. * This error doesn't affect the cipher's security, * but it does affect its compatibility with other implementations. */ var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); */ C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); }()); return CryptoJS.RabbitLegacy; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm */ var Rabbit = C_algo.Rabbit = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Swap endian for (var i = 0; i < 4; i++) { K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); } // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); */ C.Rabbit = StreamCipher._createHelper(Rabbit); }()); return CryptoJS.Rabbit; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],66:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; /** * RC4 stream cipher algorithm. */ var RC4 = C_algo.RC4 = StreamCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySigBytes = key.sigBytes; // Init sbox var S = this._S = []; for (var i = 0; i < 256; i++) { S[i] = i; } // Key setup for (var i = 0, j = 0; i < 256; i++) { var keyByteIndex = i % keySigBytes; var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; j = (j + S[i] + keyByte) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; } // Counters this._i = this._j = 0; }, _doProcessBlock: function (M, offset) { M[offset] ^= generateKeystreamWord.call(this); }, keySize: 256/32, ivSize: 0 }); function generateKeystreamWord() { // Shortcuts var S = this._S; var i = this._i; var j = this._j; // Generate keystream word var keystreamWord = 0; for (var n = 0; n < 4; n++) { i = (i + 1) % 256; j = (j + S[i]) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); } // Update counters this._i = i; this._j = j; return keystreamWord; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); */ C.RC4 = StreamCipher._createHelper(RC4); /** * Modified RC4 stream cipher algorithm. */ var RC4Drop = C_algo.RC4Drop = RC4.extend({ /** * Configuration options. * * @property {number} drop The number of keystream words to drop. Default 192 */ cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function () { RC4._doReset.call(this); // Drop for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); */ C.RC4Drop = StreamCipher._createHelper(RC4Drop); }()); return CryptoJS.RC4; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var _zl = WordArray.create([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); var _zr = WordArray.create([ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); var _sl = WordArray.create([ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); var _sr = WordArray.create([ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); /** * RIPEMD160 hash algorithm. */ var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ _doReset: function () { this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; // Swap M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcut var H = this._hash.words; var hl = _hl.words; var hr = _hr.words; var zl = _zl.words; var zr = _zr.words; var sl = _sl.words; var sr = _sr.words; // Working variables var al, bl, cl, dl, el; var ar, br, cr, dr, er; ar = al = H[0]; br = bl = H[1]; cr = cl = H[2]; dr = dl = H[3]; er = el = H[4]; // Computation var t; for (var i = 0; i < 80; i += 1) { t = (al + M[offset+zl[i]])|0; if (i<16){ t += f1(bl,cl,dl) + hl[0]; } else if (i<32) { t += f2(bl,cl,dl) + hl[1]; } else if (i<48) { t += f3(bl,cl,dl) + hl[2]; } else if (i<64) { t += f4(bl,cl,dl) + hl[3]; } else {// if (i<80) { t += f5(bl,cl,dl) + hl[4]; } t = t|0; t = rotl(t,sl[i]); t = (t+el)|0; al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = t; t = (ar + M[offset+zr[i]])|0; if (i<16){ t += f5(br,cr,dr) + hr[0]; } else if (i<32) { t += f4(br,cr,dr) + hr[1]; } else if (i<48) { t += f3(br,cr,dr) + hr[2]; } else if (i<64) { t += f2(br,cr,dr) + hr[3]; } else {// if (i<80) { t += f1(br,cr,dr) + hr[4]; } t = t|0; t = rotl(t,sr[i]) ; t = (t+er)|0; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = t; } // Intermediate hash value t = (H[1] + cl + dr)|0; H[1] = (H[2] + dl + er)|0; H[2] = (H[3] + el + ar)|0; H[3] = (H[4] + al + br)|0; H[4] = (H[0] + bl + cr)|0; H[0] = t; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 5; i++) { // Shortcut var H_i = H[i]; // Swap H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function f1(x, y, z) { return ((x) ^ (y) ^ (z)); } function f2(x, y, z) { return (((x)&(y)) | ((~x)&(z))); } function f3(x, y, z) { return (((x) | (~(y))) ^ (z)); } function f4(x, y, z) { return (((x) & (z)) | ((y)&(~(z)))); } function f5(x, y, z) { return ((x) ^ ((y) |(~(z)))); } function rotl(x,n) { return (x<<n) | (x>>>(32-n)); } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.RIPEMD160('message'); * var hash = CryptoJS.RIPEMD160(wordArray); */ C.RIPEMD160 = Hasher._createHelper(RIPEMD160); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacRIPEMD160(message, key); */ C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); }(Math)); return CryptoJS.RIPEMD160; })); },{"./core":44}],68:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Reusable object var W = []; /** * SHA-1 hash algorithm. */ var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; // Computation for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = (n << 1) | (n >>> 31); } var t = ((a << 5) | (a >>> 27)) + e + W[i]; if (i < 20) { t += ((b & c) | (~b & d)) + 0x5a827999; } else if (i < 40) { t += (b ^ c ^ d) + 0x6ed9eba1; } else if (i < 60) { t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; } else /* if (i < 80) */ { t += (b ^ c ^ d) - 0x359d3e2a; } e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA1('message'); * var hash = CryptoJS.SHA1(wordArray); */ C.SHA1 = Hasher._createHelper(SHA1); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA1(message, key); */ C.HmacSHA1 = Hasher._createHmacHelper(SHA1); }()); return CryptoJS.SHA1; })); },{"./core":44}],69:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha256"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA256 = C_algo.SHA256; /** * SHA-224 hash algorithm. */ var SHA224 = C_algo.SHA224 = SHA256.extend({ _doReset: function () { this._hash = new WordArray.init([ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]); }, _doFinalize: function () { var hash = SHA256._doFinalize.call(this); hash.sigBytes -= 4; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA224('message'); * var hash = CryptoJS.SHA224(wordArray); */ C.SHA224 = SHA256._createHelper(SHA224); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA224(message, key); */ C.HmacSHA224 = SHA256._createHmacHelper(SHA224); }()); return CryptoJS.SHA224; })); },{"./core":44,"./sha256":70}],70:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Initialization and round constants tables var H = []; var K = []; // Compute constants (function () { function isPrime(n) { var sqrtN = Math.sqrt(n); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n % factor)) { return false; } } return true; } function getFractionalBits(n) { return ((n - (n | 0)) * 0x100000000) | 0; } var n = 2; var nPrime = 0; while (nPrime < 64) { if (isPrime(n)) { if (nPrime < 8) { H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); } K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); nPrime++; } n++; } }()); // Reusable object var W = []; /** * SHA-256 hash algorithm. */ var SHA256 = C_algo.SHA256 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init(H.slice(0)); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; var f = H[5]; var g = H[6]; var h = H[7]; // Computation for (var i = 0; i < 64; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var gamma0x = W[i - 15]; var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); var gamma1x = W[i - 2]; var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; } var ch = (e & f) ^ (~e & g); var maj = (a & b) ^ (a & c) ^ (b & c); var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); var t1 = h + sigma1 + ch + K[i] + W[i]; var t2 = sigma0 + maj; h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA256('message'); * var hash = CryptoJS.SHA256(wordArray); */ C.SHA256 = Hasher._createHelper(SHA256); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA256(message, key); */ C.HmacSHA256 = Hasher._createHmacHelper(SHA256); }(Math)); return CryptoJS.SHA256; })); },{"./core":44}],71:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":44,"./x64-core":75}],72:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./sha512"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; var SHA512 = C_algo.SHA512; /** * SHA-384 hash algorithm. */ var SHA384 = C_algo.SHA384 = SHA512.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) ]); }, _doFinalize: function () { var hash = SHA512._doFinalize.call(this); hash.sigBytes -= 16; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA384('message'); * var hash = CryptoJS.SHA384(wordArray); */ C.SHA384 = SHA512._createHelper(SHA384); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA384(message, key); */ C.HmacSHA384 = SHA512._createHmacHelper(SHA384); }()); return CryptoJS.SHA384; })); },{"./core":44,"./sha512":73,"./x64-core":75}],73:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; function X64Word_create() { return X64Word.create.apply(X64Word, arguments); } // Constants var K = [ X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) ]; // Reusable objects var W = []; (function () { for (var i = 0; i < 80; i++) { W[i] = X64Word_create(); } }()); /** * SHA-512 hash algorithm. */ var SHA512 = C_algo.SHA512 = Hasher.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) ]); }, _doProcessBlock: function (M, offset) { // Shortcuts var H = this._hash.words; var H0 = H[0]; var H1 = H[1]; var H2 = H[2]; var H3 = H[3]; var H4 = H[4]; var H5 = H[5]; var H6 = H[6]; var H7 = H[7]; var H0h = H0.high; var H0l = H0.low; var H1h = H1.high; var H1l = H1.low; var H2h = H2.high; var H2l = H2.low; var H3h = H3.high; var H3l = H3.low; var H4h = H4.high; var H4l = H4.low; var H5h = H5.high; var H5l = H5.low; var H6h = H6.high; var H6l = H6.low; var H7h = H7.high; var H7l = H7.low; // Working variables var ah = H0h; var al = H0l; var bh = H1h; var bl = H1l; var ch = H2h; var cl = H2l; var dh = H3h; var dl = H3l; var eh = H4h; var el = H4l; var fh = H5h; var fl = H5l; var gh = H6h; var gl = H6l; var hh = H7h; var hl = H7l; // Rounds for (var i = 0; i < 80; i++) { // Shortcut var Wi = W[i]; // Extend message if (i < 16) { var Wih = Wi.high = M[offset + i * 2] | 0; var Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { // Gamma0 var gamma0x = W[i - 15]; var gamma0xh = gamma0x.high; var gamma0xl = gamma0x.low; var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); // Gamma1 var gamma1x = W[i - 2]; var gamma1xh = gamma1x.high; var gamma1xl = gamma1x.low; var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7 = W[i - 7]; var Wi7h = Wi7.high; var Wi7l = Wi7.low; var Wi16 = W[i - 16]; var Wi16h = Wi16.high; var Wi16l = Wi16.low; var Wil = gamma0l + Wi7l; var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); var Wil = Wil + gamma1l; var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); var Wil = Wil + Wi16l; var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); Wi.high = Wih; Wi.low = Wil; } var chh = (eh & fh) ^ (~eh & gh); var chl = (el & fl) ^ (~el & gl); var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); var majl = (al & bl) ^ (al & cl) ^ (bl & cl); var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); // t1 = h + sigma1 + ch + K[i] + W[i] var Ki = K[i]; var Kih = Ki.high; var Kil = Ki.low; var t1l = hl + sigma1l; var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); var t1l = t1l + chl; var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); var t1l = t1l + Kil; var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); var t1l = t1l + Wil; var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); // t2 = sigma0 + maj var t2l = sigma0l + majl; var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); // Update working variables hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = (dl + t1l) | 0; eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = (t1l + t2l) | 0; ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; } // Intermediate hash value H0l = H0.low = (H0l + al); H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); H1l = H1.low = (H1l + bl); H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); H2l = H2.low = (H2l + cl); H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); H3l = H3.low = (H3l + dl); H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); H4l = H4.low = (H4l + el); H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); H5l = H5.low = (H5l + fl); H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); H6l = H6.low = (H6l + gl); H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); H7l = H7.low = (H7l + hl); H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Convert hash to 32-bit word array before returning var hash = this._hash.toX32(); // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; }, blockSize: 1024/32 }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA512('message'); * var hash = CryptoJS.SHA512(wordArray); */ C.SHA512 = Hasher._createHelper(SHA512); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA512(message, key); */ C.HmacSHA512 = Hasher._createHmacHelper(SHA512); }()); return CryptoJS.SHA512; })); },{"./core":44,"./x64-core":75}],74:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Permuted Choice 1 constants var PC1 = [ 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ]; // Permuted Choice 2 constants var PC2 = [ 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ]; // Cumulative bit shift constants var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; // SBOXes and round permutation constants var SBOX_P = [ { 0x0: 0x808200, 0x10000000: 0x8000, 0x20000000: 0x808002, 0x30000000: 0x2, 0x40000000: 0x200, 0x50000000: 0x808202, 0x60000000: 0x800202, 0x70000000: 0x800000, 0x80000000: 0x202, 0x90000000: 0x800200, 0xa0000000: 0x8200, 0xb0000000: 0x808000, 0xc0000000: 0x8002, 0xd0000000: 0x800002, 0xe0000000: 0x0, 0xf0000000: 0x8202, 0x8000000: 0x0, 0x18000000: 0x808202, 0x28000000: 0x8202, 0x38000000: 0x8000, 0x48000000: 0x808200, 0x58000000: 0x200, 0x68000000: 0x808002, 0x78000000: 0x2, 0x88000000: 0x800200, 0x98000000: 0x8200, 0xa8000000: 0x808000, 0xb8000000: 0x800202, 0xc8000000: 0x800002, 0xd8000000: 0x8002, 0xe8000000: 0x202, 0xf8000000: 0x800000, 0x1: 0x8000, 0x10000001: 0x2, 0x20000001: 0x808200, 0x30000001: 0x800000, 0x40000001: 0x808002, 0x50000001: 0x8200, 0x60000001: 0x200, 0x70000001: 0x800202, 0x80000001: 0x808202, 0x90000001: 0x808000, 0xa0000001: 0x800002, 0xb0000001: 0x8202, 0xc0000001: 0x202, 0xd0000001: 0x800200, 0xe0000001: 0x8002, 0xf0000001: 0x0, 0x8000001: 0x808202, 0x18000001: 0x808000, 0x28000001: 0x800000, 0x38000001: 0x200, 0x48000001: 0x8000, 0x58000001: 0x800002, 0x68000001: 0x2, 0x78000001: 0x8202, 0x88000001: 0x8002, 0x98000001: 0x800202, 0xa8000001: 0x202, 0xb8000001: 0x808200, 0xc8000001: 0x800200, 0xd8000001: 0x0, 0xe8000001: 0x8200, 0xf8000001: 0x808002 }, { 0x0: 0x40084010, 0x1000000: 0x4000, 0x2000000: 0x80000, 0x3000000: 0x40080010, 0x4000000: 0x40000010, 0x5000000: 0x40084000, 0x6000000: 0x40004000, 0x7000000: 0x10, 0x8000000: 0x84000, 0x9000000: 0x40004010, 0xa000000: 0x40000000, 0xb000000: 0x84010, 0xc000000: 0x80010, 0xd000000: 0x0, 0xe000000: 0x4010, 0xf000000: 0x40080000, 0x800000: 0x40004000, 0x1800000: 0x84010, 0x2800000: 0x10, 0x3800000: 0x40004010, 0x4800000: 0x40084010, 0x5800000: 0x40000000, 0x6800000: 0x80000, 0x7800000: 0x40080010, 0x8800000: 0x80010, 0x9800000: 0x0, 0xa800000: 0x4000, 0xb800000: 0x40080000, 0xc800000: 0x40000010, 0xd800000: 0x84000, 0xe800000: 0x40084000, 0xf800000: 0x4010, 0x10000000: 0x0, 0x11000000: 0x40080010, 0x12000000: 0x40004010, 0x13000000: 0x40084000, 0x14000000: 0x40080000, 0x15000000: 0x10, 0x16000000: 0x84010, 0x17000000: 0x4000, 0x18000000: 0x4010, 0x19000000: 0x80000, 0x1a000000: 0x80010, 0x1b000000: 0x40000010, 0x1c000000: 0x84000, 0x1d000000: 0x40004000, 0x1e000000: 0x40000000, 0x1f000000: 0x40084010, 0x10800000: 0x84010, 0x11800000: 0x80000, 0x12800000: 0x40080000, 0x13800000: 0x4000, 0x14800000: 0x40004000, 0x15800000: 0x40084010, 0x16800000: 0x10, 0x17800000: 0x40000000, 0x18800000: 0x40084000, 0x19800000: 0x40000010, 0x1a800000: 0x40004010, 0x1b800000: 0x80010, 0x1c800000: 0x0, 0x1d800000: 0x4010, 0x1e800000: 0x40080010, 0x1f800000: 0x84000 }, { 0x0: 0x104, 0x100000: 0x0, 0x200000: 0x4000100, 0x300000: 0x10104, 0x400000: 0x10004, 0x500000: 0x4000004, 0x600000: 0x4010104, 0x700000: 0x4010000, 0x800000: 0x4000000, 0x900000: 0x4010100, 0xa00000: 0x10100, 0xb00000: 0x4010004, 0xc00000: 0x4000104, 0xd00000: 0x10000, 0xe00000: 0x4, 0xf00000: 0x100, 0x80000: 0x4010100, 0x180000: 0x4010004, 0x280000: 0x0, 0x380000: 0x4000100, 0x480000: 0x4000004, 0x580000: 0x10000, 0x680000: 0x10004, 0x780000: 0x104, 0x880000: 0x4, 0x980000: 0x100, 0xa80000: 0x4010000, 0xb80000: 0x10104, 0xc80000: 0x10100, 0xd80000: 0x4000104, 0xe80000: 0x4010104, 0xf80000: 0x4000000, 0x1000000: 0x4010100, 0x1100000: 0x10004, 0x1200000: 0x10000, 0x1300000: 0x4000100, 0x1400000: 0x100, 0x1500000: 0x4010104, 0x1600000: 0x4000004, 0x1700000: 0x0, 0x1800000: 0x4000104, 0x1900000: 0x4000000, 0x1a00000: 0x4, 0x1b00000: 0x10100, 0x1c00000: 0x4010000, 0x1d00000: 0x104, 0x1e00000: 0x10104, 0x1f00000: 0x4010004, 0x1080000: 0x4000000, 0x1180000: 0x104, 0x1280000: 0x4010100, 0x1380000: 0x0, 0x1480000: 0x10004, 0x1580000: 0x4000100, 0x1680000: 0x100, 0x1780000: 0x4010004, 0x1880000: 0x10000, 0x1980000: 0x4010104, 0x1a80000: 0x10104, 0x1b80000: 0x4000004, 0x1c80000: 0x4000104, 0x1d80000: 0x4010000, 0x1e80000: 0x4, 0x1f80000: 0x10100 }, { 0x0: 0x80401000, 0x10000: 0x80001040, 0x20000: 0x401040, 0x30000: 0x80400000, 0x40000: 0x0, 0x50000: 0x401000, 0x60000: 0x80000040, 0x70000: 0x400040, 0x80000: 0x80000000, 0x90000: 0x400000, 0xa0000: 0x40, 0xb0000: 0x80001000, 0xc0000: 0x80400040, 0xd0000: 0x1040, 0xe0000: 0x1000, 0xf0000: 0x80401040, 0x8000: 0x80001040, 0x18000: 0x40, 0x28000: 0x80400040, 0x38000: 0x80001000, 0x48000: 0x401000, 0x58000: 0x80401040, 0x68000: 0x0, 0x78000: 0x80400000, 0x88000: 0x1000, 0x98000: 0x80401000, 0xa8000: 0x400000, 0xb8000: 0x1040, 0xc8000: 0x80000000, 0xd8000: 0x400040, 0xe8000: 0x401040, 0xf8000: 0x80000040, 0x100000: 0x400040, 0x110000: 0x401000, 0x120000: 0x80000040, 0x130000: 0x0, 0x140000: 0x1040, 0x150000: 0x80400040, 0x160000: 0x80401000, 0x170000: 0x80001040, 0x180000: 0x80401040, 0x190000: 0x80000000, 0x1a0000: 0x80400000, 0x1b0000: 0x401040, 0x1c0000: 0x80001000, 0x1d0000: 0x400000, 0x1e0000: 0x40, 0x1f0000: 0x1000, 0x108000: 0x80400000, 0x118000: 0x80401040, 0x128000: 0x0, 0x138000: 0x401000, 0x148000: 0x400040, 0x158000: 0x80000000, 0x168000: 0x80001040, 0x178000: 0x40, 0x188000: 0x80000040, 0x198000: 0x1000, 0x1a8000: 0x80001000, 0x1b8000: 0x80400040, 0x1c8000: 0x1040, 0x1d8000: 0x80401000, 0x1e8000: 0x400000, 0x1f8000: 0x401040 }, { 0x0: 0x80, 0x1000: 0x1040000, 0x2000: 0x40000, 0x3000: 0x20000000, 0x4000: 0x20040080, 0x5000: 0x1000080, 0x6000: 0x21000080, 0x7000: 0x40080, 0x8000: 0x1000000, 0x9000: 0x20040000, 0xa000: 0x20000080, 0xb000: 0x21040080, 0xc000: 0x21040000, 0xd000: 0x0, 0xe000: 0x1040080, 0xf000: 0x21000000, 0x800: 0x1040080, 0x1800: 0x21000080, 0x2800: 0x80, 0x3800: 0x1040000, 0x4800: 0x40000, 0x5800: 0x20040080, 0x6800: 0x21040000, 0x7800: 0x20000000, 0x8800: 0x20040000, 0x9800: 0x0, 0xa800: 0x21040080, 0xb800: 0x1000080, 0xc800: 0x20000080, 0xd800: 0x21000000, 0xe800: 0x1000000, 0xf800: 0x40080, 0x10000: 0x40000, 0x11000: 0x80, 0x12000: 0x20000000, 0x13000: 0x21000080, 0x14000: 0x1000080, 0x15000: 0x21040000, 0x16000: 0x20040080, 0x17000: 0x1000000, 0x18000: 0x21040080, 0x19000: 0x21000000, 0x1a000: 0x1040000, 0x1b000: 0x20040000, 0x1c000: 0x40080, 0x1d000: 0x20000080, 0x1e000: 0x0, 0x1f000: 0x1040080, 0x10800: 0x21000080, 0x11800: 0x1000000, 0x12800: 0x1040000, 0x13800: 0x20040080, 0x14800: 0x20000000, 0x15800: 0x1040080, 0x16800: 0x80, 0x17800: 0x21040000, 0x18800: 0x40080, 0x19800: 0x21040080, 0x1a800: 0x0, 0x1b800: 0x21000000, 0x1c800: 0x1000080, 0x1d800: 0x40000, 0x1e800: 0x20040000, 0x1f800: 0x20000080 }, { 0x0: 0x10000008, 0x100: 0x2000, 0x200: 0x10200000, 0x300: 0x10202008, 0x400: 0x10002000, 0x500: 0x200000, 0x600: 0x200008, 0x700: 0x10000000, 0x800: 0x0, 0x900: 0x10002008, 0xa00: 0x202000, 0xb00: 0x8, 0xc00: 0x10200008, 0xd00: 0x202008, 0xe00: 0x2008, 0xf00: 0x10202000, 0x80: 0x10200000, 0x180: 0x10202008, 0x280: 0x8, 0x380: 0x200000, 0x480: 0x202008, 0x580: 0x10000008, 0x680: 0x10002000, 0x780: 0x2008, 0x880: 0x200008, 0x980: 0x2000, 0xa80: 0x10002008, 0xb80: 0x10200008, 0xc80: 0x0, 0xd80: 0x10202000, 0xe80: 0x202000, 0xf80: 0x10000000, 0x1000: 0x10002000, 0x1100: 0x10200008, 0x1200: 0x10202008, 0x1300: 0x2008, 0x1400: 0x200000, 0x1500: 0x10000000, 0x1600: 0x10000008, 0x1700: 0x202000, 0x1800: 0x202008, 0x1900: 0x0, 0x1a00: 0x8, 0x1b00: 0x10200000, 0x1c00: 0x2000, 0x1d00: 0x10002008, 0x1e00: 0x10202000, 0x1f00: 0x200008, 0x1080: 0x8, 0x1180: 0x202000, 0x1280: 0x200000, 0x1380: 0x10000008, 0x1480: 0x10002000, 0x1580: 0x2008, 0x1680: 0x10202008, 0x1780: 0x10200000, 0x1880: 0x10202000, 0x1980: 0x10200008, 0x1a80: 0x2000, 0x1b80: 0x202008, 0x1c80: 0x200008, 0x1d80: 0x0, 0x1e80: 0x10000000, 0x1f80: 0x10002008 }, { 0x0: 0x100000, 0x10: 0x2000401, 0x20: 0x400, 0x30: 0x100401, 0x40: 0x2100401, 0x50: 0x0, 0x60: 0x1, 0x70: 0x2100001, 0x80: 0x2000400, 0x90: 0x100001, 0xa0: 0x2000001, 0xb0: 0x2100400, 0xc0: 0x2100000, 0xd0: 0x401, 0xe0: 0x100400, 0xf0: 0x2000000, 0x8: 0x2100001, 0x18: 0x0, 0x28: 0x2000401, 0x38: 0x2100400, 0x48: 0x100000, 0x58: 0x2000001, 0x68: 0x2000000, 0x78: 0x401, 0x88: 0x100401, 0x98: 0x2000400, 0xa8: 0x2100000, 0xb8: 0x100001, 0xc8: 0x400, 0xd8: 0x2100401, 0xe8: 0x1, 0xf8: 0x100400, 0x100: 0x2000000, 0x110: 0x100000, 0x120: 0x2000401, 0x130: 0x2100001, 0x140: 0x100001, 0x150: 0x2000400, 0x160: 0x2100400, 0x170: 0x100401, 0x180: 0x401, 0x190: 0x2100401, 0x1a0: 0x100400, 0x1b0: 0x1, 0x1c0: 0x0, 0x1d0: 0x2100000, 0x1e0: 0x2000001, 0x1f0: 0x400, 0x108: 0x100400, 0x118: 0x2000401, 0x128: 0x2100001, 0x138: 0x1, 0x148: 0x2000000, 0x158: 0x100000, 0x168: 0x401, 0x178: 0x2100400, 0x188: 0x2000001, 0x198: 0x2100000, 0x1a8: 0x0, 0x1b8: 0x2100401, 0x1c8: 0x100401, 0x1d8: 0x400, 0x1e8: 0x2000400, 0x1f8: 0x100001 }, { 0x0: 0x8000820, 0x1: 0x20000, 0x2: 0x8000000, 0x3: 0x20, 0x4: 0x20020, 0x5: 0x8020820, 0x6: 0x8020800, 0x7: 0x800, 0x8: 0x8020000, 0x9: 0x8000800, 0xa: 0x20800, 0xb: 0x8020020, 0xc: 0x820, 0xd: 0x0, 0xe: 0x8000020, 0xf: 0x20820, 0x80000000: 0x800, 0x80000001: 0x8020820, 0x80000002: 0x8000820, 0x80000003: 0x8000000, 0x80000004: 0x8020000, 0x80000005: 0x20800, 0x80000006: 0x20820, 0x80000007: 0x20, 0x80000008: 0x8000020, 0x80000009: 0x820, 0x8000000a: 0x20020, 0x8000000b: 0x8020800, 0x8000000c: 0x0, 0x8000000d: 0x8020020, 0x8000000e: 0x8000800, 0x8000000f: 0x20000, 0x10: 0x20820, 0x11: 0x8020800, 0x12: 0x20, 0x13: 0x800, 0x14: 0x8000800, 0x15: 0x8000020, 0x16: 0x8020020, 0x17: 0x20000, 0x18: 0x0, 0x19: 0x20020, 0x1a: 0x8020000, 0x1b: 0x8000820, 0x1c: 0x8020820, 0x1d: 0x20800, 0x1e: 0x820, 0x1f: 0x8000000, 0x80000010: 0x20000, 0x80000011: 0x800, 0x80000012: 0x8020020, 0x80000013: 0x20820, 0x80000014: 0x20, 0x80000015: 0x8020000, 0x80000016: 0x8000000, 0x80000017: 0x8000820, 0x80000018: 0x8020820, 0x80000019: 0x8000020, 0x8000001a: 0x8000800, 0x8000001b: 0x0, 0x8000001c: 0x20800, 0x8000001d: 0x820, 0x8000001e: 0x20020, 0x8000001f: 0x8020800 } ]; // Masks that select the SBOX input var SBOX_MASK = [ 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f ]; /** * DES block cipher algorithm. */ var DES = C_algo.DES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Select 56 bits according to PC1 var keyBits = []; for (var i = 0; i < 56; i++) { var keyBitPos = PC1[i] - 1; keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; } // Assemble 16 subkeys var subKeys = this._subKeys = []; for (var nSubKey = 0; nSubKey < 16; nSubKey++) { // Create subkey var subKey = subKeys[nSubKey] = []; // Shortcut var bitShift = BIT_SHIFTS[nSubKey]; // Select 48 bits according to PC2 for (var i = 0; i < 24; i++) { // Select from the left 28 key bits subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); // Select from the right 28 key bits subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); } // Since each subkey is applied to an expanded 32-bit input, // the subkey can be broken into 8 values scaled to 32-bits, // which allows the key to be used without expansion subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); for (var i = 1; i < 7; i++) { subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); } subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); } // Compute inverse subkeys var invSubKeys = this._invSubKeys = []; for (var i = 0; i < 16; i++) { invSubKeys[i] = subKeys[15 - i]; } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._subKeys); }, decryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._invSubKeys); }, _doCryptBlock: function (M, offset, subKeys) { // Get input this._lBlock = M[offset]; this._rBlock = M[offset + 1]; // Initial permutation exchangeLR.call(this, 4, 0x0f0f0f0f); exchangeLR.call(this, 16, 0x0000ffff); exchangeRL.call(this, 2, 0x33333333); exchangeRL.call(this, 8, 0x00ff00ff); exchangeLR.call(this, 1, 0x55555555); // Rounds for (var round = 0; round < 16; round++) { // Shortcuts var subKey = subKeys[round]; var lBlock = this._lBlock; var rBlock = this._rBlock; // Feistel function var f = 0; for (var i = 0; i < 8; i++) { f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; } this._lBlock = rBlock; this._rBlock = lBlock ^ f; } // Undo swap from last round var t = this._lBlock; this._lBlock = this._rBlock; this._rBlock = t; // Final permutation exchangeLR.call(this, 1, 0x55555555); exchangeRL.call(this, 8, 0x00ff00ff); exchangeRL.call(this, 2, 0x33333333); exchangeLR.call(this, 16, 0x0000ffff); exchangeLR.call(this, 4, 0x0f0f0f0f); // Set output M[offset] = this._lBlock; M[offset + 1] = this._rBlock; }, keySize: 64/32, ivSize: 64/32, blockSize: 64/32 }); // Swap bits across the left and right words function exchangeLR(offset, mask) { var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; } function exchangeRL(offset, mask) { var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; this._lBlock ^= t; this._rBlock ^= t << offset; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); */ C.DES = BlockCipher._createHelper(DES); /** * Triple-DES block cipher algorithm. */ var TripleDES = C_algo.TripleDES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Create DES instances this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); }, encryptBlock: function (M, offset) { this._des1.encryptBlock(M, offset); this._des2.decryptBlock(M, offset); this._des3.encryptBlock(M, offset); }, decryptBlock: function (M, offset) { this._des3.decryptBlock(M, offset); this._des2.encryptBlock(M, offset); this._des1.decryptBlock(M, offset); }, keySize: 192/32, ivSize: 64/32, blockSize: 64/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); */ C.TripleDES = BlockCipher._createHelper(TripleDES); }()); return CryptoJS.TripleDES; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":44}],76:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],77:[function(_dereq_,module,exports){ (function (process,global){ /*! localForage -- Offline Storage, Improved Version 1.3.0 https://mozilla.github.io/localForage (c) 2013-2015 Mozilla, Apache License 2.0 */ (function() { var define, requireModule, _dereq_, requirejs; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requirejs = _dereq_ = requireModule = function(name) { requirejs._eak_seen = registry; if (seen[name]) { return seen[name]; } seen[name] = {}; if (!registry[name]) { throw new Error("Could not find module " + name); } var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(resolve(deps[i]))); } } var value = callback.apply(this, reified); return seen[name] = exports || value; function resolve(child) { if (child.charAt(0) !== '.') { return child; } var parts = child.split("/"); var parentBase = name.split("/").slice(0, -1); for (var i=0, l=parts.length; i<l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join("/"); } }; })(); define("promise/all", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; var isFunction = __dependency1__.isFunction; /** Returns a promise that is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The return promise is fulfilled with an array that gives all the values in the order they were passed in the `promises` array argument. Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `RSVP.all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error("2")); var promise3 = RSVP.reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @for RSVP @param {Array} promises @param {String} label @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. */ function all(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to all.'); } return new Promise(function(resolve, reject) { var results = [], remaining = promises.length, promise; if (remaining === 0) { resolve([]); } function resolver(index) { return function(value) { resolveAll(index, value); }; } function resolveAll(index, value) { results[index] = value; if (--remaining === 0) { resolve(results); } } for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && isFunction(promise.then)) { promise.then(resolver(i), reject); } else { resolveAll(i, promise); } } }); } __exports__.all = all; }); define("promise/asap", ["exports"], function(__exports__) { "use strict"; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this); // node function useNextTick() { return function() { process.nextTick(flush); }; } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } function useSetTimeout() { return function() { local.setTimeout(flush, 1); }; } var queue = []; function flush() { for (var i = 0; i < queue.length; i++) { var tuple = queue[i]; var callback = tuple[0], arg = tuple[1]; callback(arg); } queue = []; } var scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else { scheduleFlush = useSetTimeout(); } function asap(callback, arg) { var length = queue.push([callback, arg]); if (length === 1) { // If length is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. scheduleFlush(); } } __exports__.asap = asap; }); define("promise/config", ["exports"], function(__exports__) { "use strict"; var config = { instrument: false }; function configure(name, value) { if (arguments.length === 2) { config[name] = value; } else { return config[name]; } } __exports__.config = config; __exports__.configure = configure; }); define("promise/polyfill", ["./promise","./utils","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /*global self*/ var RSVPPromise = __dependency1__.Promise; var isFunction = __dependency2__.isFunction; function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = RSVPPromise; } } __exports__.polyfill = polyfill; }); define("promise/promise", ["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) { "use strict"; var config = __dependency1__.config; var configure = __dependency1__.configure; var objectOrFunction = __dependency2__.objectOrFunction; var isFunction = __dependency2__.isFunction; var now = __dependency2__.now; var all = __dependency3__.all; var race = __dependency4__.race; var staticResolve = __dependency5__.resolve; var staticReject = __dependency6__.reject; var asap = __dependency7__.asap; var counter = 0; config.async = asap; // default async is asap; function Promise(resolver) { if (!isFunction(resolver)) { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } if (!(this instanceof Promise)) { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } this._subscribers = []; invokeResolver(resolver, this); } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch(e) { rejectPromise(e); } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value, error, succeeded, failed; if (hasCallback) { try { value = callback(detail); succeeded = true; } catch(e) { failed = true; error = e; } } else { value = detail; succeeded = true; } if (handleThenable(promise, value)) { return; } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { resolve(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } var PENDING = void 0; var SEALED = 0; var FULFILLED = 1; var REJECTED = 2; function subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; subscribers[length] = child; subscribers[length + FULFILLED] = onFulfillment; subscribers[length + REJECTED] = onRejection; } function publish(promise, settled) { var child, callback, subscribers = promise._subscribers, detail = promise._detail; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; invokeCallback(settled, child, callback, detail); } promise._subscribers = null; } Promise.prototype = { constructor: Promise, _state: undefined, _detail: undefined, _subscribers: undefined, then: function(onFulfillment, onRejection) { var promise = this; var thenPromise = new this.constructor(function() {}); if (this._state) { var callbacks = arguments; config.async(function invokePromiseCallback() { invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); }); } else { subscribe(this, thenPromise, onFulfillment, onRejection); } return thenPromise; }, 'catch': function(onRejection) { return this.then(null, onRejection); } }; Promise.all = all; Promise.race = race; Promise.resolve = staticResolve; Promise.reject = staticReject; function handleThenable(promise, value) { var then = null, resolved; try { if (promise === value) { throw new TypeError("A promises callback cannot return that same promise."); } if (objectOrFunction(value)) { then = value.then; if (isFunction(then)) { then.call(value, function(val) { if (resolved) { return true; } resolved = true; if (value !== val) { resolve(promise, val); } else { fulfill(promise, val); } }, function(val) { if (resolved) { return true; } resolved = true; reject(promise, val); }); return true; } } } catch (error) { if (resolved) { return true; } reject(promise, error); return true; } return false; } function resolve(promise, value) { if (promise === value) { fulfill(promise, value); } else if (!handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = value; config.async(publishFulfillment, promise); } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = reason; config.async(publishRejection, promise); } function publishFulfillment(promise) { publish(promise, promise._state = FULFILLED); } function publishRejection(promise) { publish(promise, promise._state = REJECTED); } __exports__.Promise = Promise; }); define("promise/race", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; /** `RSVP.race` allows you to watch a series of promises and act as soon as the first promise given to the `promises` argument fulfills or rejects. Example: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 2"); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // result === "promise 2" because it was resolved before promise1 // was resolved. }); ``` `RSVP.race` is deterministic in that only the state of the first completed promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first completed promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error("promise 2")); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // Code here never runs because there are rejected promises! }, function(reason){ // reason.message === "promise2" because promise 2 became rejected before // promise 1 became fulfilled }); ``` @method race @for RSVP @param {Array} promises array of promises to observe @param {String} label optional string for describing the promise returned. Useful for tooling. @return {Promise} a promise that becomes fulfilled with the value the first completed promises is resolved with if the first completed promise was fulfilled, or rejected with the reason that the first completed promise was rejected with. */ function race(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to race.'); } return new Promise(function(resolve, reject) { var results = [], promise; for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolve, reject); } else { resolve(promise); } } }); } __exports__.race = race; }); define("promise/reject", ["exports"], function(__exports__) { "use strict"; /** `RSVP.reject` returns a promise that will become rejected with the passed `reason`. `RSVP.reject` is essentially shorthand for the following: ```javascript var promise = new RSVP.Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript var promise = RSVP.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @for RSVP @param {Any} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Promise = this; return new Promise(function (resolve, reject) { reject(reason); }); } __exports__.reject = reject; }); define("promise/resolve", ["exports"], function(__exports__) { "use strict"; function resolve(value) { /*jshint validthis:true */ if (value && typeof value === 'object' && value.constructor === this) { return value; } var Promise = this; return new Promise(function(resolve) { resolve(value); }); } __exports__.resolve = resolve; }); define("promise/utils", ["exports"], function(__exports__) { "use strict"; function objectOrFunction(x) { return isFunction(x) || (typeof x === "object" && x !== null); } function isFunction(x) { return typeof x === "function"; } function isArray(x) { return Object.prototype.toString.call(x) === "[object Array]"; } // Date.now is not available in browsers < IE9 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility var now = Date.now || function() { return new Date().getTime(); }; __exports__.objectOrFunction = objectOrFunction; __exports__.isFunction = isFunction; __exports__.isArray = isArray; __exports__.now = now; }); requireModule('promise/polyfill').polyfill(); }());(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["localforage"] = factory(); else root["localforage"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { 'use strict'; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE]; var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function (self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function () { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function () { try { return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem; } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function () { var _args = arguments; return localForageInstance.ready().then(function () { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var LocalForage = (function () { function LocalForage(options) { _classCallCheck(this, LocalForage); this.INDEXEDDB = DriverType.INDEXEDDB; this.LOCALSTORAGE = DriverType.LOCALSTORAGE; this.WEBSQL = DriverType.WEBSQL; this._defaultConfig = extend({}, DefaultConfig); this._config = extend({}, this._defaultConfig, options); this._driverSet = null; this._initDriver = null; this._ready = false; this._dbInfo = null; this._wrapLibraryMethodsWithReady(); this.setDriver(this._config.driver); } // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function config(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof options === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof options === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { var promise = new Promise(function (resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); var namingError = new Error('Custom driver name already in use: ' + driverObject._driver); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function (supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); promise.then(callback, errorCallback); return promise; }; LocalForage.prototype.driver = function driver() { return this._driver || null; }; LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { var self = this; var getDriverPromise = (function () { if (isLibraryDriver(driverName)) { switch (driverName) { case self.INDEXEDDB: return new Promise(function (resolve, reject) { resolve(__webpack_require__(1)); }); case self.LOCALSTORAGE: return new Promise(function (resolve, reject) { resolve(__webpack_require__(2)); }); case self.WEBSQL: return new Promise(function (resolve, reject) { resolve(__webpack_require__(4)); }); } } else if (CustomDrivers[driverName]) { return Promise.resolve(CustomDrivers[driverName]); } return Promise.reject(new Error('Driver not found.')); })(); getDriverPromise.then(callback, errorCallback); return getDriverPromise; }; LocalForage.prototype.getSerializer = function getSerializer(callback) { var serializerPromise = new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }); if (callback && typeof callback === 'function') { serializerPromise.then(function (result) { callback(result); }); } return serializerPromise; }; LocalForage.prototype.ready = function ready(callback) { var self = this; var promise = self._driverSet.then(function () { if (self._ready === null) { self._ready = self._initDriver(); } return self._ready; }); promise.then(callback, callback); return promise; }; LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { var self = this; if (!isArray(drivers)) { drivers = [drivers]; } var supportedDrivers = this._getSupportedDrivers(drivers); function setDriverToConfig() { self._config.driver = self.driver(); } function initDriver(supportedDrivers) { return function () { var currentDriverIndex = 0; function driverPromiseLoop() { while (currentDriverIndex < supportedDrivers.length) { var driverName = supportedDrivers[currentDriverIndex]; currentDriverIndex++; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._extend(driver); setDriverToConfig(); self._ready = self._initStorage(self._config); return self._ready; })['catch'](driverPromiseLoop); } setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; } return driverPromiseLoop(); }; } // There might be a driver initialization in progress // so wait for it to finish in order to avoid a possible // race condition to set _dbInfo var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () { return Promise.resolve(); }) : Promise.resolve(); this._driverSet = oldDriverSetDone.then(function () { var driverName = supportedDrivers[0]; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._driver = driver._driver; setDriverToConfig(); self._wrapLibraryMethodsWithReady(); self._initDriver = initDriver(supportedDrivers); }); })['catch'](function () { setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; }); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function supports(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { var supportedDrivers = []; for (var i = 0, len = drivers.length; i < len; i++) { var driverName = drivers[i]; if (this.supports(driverName)) { supportedDrivers.push(driverName); } } return supportedDrivers; }; LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } }; LocalForage.prototype.createInstance = function createInstance(options) { return new LocalForage(options); }; return LocalForage; })(); var localForage = new LocalForage(); exports['default'] = localForage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 1 */ /***/ function(module, exports) { // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; var dbContexts; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // Fetch a blob using ajax. This reveals bugs in Chrome < 43. // For details on all this junk: // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme function _blobAjax(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function () { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { return resolve({ response: xhr.response, type: xhr.getResponseHeader('Content-Type') }); } reject({ status: xhr.status, response: xhr.response }); }; xhr.send(); }); } // // Detect blob support. Chrome didn't support it until version 38. // In version 37 they had a broken version where PNGs (and possibly // other binary types) aren't stored correctly, because when you fetch // them, the content type is always null. // // Furthermore, they have some outstanding bugs where blobs occasionally // are read by FileReader as null, or by ajax as 404s. // // Sadly we use the 404 bug to detect the FileReader bug, so if they // get fixed independently and released in different versions of Chrome, // then the bug could come back. So it's worthwhile to watch these issues: // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // function _checkBlobSupportWithoutCaching(idb) { return new Promise(function (resolve, reject) { var blob = _createBlob([''], { type: 'image/png' }); var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.oncomplete = function () { // have to do it in a separate transaction, else the correct // content type is always returned var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key'); getBlobReq.onerror = reject; getBlobReq.onsuccess = function (e) { var storedBlob = e.target.result; var url = URL.createObjectURL(storedBlob); _blobAjax(url).then(function (res) { resolve(!!(res && res.type === 'image/png')); }, function () { resolve(false); }).then(function () { URL.revokeObjectURL(url); }); }; }; })['catch'](function () { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function (value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function (resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function (e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type }); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } // Initialize a singleton container for all running localForages. if (!dbContexts) { dbContexts = {}; } // Get the current context of the database; var dbContext = dbContexts[dbInfo.name]; // ...or create a new context. if (!dbContext) { dbContext = { // Running localForages sharing a database. forages: [], // Shared database. db: null }; // Register the new context in the global container. dbContexts[dbInfo.name] = dbContext; } // Register itself as a running localForage in the current context. dbContext.forages.push(this); // Create an array of readiness of the related localForages. var readyPromises = []; function ignoreErrors() { // Don't handle errors here, // just makes sure related localForages aren't pending. return Promise.resolve(); } for (var j = 0; j < dbContext.forages.length; j++) { var forage = dbContext.forages[j]; if (forage !== this) { // Don't wait for itself... readyPromises.push(forage.ready()['catch'](ignoreErrors)); } } // Take a snapshot of the related localForages. var forages = dbContext.forages.slice(0); // Initialize the connection process only when // all the related localForages aren't pending. return Promise.all(readyPromises).then(function () { dbInfo.db = dbContext.db; // Get the connection or open a new one without upgrade. return _getOriginalConnection(dbInfo); }).then(function (db) { dbInfo.db = db; if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } return db; }).then(function (db) { dbInfo.db = dbContext.db = db; self._dbInfo = dbInfo; // Share the final connection amongst related localForages. for (var k in forages) { var forage = forages[k]; if (forage !== self) { // Self is already up-to-date. forage._dbInfo.db = dbInfo.db; forage._dbInfo.version = dbInfo.version; } } }); } function _getOriginalConnection(dbInfo) { return _getConnection(dbInfo, false); } function _getUpgradedConnection(dbInfo) { return _getConnection(dbInfo, true); } function _getConnection(dbInfo, upgradeNeeded) { return new Promise(function (resolve, reject) { if (dbInfo.db) { if (upgradeNeeded) { dbInfo.db.close(); } else { return resolve(dbInfo.db); } } var dbArgs = [dbInfo.name]; if (upgradeNeeded) { dbArgs.push(dbInfo.version); } var openreq = indexedDB.open.apply(indexedDB, dbArgs); if (upgradeNeeded) { openreq.onupgradeneeded = function (e) { var db = openreq.result; try { db.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // Added when support for blob shims was added db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } } catch (ex) { if (ex.name === 'ConstraintError') { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); } else { throw ex; } } }; } openreq.onerror = function () { reject(openreq.error); }; openreq.onsuccess = function () { resolve(openreq.result); }; }); } function _isUpgradeNeeded(dbInfo, defaultVersion) { if (!dbInfo.db) { return true; } var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); var isDowngrade = dbInfo.version < dbInfo.db.version; var isUpgrade = dbInfo.version > dbInfo.db.version; if (isDowngrade) { // If the version is not the default one // then warn for impossible downgrade. if (dbInfo.version !== defaultVersion) { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); } // Align the versions to prevent errors. dbInfo.version = dbInfo.db.version; } if (isUpgrade || isNewStore) { // If the store is new then increment the version (if needed). // This will trigger an "upgradeneeded" event which is required // for creating a store. if (isNewStore) { var incVersion = dbInfo.db.version + 1; if (incVersion > dbInfo.version) { dbInfo.version = incVersion; } } return true; } return false; } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function () { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function () { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void 0) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { var dbInfo; self.ready().then(function () { dbInfo = self._dbInfo; return _checkBlobSupport(dbInfo.db); }).then(function (blobSupport) { if (!blobSupport && value instanceof Blob) { return _encodeBlob(value); } return value; }).then(function (value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function () { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function () { resolve(); }; transaction.onerror = function () { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function () { resolve(); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function () { resolve(req.result); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function () { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function () { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = asyncStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; if (dbInfo.storeName !== self._defaultConfig.storeName) { dbInfo.keyPrefix += dbInfo.storeName + '/'; } self._dbInfo = dbInfo; return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function () { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = dbInfo.serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var keyPrefix = dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = dbInfo.serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void 0) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function (keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function (resolve, reject) { var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { try { localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = localStorageWrapper; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; (function () { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Get out of our habit of using `window` inline, at least. var globalObject = this; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function () { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], { type: blobType }); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i += 4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); /*jslint bitwise: true */ bytes[p++] = encoded1 << 2 | encoded2 >> 4; bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if (bytes.length % 3 === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; exports['default'] = localforageSerializer; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; } } var dbInfoPromise = new Promise(function (resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function () { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); }); }); return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = dbInfo.serializer.deserialize(result); } resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = dbInfo.serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void 0) { resolve(result); return; } } resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { dbInfo.db.transaction(function (t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () { resolve(originalValue); }, function (t, error) { reject(error); }); }, function (sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { var result = results.rows.item(0).c; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = webSQLStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ } /******/ ]) }); ; }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":76}],78:[function(_dereq_,module,exports){ // Top level file is just a mixin of submodules & constants 'use strict'; var assign = _dereq_('./lib/utils/common').assign; var deflate = _dereq_('./lib/deflate'); var inflate = _dereq_('./lib/inflate'); var constants = _dereq_('./lib/zlib/constants'); var pako = {}; assign(pako, deflate, inflate, constants); module.exports = pako; },{"./lib/deflate":79,"./lib/inflate":80,"./lib/utils/common":81,"./lib/zlib/constants":84}],79:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_SYNC_FLUSH = 2; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overriden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Deflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ var Deflate = function(options) { this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } }; /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be * converted to utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the compression context. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === Z_SYNC_FLUSH) { this.onEnd(Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function(status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate alrorythm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; },{"./utils/common":81,"./utils/strings":82,"./zlib/deflate.js":86,"./zlib/messages":91,"./zlib/zstream":93}],80:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var c = _dereq_('./zlib/constants'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var gzheader = _dereq_('./zlib/gzheader'); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overriden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ var Inflate = function(options) { this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new gzheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); }; /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; var next_out_utf8, tail, utf8str; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function(status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 alligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; },{"./utils/common":81,"./utils/strings":82,"./zlib/constants":84,"./zlib/gzheader":87,"./zlib/inflate.js":89,"./zlib/messages":91,"./zlib/zstream":93}],81:[function(_dereq_,module,exports){ 'use strict'; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (source.hasOwnProperty(p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs+len), dest_offs); return; } // Fallback to ordinary array for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i=0, l=chunks.length; i<l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i=0, l=chunks.length; i<l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); },{}],82:[function(_dereq_,module,exports){ // String encode/decode helpers 'use strict'; var utils = _dereq_('./common'); // Quick check if we can use fast array to bin string conversion // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safary // var STR_APPLY_OK = true; var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new utils.Buf8(256); for (var q=0; q<256; q++) { _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); } _utf8len[254]=_utf8len[254]=1; // Invalid sequence start // convert string to array (typed, when possible) exports.string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new utils.Buf8(buf_len); // convert for (i=0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Helper (used in 2 places) function buf2binstring(buf, len) { // use fallback for big arrays to avoid stack overflow if (len < 65537) { if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); } } var result = ''; for (var i=0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; } // Convert byte array to binary string exports.buf2binstring = function(buf) { return buf2binstring(buf, buf.length); }; // Convert binary string (typed, when possible) exports.binstring2buf = function(str) { var buf = new utils.Buf8(str.length); for (var i=0, len=buf.length; i < len; i++) { buf[i] = str.charCodeAt(i); } return buf; }; // convert array to string exports.buf2string = function (buf, max) { var i, out, c, c_len; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len*2); for (out=0, i=0; i<len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); exports.utf8border = function(buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max-1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; },{"./common":81}],83:[function(_dereq_,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It doesn't worth to make additional optimizationa as in original. // Small size is preferable. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; },{}],84:[function(_dereq_,module,exports){ module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],85:[function(_dereq_,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n =0; n < 256; n++) { c = n; for (var k =0; k < 8; k++) { c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc = crc ^ (-1); for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],86:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var trees = _dereq_('./trees'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var msg = _dereq_('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only (s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH-1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length-1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH-1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ var Config = function (good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; }; var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2); this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; s.pending_buf = new utils.Buf8(s.pending_buf_size); s.d_buf = s.lit_bufsize >> 1; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Copy the source state to the destination state */ //function deflateCopy(dest, source) { // //} exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":81,"./adler32":83,"./crc32":85,"./messages":91,"./trees":92}],87:[function(_dereq_,module,exports){ 'use strict'; function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } module.exports = GZheader; },{}],88:[function(_dereq_,module,exports){ 'use strict'; // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; },{}],89:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var inflate_fast = _dereq_('./inffast'); var inflate_table = _dereq_('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function ZSWAP32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9}); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5}); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window,src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window,src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more conveniend processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = ZSWAP32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = {bits: state.lenbits}; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = {bits: state.lenbits}; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = {bits: state.distbits}; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' insdead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":81,"./adler32":83,"./crc32":85,"./inffast":88,"./inftrees":90}],90:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; var lext = [ /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 ]; var dbase = [ /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 ]; var dext = [ /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } var i=0; /* process all codes and make table entries */ for (;;) { i++; /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; },{"../utils/common":81}],91:[function(_dereq_,module,exports){ 'use strict'; module.exports = { '2': 'need dictionary', /* Z_NEED_DICT 2 */ '1': 'stream end', /* Z_STREAM_END 1 */ '0': '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; },{}],92:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ var extra_lbits = /* extra bits for each length code */ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; var extra_dbits = /* extra bits for each distance code */ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES+2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH-MIN_MATCH+1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; }; var static_l_desc; var static_d_desc; var static_bl_desc; var TreeDesc = function(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ }; function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short (s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max+1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n*2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n-base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits+1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m*2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/; tree[m*2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits-1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n*2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1<<extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length-1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<<extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n*2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n*2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES+1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n*2 + 1]/*.Len*/ = 5; static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n*2; var _m2 = m*2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j+1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n*2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node*2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6*2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10*2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138*2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count-3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count-3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count-11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3*(max_blindex+1) + 5+5+4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes-1, 5); send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len+3+7) >>> 3; static_lenb = (s.static_len+3+7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len+4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc*2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize-1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":81}],93:[function(_dereq_,module,exports){ 'use strict'; function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; },{}],94:[function(_dereq_,module,exports){ /* * Copyright 2012-2013 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define, location) { 'use strict'; var undef; define(function (_dereq_) { var mixin, origin, urlRE, absoluteUrlRE, fullyQualifiedUrlRE; mixin = _dereq_('./util/mixin'); urlRE = /([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?(\/[^?#]*)?(\?[^#]*)?(#\S*)?/i; absoluteUrlRE = /^([a-z][a-z0-9\-\+\.]*:\/\/|\/)/i; fullyQualifiedUrlRE = /([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?\//i; /** * Apply params to the template to create a URL. * * Parameters that are not applied directly to the template, are appended * to the URL as query string parameters. * * @param {string} template the URI template * @param {Object} params parameters to apply to the template * @return {string} the resulting URL */ function buildUrl(template, params) { // internal builder to convert template with params. var url, name, queryStringParams, re; url = template; queryStringParams = {}; if (params) { for (name in params) { /*jshint forin:false */ re = new RegExp('\\{' + name + '\\}'); if (re.test(url)) { url = url.replace(re, encodeURIComponent(params[name]), 'g'); } else { queryStringParams[name] = params[name]; } } for (name in queryStringParams) { url += url.indexOf('?') === -1 ? '?' : '&'; url += encodeURIComponent(name); if (queryStringParams[name] !== null && queryStringParams[name] !== undefined) { url += '='; url += encodeURIComponent(queryStringParams[name]); } } } return url; } function startsWith(str, test) { return str.indexOf(test) === 0; } /** * Create a new URL Builder * * @param {string|UrlBuilder} template the base template to build from, may be another UrlBuilder * @param {Object} [params] base parameters * @constructor */ function UrlBuilder(template, params) { if (!(this instanceof UrlBuilder)) { // invoke as a constructor return new UrlBuilder(template, params); } if (template instanceof UrlBuilder) { this._template = template.template; this._params = mixin({}, this._params, params); } else { this._template = (template || '').toString(); this._params = params || {}; } } UrlBuilder.prototype = { /** * Create a new UrlBuilder instance that extends the current builder. * The current builder is unmodified. * * @param {string} [template] URL template to append to the current template * @param {Object} [params] params to combine with current params. New params override existing params * @return {UrlBuilder} the new builder */ append: function (template, params) { // TODO consider query strings and fragments return new UrlBuilder(this._template + template, mixin({}, this._params, params)); }, /** * Create a new UrlBuilder with a fully qualified URL based on the * window's location or base href and the current templates relative URL. * * Path variables are preserved. * * *Browser only* * * @return {UrlBuilder} the fully qualified URL template */ fullyQualify: function () { if (!location) { return this; } if (this.isFullyQualified()) { return this; } var template = this._template; if (startsWith(template, '//')) { template = origin.protocol + template; } else if (startsWith(template, '/')) { template = origin.origin + template; } else if (!this.isAbsolute()) { template = origin.origin + origin.pathname.substring(0, origin.pathname.lastIndexOf('/') + 1); } if (template.indexOf('/', 8) === -1) { // default the pathname to '/' template = template + '/'; } return new UrlBuilder(template, this._params); }, /** * True if the URL is absolute * * @return {boolean} */ isAbsolute: function () { return absoluteUrlRE.test(this.build()); }, /** * True if the URL is fully qualified * * @return {boolean} */ isFullyQualified: function () { return fullyQualifiedUrlRE.test(this.build()); }, /** * True if the URL is cross origin. The protocol, host and port must not be * the same in order to be cross origin, * * @return {boolean} */ isCrossOrigin: function () { if (!origin) { return true; } var url = this.parts(); return url.protocol !== origin.protocol || url.hostname !== origin.hostname || url.port !== origin.port; }, /** * Split a URL into its consituent parts following the naming convention of * 'window.location'. One difference is that the port will contain the * protocol default if not specified. * * @see https://developer.mozilla.org/en-US/docs/DOM/window.location * * @returns {Object} a 'window.location'-like object */ parts: function () { /*jshint maxcomplexity:20 */ var url, parts; url = this.fullyQualify().build().match(urlRE); parts = { href: url[0], protocol: url[1], host: url[3] || '', hostname: url[4] || '', port: url[6], pathname: url[7] || '', search: url[8] || '', hash: url[9] || '' }; parts.origin = parts.protocol + '//' + parts.host; parts.port = parts.port || (parts.protocol === 'https:' ? '443' : parts.protocol === 'http:' ? '80' : ''); return parts; }, /** * Expand the template replacing path variables with parameters * * @param {Object} [params] params to combine with current params. New params override existing params * @return {string} the expanded URL */ build: function (params) { return buildUrl(this._template, mixin({}, this._params, params)); }, /** * @see build */ toString: function () { return this.build(); } }; origin = location ? new UrlBuilder(location.href).parts() : undef; return UrlBuilder; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); }, typeof window !== 'undefined' ? window.location : void 0 // Boilerplate for AMD and Node )); },{"./util/mixin":130}],95:[function(_dereq_,module,exports){ /* * Copyright 2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var rest = _dereq_('./client/default'), browser = _dereq_('./client/xhr'); rest.setPlatformDefaultClient(browser); return rest; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"./client/default":97,"./client/xhr":98}],96:[function(_dereq_,module,exports){ /* * Copyright 2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { /** * Add common helper methods to a client impl * * @param {function} impl the client implementation * @param {Client} [target] target of this client, used when wrapping other clients * @returns {Client} the client impl with additional methods */ return function client(impl, target) { if (target) { /** * @returns {Client} the target client */ impl.skip = function skip() { return target; }; } /** * Allow a client to easily be wrapped by an interceptor * * @param {Interceptor} interceptor the interceptor to wrap this client with * @param [config] configuration for the interceptor * @returns {Client} the newly wrapped client */ impl.wrap = function wrap(interceptor, config) { return interceptor(impl, config); }; /** * @deprecated */ impl.chain = function chain() { if (typeof console !== 'undefined') { console.log('rest.js: client.chain() is deprecated, use client.wrap() instead'); } return impl.wrap.apply(this, arguments); }; return impl; }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],97:[function(_dereq_,module,exports){ /* * Copyright 2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; var undef; define(function (_dereq_) { /** * Plain JS Object containing properties that represent an HTTP request. * * Depending on the capabilities of the underlying client, a request * may be cancelable. If a request may be canceled, the client will add * a canceled flag and cancel function to the request object. Canceling * the request will put the response into an error state. * * @field {string} [method='GET'] HTTP method, commonly GET, POST, PUT, DELETE or HEAD * @field {string|UrlBuilder} [path=''] path template with optional path variables * @field {Object} [params] parameters for the path template and query string * @field {Object} [headers] custom HTTP headers to send, in addition to the clients default headers * @field [entity] the HTTP entity, common for POST or PUT requests * @field {boolean} [canceled] true if the request has been canceled, set by the client * @field {Function} [cancel] cancels the request if invoked, provided by the client * @field {Client} [originator] the client that first handled this request, provided by the interceptor * * @class Request */ /** * Plain JS Object containing properties that represent an HTTP response * * @field {Object} [request] the request object as received by the root client * @field {Object} [raw] the underlying request object, like XmlHttpRequest in a browser * @field {number} [status.code] status code of the response (i.e. 200, 404) * @field {string} [status.text] status phrase of the response * @field {Object] [headers] response headers hash of normalized name, value pairs * @field [entity] the response body * * @class Response */ /** * HTTP client particularly suited for RESTful operations. * * @field {function} wrap wraps this client with a new interceptor returning the wrapped client * * @param {Request} the HTTP request * @returns {ResponsePromise<Response>} a promise the resolves to the HTTP response * * @class Client */ /** * Extended when.js Promises/A+ promise with HTTP specific helpers *q * @method entity promise for the HTTP entity * @method status promise for the HTTP status code * @method headers promise for the HTTP response headers * @method header promise for a specific HTTP response header * * @class ResponsePromise * @extends Promise */ var client, target, platformDefault; client = _dereq_('../client'); /** * Make a request with the default client * @param {Request} the HTTP request * @returns {Promise<Response>} a promise the resolves to the HTTP response */ function defaultClient() { return target.apply(undef, arguments); } /** * Change the default client * @param {Client} client the new default client */ defaultClient.setDefaultClient = function setDefaultClient(client) { target = client; }; /** * Obtain a direct reference to the current default client * @returns {Client} the default client */ defaultClient.getDefaultClient = function getDefaultClient() { return target; }; /** * Reset the default client to the platform default */ defaultClient.resetDefaultClient = function resetDefaultClient() { target = platformDefault; }; /** * @private */ defaultClient.setPlatformDefaultClient = function setPlatformDefaultClient(client) { if (platformDefault) { throw new Error('Unable to redefine platformDefaultClient'); } target = platformDefault = client; }; return client(defaultClient); }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"../client":96}],98:[function(_dereq_,module,exports){ /* * Copyright 2012-2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define, global) { 'use strict'; define(function (_dereq_) { var when, UrlBuilder, normalizeHeaderName, responsePromise, client, headerSplitRE; when = _dereq_('when'); UrlBuilder = _dereq_('../UrlBuilder'); normalizeHeaderName = _dereq_('../util/normalizeHeaderName'); responsePromise = _dereq_('../util/responsePromise'); client = _dereq_('../client'); // according to the spec, the line break is '\r\n', but doesn't hold true in practice headerSplitRE = /[\r|\n]+/; function parseHeaders(raw) { // Note: Set-Cookie will be removed by the browser var headers = {}; if (!raw) { return headers; } raw.trim().split(headerSplitRE).forEach(function (header) { var boundary, name, value; boundary = header.indexOf(':'); name = normalizeHeaderName(header.substring(0, boundary).trim()); value = header.substring(boundary + 1).trim(); if (headers[name]) { if (Array.isArray(headers[name])) { // add to an existing array headers[name].push(value); } else { // convert single value to array headers[name] = [headers[name], value]; } } else { // new, single value headers[name] = value; } }); return headers; } function safeMixin(target, source) { Object.keys(source || {}).forEach(function (prop) { // make sure the property already exists as // IE 6 will blow up if we add a new prop if (source.hasOwnProperty(prop) && prop in target) { try { target[prop] = source[prop]; } catch (e) { // ignore, expected for some properties at some points in the request lifecycle } } }); return target; } return client(function xhr(request) { return responsePromise.promise(function (resolve, reject) { /*jshint maxcomplexity:20 */ var client, method, url, headers, entity, headerName, response, XMLHttpRequest; request = typeof request === 'string' ? { path: request } : request || {}; response = { request: request }; if (request.canceled) { response.error = 'precanceled'; reject(response); return; } XMLHttpRequest = request.engine || global.XMLHttpRequest; if (!XMLHttpRequest) { reject({ request: request, error: 'xhr-not-available' }); return; } entity = request.entity; request.method = request.method || (entity ? 'POST' : 'GET'); method = request.method; url = new UrlBuilder(request.path || '', request.params).build(); try { client = response.raw = new XMLHttpRequest(); // mixin extra request properties before and after opening the request as some properties require being set at different phases of the request safeMixin(client, request.mixin); client.open(method, url, true); safeMixin(client, request.mixin); headers = request.headers; for (headerName in headers) { /*jshint forin:false */ if (headerName === 'Content-Type' && headers[headerName] === 'multipart/form-data') { // XMLHttpRequest generates its own Content-Type header with the // appropriate multipart boundary when sending multipart/form-data. continue; } client.setRequestHeader(headerName, headers[headerName]); } request.canceled = false; request.cancel = function cancel() { request.canceled = true; client.abort(); reject(response); }; client.onreadystatechange = function (/* e */) { if (request.canceled) { return; } if (client.readyState === (XMLHttpRequest.DONE || 4)) { response.status = { code: client.status, text: client.statusText }; response.headers = parseHeaders(client.getAllResponseHeaders()); response.entity = client.responseText; if (response.status.code > 0) { // check status code as readystatechange fires before error event resolve(response); } else { // give the error callback a chance to fire before resolving // requests for file:// URLs do not have a status code setTimeout(function () { resolve(response); }, 0); } } }; try { client.onerror = function (/* e */) { response.error = 'loaderror'; reject(response); }; } catch (e) { // IE 6 will not support error handling } client.send(entity); } catch (e) { response.error = 'loaderror'; reject(response); } }); }); }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); }, typeof window !== 'undefined' ? window : void 0 // Boilerplate for AMD and Node )); },{"../UrlBuilder":94,"../client":96,"../util/normalizeHeaderName":131,"../util/responsePromise":132,"when":127}],99:[function(_dereq_,module,exports){ /* * Copyright 2012-2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var defaultClient, mixin, responsePromise, client, when; defaultClient = _dereq_('./client/default'); mixin = _dereq_('./util/mixin'); responsePromise = _dereq_('./util/responsePromise'); client = _dereq_('./client'); when = _dereq_('when'); /** * Interceptors have the ability to intercept the request and/org response * objects. They may augment, prune, transform or replace the * request/response as needed. Clients may be composed by wrapping * together multiple interceptors. * * Configured interceptors are functional in nature. Wrapping a client in * an interceptor will not affect the client, merely the data that flows in * and out of that client. A common configuration can be created once and * shared; specialization can be created by further wrapping that client * with custom interceptors. * * @param {Client} [target] client to wrap * @param {Object} [config] configuration for the interceptor, properties will be specific to the interceptor implementation * @returns {Client} A client wrapped with the interceptor * * @class Interceptor */ function defaultInitHandler(config) { return config; } function defaultRequestHandler(request /*, config, meta */) { return request; } function defaultResponseHandler(response /*, config, meta */) { return response; } function race(promisesOrValues) { // this function is different than when.any as the first to reject also wins return when.promise(function (resolve, reject) { promisesOrValues.forEach(function (promiseOrValue) { when(promiseOrValue, resolve, reject); }); }); } /** * Alternate return type for the request handler that allows for more complex interactions. * * @param properties.request the traditional request return object * @param {Promise} [properties.abort] promise that resolves if/when the request is aborted * @param {Client} [properties.client] override the defined client with an alternate client * @param [properties.response] response for the request, short circuit the request */ function ComplexRequest(properties) { if (!(this instanceof ComplexRequest)) { // in case users forget the 'new' don't mix into the interceptor return new ComplexRequest(properties); } mixin(this, properties); } /** * Create a new interceptor for the provided handlers. * * @param {Function} [handlers.init] one time intialization, must return the config object * @param {Function} [handlers.request] request handler * @param {Function} [handlers.response] response handler regardless of error state * @param {Function} [handlers.success] response handler when the request is not in error * @param {Function} [handlers.error] response handler when the request is in error, may be used to 'unreject' an error state * @param {Function} [handlers.client] the client to use if otherwise not specified, defaults to platform default client * * @returns {Interceptor} */ function interceptor(handlers) { var initHandler, requestHandler, successResponseHandler, errorResponseHandler; handlers = handlers || {}; initHandler = handlers.init || defaultInitHandler; requestHandler = handlers.request || defaultRequestHandler; successResponseHandler = handlers.success || handlers.response || defaultResponseHandler; errorResponseHandler = handlers.error || function () { // Propagate the rejection, with the result of the handler return when((handlers.response || defaultResponseHandler).apply(this, arguments), when.reject, when.reject); }; return function (target, config) { if (typeof target === 'object') { config = target; } if (typeof target !== 'function') { target = handlers.client || defaultClient; } config = initHandler(config || {}); function interceptedClient(request) { var context, meta; context = {}; meta = { 'arguments': Array.prototype.slice.call(arguments), client: interceptedClient }; request = typeof request === 'string' ? { path: request } : request || {}; request.originator = request.originator || interceptedClient; return responsePromise( requestHandler.call(context, request, config, meta), function (request) { var response, abort, next; next = target; if (request instanceof ComplexRequest) { // unpack request abort = request.abort; next = request.client || next; response = request.response; // normalize request, must be last request = request.request; } response = response || when(request, function (request) { return when( next(request), function (response) { return successResponseHandler.call(context, response, config, meta); }, function (response) { return errorResponseHandler.call(context, response, config, meta); } ); }); return abort ? race([response, abort]) : response; }, function (error) { return when.reject({ request: request, error: error }); } ); } return client(interceptedClient, target); }; } interceptor.ComplexRequest = ComplexRequest; return interceptor; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"./client":96,"./client/default":97,"./util/mixin":130,"./util/responsePromise":132,"when":127}],100:[function(_dereq_,module,exports){ /* * Copyright 2012-2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var interceptor, mime, registry, noopConverter, when; interceptor = _dereq_('../interceptor'); mime = _dereq_('../mime'); registry = _dereq_('../mime/registry'); when = _dereq_('when'); noopConverter = { read: function (obj) { return obj; }, write: function (obj) { return obj; } }; /** * MIME type support for request and response entities. Entities are * (de)serialized using the converter for the MIME type. * * Request entities are converted using the desired converter and the * 'Accept' request header prefers this MIME. * * Response entities are converted based on the Content-Type response header. * * @param {Client} [client] client to wrap * @param {string} [config.mime='text/plain'] MIME type to encode the request * entity * @param {string} [config.accept] Accept header for the request * @param {Client} [config.client=<request.originator>] client passed to the * converter, defaults to the client originating the request * @param {Registry} [config.registry] MIME registry, defaults to the root * registry * @param {boolean} [config.permissive] Allow an unkown request MIME type * * @returns {Client} */ return interceptor({ init: function (config) { config.registry = config.registry || registry; return config; }, request: function (request, config) { var type, headers; headers = request.headers || (request.headers = {}); type = mime.parse(headers['Content-Type'] = headers['Content-Type'] || config.mime || 'text/plain'); headers.Accept = headers.Accept || config.accept || type.raw + ', application/json;q=0.8, text/plain;q=0.5, */*;q=0.2'; if (!('entity' in request)) { return request; } return config.registry.lookup(type).otherwise(function () { // failed to resolve converter if (config.permissive) { return noopConverter; } throw 'mime-unknown'; }).then(function (converter) { var client = config.client || request.originator; return when.attempt(converter.write, request.entity, { client: client, request: request, mime: type, registry: config.registry }) .otherwise(function() { throw 'mime-serialization'; }) .then(function(entity) { request.entity = entity; return request; }); }); }, response: function (response, config) { if (!(response.headers && response.headers['Content-Type'] && response.entity)) { return response; } var type = mime.parse(response.headers['Content-Type']); return config.registry.lookup(type).otherwise(function () { return noopConverter; }).then(function (converter) { var client = config.client || response.request && response.request.originator; return when.attempt(converter.read, response.entity, { client: client, response: response, mime: type, registry: config.registry }) .otherwise(function (e) { response.error = 'mime-deserialization'; response.cause = e; throw response; }) .then(function (entity) { response.entity = entity; return response; }); }); } }); }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"../interceptor":99,"../mime":103,"../mime/registry":104,"when":127}],101:[function(_dereq_,module,exports){ /* * Copyright 2012-2013 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var interceptor, UrlBuilder; interceptor = _dereq_('../interceptor'); UrlBuilder = _dereq_('../UrlBuilder'); function startsWith(str, prefix) { return str.indexOf(prefix) === 0; } function endsWith(str, suffix) { return str.lastIndexOf(suffix) + suffix.length === str.length; } /** * Prefixes the request path with a common value. * * @param {Client} [client] client to wrap * @param {number} [config.prefix] path prefix * * @returns {Client} */ return interceptor({ request: function (request, config) { var path; if (config.prefix && !(new UrlBuilder(request.path).isFullyQualified())) { path = config.prefix; if (request.path) { if (!endsWith(path, '/') && !startsWith(request.path, '/')) { // add missing '/' between path sections path += '/'; } path += request.path; } request.path = path; } return request; } }); }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"../UrlBuilder":94,"../interceptor":99}],102:[function(_dereq_,module,exports){ /* * Copyright 2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var interceptor, uriTemplate, mixin; interceptor = _dereq_('../interceptor'); uriTemplate = _dereq_('../util/uriTemplate'); mixin = _dereq_('../util/mixin'); /** * Applies request params to the path as a URI Template * * Params are removed from the request object, as they have been consumed. * * @param {Client} [client] client to wrap * @param {Object} [config.params] default param values * @param {string} [config.template] default template * * @returns {Client} */ return interceptor({ init: function (config) { config.params = config.params || {}; config.template = config.template || ''; return config; }, request: function (request, config) { var template, params; template = request.path || config.template; params = mixin({}, request.params, config.params); request.path = uriTemplate.expand(template, params); delete request.params; return request; } }); }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"../interceptor":99,"../util/mixin":130,"../util/uriTemplate":134}],103:[function(_dereq_,module,exports){ /* * Copyright 2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; var undef; define(function (/* require */) { /** * Parse a MIME type into it's constituent parts * * @param {string} mime MIME type to parse * @return {{ * {string} raw the original MIME type * {string} type the type and subtype * {string} [suffix] mime suffix, including the plus, if any * {Object} params key/value pair of attributes * }} */ function parse(mime) { var params, type; params = mime.split(';'); type = params[0].trim().split('+'); return { raw: mime, type: type[0], suffix: type[1] ? '+' + type[1] : '', params: params.slice(1).reduce(function (params, pair) { pair = pair.split('='); params[pair[0].trim()] = pair[1] ? pair[1].trim() : undef; return params; }, {}) }; } return { parse: parse }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],104:[function(_dereq_,module,exports){ /* * Copyright 2012-2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var mime, when, registry; mime = _dereq_('../mime'); when = _dereq_('when'); function Registry(mimes) { /** * Lookup the converter for a MIME type * * @param {string} type the MIME type * @return a promise for the converter */ this.lookup = function lookup(type) { var parsed; parsed = typeof type === 'string' ? mime.parse(type) : type; if (mimes[parsed.raw]) { return mimes[parsed.raw]; } if (mimes[parsed.type + parsed.suffix]) { return mimes[parsed.type + parsed.suffix]; } if (mimes[parsed.type]) { return mimes[parsed.type]; } if (mimes[parsed.suffix]) { return mimes[parsed.suffix]; } return when.reject(new Error('Unable to locate converter for mime "' + parsed.raw + '"')); }; /** * Create a late dispatched proxy to the target converter. * * Common when a converter is registered under multiple names and * should be kept in sync if updated. * * @param {string} type mime converter to dispatch to * @returns converter whose read/write methods target the desired mime converter */ this.delegate = function delegate(type) { return { read: function () { var args = arguments; return this.lookup(type).then(function (converter) { return converter.read.apply(this, args); }.bind(this)); }.bind(this), write: function () { var args = arguments; return this.lookup(type).then(function (converter) { return converter.write.apply(this, args); }.bind(this)); }.bind(this) }; }; /** * Register a custom converter for a MIME type * * @param {string} type the MIME type * @param converter the converter for the MIME type * @return a promise for the converter */ this.register = function register(type, converter) { mimes[type] = when(converter); return mimes[type]; }; /** * Create a child registry whoes registered converters remain local, while * able to lookup converters from its parent. * * @returns child MIME registry */ this.child = function child() { return new Registry(Object.create(mimes)); }; } registry = new Registry({}); // include provided serializers registry.register('application/hal', _dereq_('./type/application/hal')); registry.register('application/json', _dereq_('./type/application/json')); registry.register('application/x-www-form-urlencoded', _dereq_('./type/application/x-www-form-urlencoded')); registry.register('multipart/form-data', _dereq_('./type/multipart/form-data')); registry.register('text/plain', _dereq_('./type/text/plain')); registry.register('+json', registry.delegate('application/json')); return registry; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"../mime":103,"./type/application/hal":105,"./type/application/json":106,"./type/application/x-www-form-urlencoded":107,"./type/multipart/form-data":108,"./type/text/plain":109,"when":127}],105:[function(_dereq_,module,exports){ /* * Copyright 2013-2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var pathPrefix, template, find, lazyPromise, responsePromise, when; pathPrefix = _dereq_('../../../interceptor/pathPrefix'); template = _dereq_('../../../interceptor/template'); find = _dereq_('../../../util/find'); lazyPromise = _dereq_('../../../util/lazyPromise'); responsePromise = _dereq_('../../../util/responsePromise'); when = _dereq_('when'); function defineProperty(obj, name, value) { Object.defineProperty(obj, name, { value: value, configurable: true, enumerable: false, writeable: true }); } /** * Hypertext Application Language serializer * * Implemented to https://tools.ietf.org/html/draft-kelly-json-hal-06 * * As the spec is still a draft, this implementation will be updated as the * spec evolves * * Objects are read as HAL indexing links and embedded objects on to the * resource. Objects are written as plain JSON. * * Embedded relationships are indexed onto the resource by the relationship * as a promise for the related resource. * * Links are indexed onto the resource as a lazy promise that will GET the * resource when a handler is first registered on the promise. * * A `requestFor` method is added to the entity to make a request for the * relationship. * * A `clientFor` method is added to the entity to get a full Client for a * relationship. * * The `_links` and `_embedded` properties on the resource are made * non-enumerable. */ return { read: function (str, opts) { var client, console; opts = opts || {}; client = opts.client; console = opts.console || console; function deprecationWarning(relationship, deprecation) { if (deprecation && console && console.warn || console.log) { (console.warn || console.log).call(console, 'Relationship \'' + relationship + '\' is deprecated, see ' + deprecation); } } return opts.registry.lookup(opts.mime.suffix).then(function (converter) { return when(converter.read(str, opts)).then(function (root) { find.findProperties(root, '_embedded', function (embedded, resource, name) { Object.keys(embedded).forEach(function (relationship) { if (relationship in resource) { return; } var related = responsePromise({ entity: embedded[relationship] }); defineProperty(resource, relationship, related); }); defineProperty(resource, name, embedded); }); find.findProperties(root, '_links', function (links, resource, name) { Object.keys(links).forEach(function (relationship) { var link = links[relationship]; if (relationship in resource) { return; } defineProperty(resource, relationship, responsePromise.make(lazyPromise(function () { if (link.deprecation) { deprecationWarning(relationship, link.deprecation); } if (link.templated === true) { return template(client)({ path: link.href }); } return client({ path: link.href }); }))); }); defineProperty(resource, name, links); defineProperty(resource, 'clientFor', function (relationship, clientOverride) { var link = links[relationship]; if (!link) { throw new Error('Unknown relationship: ' + relationship); } if (link.deprecation) { deprecationWarning(relationship, link.deprecation); } if (link.templated === true) { return template( clientOverride || client, { template: link.href } ); } return pathPrefix( clientOverride || client, { prefix: link.href } ); }); defineProperty(resource, 'requestFor', function (relationship, request, clientOverride) { var client = this.clientFor(relationship, clientOverride); return client(request); }); }); return root; }); }); }, write: function (obj, opts) { return opts.registry.lookup(opts.mime.suffix).then(function (converter) { return converter.write(obj, opts); }); } }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"../../../interceptor/pathPrefix":101,"../../../interceptor/template":102,"../../../util/find":128,"../../../util/lazyPromise":129,"../../../util/responsePromise":132,"when":127}],106:[function(_dereq_,module,exports){ /* * Copyright 2012-2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { /** * Create a new JSON converter with custom reviver/replacer. * * The extended converter must be published to a MIME registry in order * to be used. The existing converter will not be modified. * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON * * @param {function} [reviver=undefined] custom JSON.parse reviver * @param {function|Array} [replacer=undefined] custom JSON.stringify replacer */ function createConverter(reviver, replacer) { return { read: function (str) { return JSON.parse(str, reviver); }, write: function (obj) { return JSON.stringify(obj, replacer); }, extend: createConverter }; } return createConverter(); }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],107:[function(_dereq_,module,exports){ /* * Copyright 2012 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { var encodedSpaceRE, urlEncodedSpaceRE; encodedSpaceRE = /%20/g; urlEncodedSpaceRE = /\+/g; function urlEncode(str) { str = encodeURIComponent(str); // spec says space should be encoded as '+' return str.replace(encodedSpaceRE, '+'); } function urlDecode(str) { // spec says space should be encoded as '+' str = str.replace(urlEncodedSpaceRE, ' '); return decodeURIComponent(str); } function append(str, name, value) { if (Array.isArray(value)) { value.forEach(function (value) { str = append(str, name, value); }); } else { if (str.length > 0) { str += '&'; } str += urlEncode(name); if (value !== undefined && value !== null) { str += '=' + urlEncode(value); } } return str; } return { read: function (str) { var obj = {}; str.split('&').forEach(function (entry) { var pair, name, value; pair = entry.split('='); name = urlDecode(pair[0]); if (pair.length === 2) { value = urlDecode(pair[1]); } else { value = null; } if (name in obj) { if (!Array.isArray(obj[name])) { // convert to an array, perserving currnent value obj[name] = [obj[name]]; } obj[name].push(value); } else { obj[name] = value; } }); return obj; }, write: function (obj) { var str = ''; Object.keys(obj).forEach(function (name) { str = append(str, name, obj[name]); }); return str; } }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],108:[function(_dereq_,module,exports){ /* * Copyright 2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Michael Jackson */ /* global FormData, File, Blob */ (function (define) { 'use strict'; define(function (/* require */) { function isFormElement(object) { return object && object.nodeType === 1 && // Node.ELEMENT_NODE object.tagName === 'FORM'; } function createFormDataFromObject(object) { var formData = new FormData(); var value; for (var property in object) { if (object.hasOwnProperty(property)) { value = object[property]; if (value instanceof File) { formData.append(property, value, value.name); } else if (value instanceof Blob) { formData.append(property, value); } else { formData.append(property, String(value)); } } } return formData; } return { write: function (object) { if (typeof FormData === 'undefined') { throw new Error('The multipart/form-data mime serializer requires FormData support'); } // Support FormData directly. if (object instanceof FormData) { return object; } // Support <form> elements. if (isFormElement(object)) { return new FormData(object); } // Support plain objects, may contain File/Blob as value. if (typeof object === 'object' && object !== null) { return createFormDataFromObject(object); } throw new Error('Unable to create FormData from object ' + object); } }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],109:[function(_dereq_,module,exports){ /* * Copyright 2012 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { return { read: function (str) { return str; }, write: function (obj) { return obj.toString(); } }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],110:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function (_dereq_) { var makePromise = _dereq_('./makePromise'); var Scheduler = _dereq_('./Scheduler'); var async = _dereq_('./env').asap; return makePromise({ scheduler: new Scheduler(async) }); }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); }); },{"./Scheduler":111,"./env":123,"./makePromise":125}],111:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { // Credit to Twisol (https://github.com/Twisol) for suggesting // this type of extensible queue + trampoline approach for next-tick conflation. /** * Async task scheduler * @param {function} async function to schedule a single async function * @constructor */ function Scheduler(async) { this._async = async; this._running = false; this._queue = this; this._queueLen = 0; this._afterQueue = {}; this._afterQueueLen = 0; var self = this; this.drain = function() { self._drain(); }; } /** * Enqueue a task * @param {{ run:function }} task */ Scheduler.prototype.enqueue = function(task) { this._queue[this._queueLen++] = task; this.run(); }; /** * Enqueue a task to run after the main task queue * @param {{ run:function }} task */ Scheduler.prototype.afterQueue = function(task) { this._afterQueue[this._afterQueueLen++] = task; this.run(); }; Scheduler.prototype.run = function() { if (!this._running) { this._running = true; this._async(this.drain); } }; /** * Drain the handler queue entirely, and then the after queue */ Scheduler.prototype._drain = function() { var i = 0; for (; i < this._queueLen; ++i) { this._queue[i].run(); this._queue[i] = void 0; } this._queueLen = 0; this._running = false; for (i = 0; i < this._afterQueueLen; ++i) { this._afterQueue[i].run(); this._afterQueue[i] = void 0; } this._afterQueueLen = 0; }; return Scheduler; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],112:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { /** * Custom error type for promises rejected by promise.timeout * @param {string} message * @constructor */ function TimeoutError (message) { Error.call(this); this.message = message; this.name = TimeoutError.name; if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, TimeoutError); } } TimeoutError.prototype = Object.create(Error.prototype); TimeoutError.prototype.constructor = TimeoutError; return TimeoutError; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],113:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { makeApply.tryCatchResolve = tryCatchResolve; return makeApply; function makeApply(Promise, call) { if(arguments.length < 2) { call = tryCatchResolve; } return apply; function apply(f, thisArg, args) { var p = Promise._defer(); var l = args.length; var params = new Array(l); callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler); return p; } function callAndResolve(c, h) { if(c.i < 0) { return call(c.f, c.thisArg, c.params, h); } var handler = Promise._handler(c.args[c.i]); handler.fold(callAndResolveNext, c, void 0, h); } function callAndResolveNext(c, x, h) { c.params[c.i] = x; c.i -= 1; callAndResolve(c, h); } } function tryCatchResolve(f, thisArg, args, resolver) { try { resolver.resolve(f.apply(thisArg, args)); } catch(e) { resolver.reject(e); } } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],114:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(_dereq_) { var state = _dereq_('../state'); var applier = _dereq_('../apply'); return function array(Promise) { var applyFold = applier(Promise); var toPromise = Promise.resolve; var all = Promise.all; var ar = Array.prototype.reduce; var arr = Array.prototype.reduceRight; var slice = Array.prototype.slice; // Additional array combinators Promise.any = any; Promise.some = some; Promise.settle = settle; Promise.map = map; Promise.filter = filter; Promise.reduce = reduce; Promise.reduceRight = reduceRight; /** * When this promise fulfills with an array, do * onFulfilled.apply(void 0, array) * @param {function} onFulfilled function to apply * @returns {Promise} promise for the result of applying onFulfilled */ Promise.prototype.spread = function(onFulfilled) { return this.then(all).then(function(array) { return onFulfilled.apply(this, array); }); }; return Promise; /** * One-winner competitive race. * Return a promise that will fulfill when one of the promises * in the input array fulfills, or will reject when all promises * have rejected. * @param {array} promises * @returns {Promise} promise for the first fulfilled value */ function any(promises) { var p = Promise._defer(); var resolver = p._handler; var l = promises.length>>>0; var pending = l; var errors = []; for (var h, x, i = 0; i < l; ++i) { x = promises[i]; if(x === void 0 && !(i in promises)) { --pending; continue; } h = Promise._handler(x); if(h.state() > 0) { resolver.become(h); Promise._visitRemaining(promises, i, h); break; } else { h.visit(resolver, handleFulfill, handleReject); } } if(pending === 0) { resolver.reject(new RangeError('any(): array must not be empty')); } return p; function handleFulfill(x) { /*jshint validthis:true*/ errors = null; this.resolve(x); // this === resolver } function handleReject(e) { /*jshint validthis:true*/ if(this.resolved) { // this === resolver return; } errors.push(e); if(--pending === 0) { this.reject(errors); } } } /** * N-winner competitive race * Return a promise that will fulfill when n input promises have * fulfilled, or will reject when it becomes impossible for n * input promises to fulfill (ie when promises.length - n + 1 * have rejected) * @param {array} promises * @param {number} n * @returns {Promise} promise for the earliest n fulfillment values * * @deprecated */ function some(promises, n) { /*jshint maxcomplexity:7*/ var p = Promise._defer(); var resolver = p._handler; var results = []; var errors = []; var l = promises.length>>>0; var nFulfill = 0; var nReject; var x, i; // reused in both for() loops // First pass: count actual array items for(i=0; i<l; ++i) { x = promises[i]; if(x === void 0 && !(i in promises)) { continue; } ++nFulfill; } // Compute actual goals n = Math.max(n, 0); nReject = (nFulfill - n + 1); nFulfill = Math.min(n, nFulfill); if(n > nFulfill) { resolver.reject(new RangeError('some(): array must contain at least ' + n + ' item(s), but had ' + nFulfill)); } else if(nFulfill === 0) { resolver.resolve(results); } // Second pass: observe each array item, make progress toward goals for(i=0; i<l; ++i) { x = promises[i]; if(x === void 0 && !(i in promises)) { continue; } Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify); } return p; function fulfill(x) { /*jshint validthis:true*/ if(this.resolved) { // this === resolver return; } results.push(x); if(--nFulfill === 0) { errors = null; this.resolve(results); } } function reject(e) { /*jshint validthis:true*/ if(this.resolved) { // this === resolver return; } errors.push(e); if(--nReject === 0) { results = null; this.reject(errors); } } } /** * Apply f to the value of each promise in a list of promises * and return a new list containing the results. * @param {array} promises * @param {function(x:*, index:Number):*} f mapping function * @returns {Promise} */ function map(promises, f) { return Promise._traverse(f, promises); } /** * Filter the provided array of promises using the provided predicate. Input may * contain promises and values * @param {Array} promises array of promises and values * @param {function(x:*, index:Number):boolean} predicate filtering predicate. * Must return truthy (or promise for truthy) for items to retain. * @returns {Promise} promise that will fulfill with an array containing all items * for which predicate returned truthy. */ function filter(promises, predicate) { var a = slice.call(promises); return Promise._traverse(predicate, a).then(function(keep) { return filterSync(a, keep); }); } function filterSync(promises, keep) { // Safe because we know all promises have fulfilled if we've made it this far var l = keep.length; var filtered = new Array(l); for(var i=0, j=0; i<l; ++i) { if(keep[i]) { filtered[j++] = Promise._handler(promises[i]).value; } } filtered.length = j; return filtered; } /** * Return a promise that will always fulfill with an array containing * the outcome states of all input promises. The returned promise * will never reject. * @param {Array} promises * @returns {Promise} promise for array of settled state descriptors */ function settle(promises) { return all(promises.map(settleOne)); } function settleOne(p) { var h = Promise._handler(p); if(h.state() === 0) { return toPromise(p).then(state.fulfilled, state.rejected); } h._unreport(); return state.inspect(h); } /** * Traditional reduce function, similar to `Array.prototype.reduce()`, but * input may contain promises and/or values, and reduceFunc * may return either a value or a promise, *and* initialValue may * be a promise for the starting value. * @param {Array|Promise} promises array or promise for an array of anything, * may contain a mix of promises and values. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function * @returns {Promise} that will resolve to the final reduced value */ function reduce(promises, f /*, initialValue */) { return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2]) : ar.call(promises, liftCombine(f)); } /** * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but * input may contain promises and/or values, and reduceFunc * may return either a value or a promise, *and* initialValue may * be a promise for the starting value. * @param {Array|Promise} promises array or promise for an array of anything, * may contain a mix of promises and values. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function * @returns {Promise} that will resolve to the final reduced value */ function reduceRight(promises, f /*, initialValue */) { return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2]) : arr.call(promises, liftCombine(f)); } function liftCombine(f) { return function(z, x, i) { return applyFold(f, void 0, [z,x,i]); }; } }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); },{"../apply":113,"../state":126}],115:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function flow(Promise) { var resolve = Promise.resolve; var reject = Promise.reject; var origCatch = Promise.prototype['catch']; /** * Handle the ultimate fulfillment value or rejection reason, and assume * responsibility for all errors. If an error propagates out of result * or handleFatalError, it will be rethrown to the host, resulting in a * loud stack track on most platforms and a crash on some. * @param {function?} onResult * @param {function?} onError * @returns {undefined} */ Promise.prototype.done = function(onResult, onError) { this._handler.visit(this._handler.receiver, onResult, onError); }; /** * Add Error-type and predicate matching to catch. Examples: * promise['catch'](TypeError, handleTypeError) * ['catch'](predicate, handleMatchedErrors) * ['catch'](handleRemainingErrors) * @param onRejected * @returns {*} */ Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) { if (arguments.length < 2) { return origCatch.call(this, onRejected); } if(typeof onRejected !== 'function') { return this.ensure(rejectInvalidPredicate); } return origCatch.call(this, createCatchFilter(arguments[1], onRejected)); }; /** * Wraps the provided catch handler, so that it will only be called * if the predicate evaluates truthy * @param {?function} handler * @param {function} predicate * @returns {function} conditional catch handler */ function createCatchFilter(handler, predicate) { return function(e) { return evaluatePredicate(e, predicate) ? handler.call(this, e) : reject(e); }; } /** * Ensures that onFulfilledOrRejected will be called regardless of whether * this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT * receive the promises' value or reason. Any returned value will be disregarded. * onFulfilledOrRejected may throw or return a rejected promise to signal * an additional error. * @param {function} handler handler to be called regardless of * fulfillment or rejection * @returns {Promise} */ Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) { if(typeof handler !== 'function') { return this; } return this.then(function(x) { return runSideEffect(handler, this, identity, x); }, function(e) { return runSideEffect(handler, this, reject, e); }); }; function runSideEffect (handler, thisArg, propagate, value) { var result = handler.call(thisArg); return maybeThenable(result) ? propagateValue(result, propagate, value) : propagate(value); } function propagateValue (result, propagate, x) { return resolve(result).then(function () { return propagate(x); }); } /** * Recover from a failure by returning a defaultValue. If defaultValue * is a promise, it's fulfillment value will be used. If defaultValue is * a promise that rejects, the returned promise will reject with the * same reason. * @param {*} defaultValue * @returns {Promise} new promise */ Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) { return this.then(void 0, function() { return defaultValue; }); }; /** * Shortcut for .then(function() { return value; }) * @param {*} value * @return {Promise} a promise that: * - is fulfilled if value is not a promise, or * - if value is a promise, will fulfill with its value, or reject * with its reason. */ Promise.prototype['yield'] = function(value) { return this.then(function() { return value; }); }; /** * Runs a side effect when this promise fulfills, without changing the * fulfillment value. * @param {function} onFulfilledSideEffect * @returns {Promise} */ Promise.prototype.tap = function(onFulfilledSideEffect) { return this.then(onFulfilledSideEffect)['yield'](this); }; return Promise; }; function rejectInvalidPredicate() { throw new TypeError('catch predicate must be a function'); } function evaluatePredicate(e, predicate) { return isError(predicate) ? e instanceof predicate : predicate(e); } function isError(predicate) { return predicate === Error || (predicate != null && predicate.prototype instanceof Error); } function maybeThenable(x) { return (typeof x === 'object' || typeof x === 'function') && x !== null; } function identity(x) { return x; } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],116:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ /** @author Jeff Escalante */ (function(define) { 'use strict'; define(function() { return function fold(Promise) { Promise.prototype.fold = function(f, z) { var promise = this._beget(); this._handler.fold(function(z, x, to) { Promise._handler(z).fold(function(x, z, to) { to.resolve(f.call(this, z, x)); }, x, this, to); }, z, promise._handler.receiver, promise._handler); return promise; }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],117:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(_dereq_) { var inspect = _dereq_('../state').inspect; return function inspection(Promise) { Promise.prototype.inspect = function() { return inspect(Promise._handler(this)); }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); },{"../state":126}],118:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function generate(Promise) { var resolve = Promise.resolve; Promise.iterate = iterate; Promise.unfold = unfold; return Promise; /** * @deprecated Use github.com/cujojs/most streams and most.iterate * Generate a (potentially infinite) stream of promised values: * x, f(x), f(f(x)), etc. until condition(x) returns true * @param {function} f function to generate a new x from the previous x * @param {function} condition function that, given the current x, returns * truthy when the iterate should stop * @param {function} handler function to handle the value produced by f * @param {*|Promise} x starting value, may be a promise * @return {Promise} the result of the last call to f before * condition returns true */ function iterate(f, condition, handler, x) { return unfold(function(x) { return [x, f(x)]; }, condition, handler, x); } /** * @deprecated Use github.com/cujojs/most streams and most.unfold * Generate a (potentially infinite) stream of promised values * by applying handler(generator(seed)) iteratively until * condition(seed) returns true. * @param {function} unspool function that generates a [value, newSeed] * given a seed. * @param {function} condition function that, given the current seed, returns * truthy when the unfold should stop * @param {function} handler function to handle the value produced by unspool * @param x {*|Promise} starting value, may be a promise * @return {Promise} the result of the last value produced by unspool before * condition returns true */ function unfold(unspool, condition, handler, x) { return resolve(x).then(function(seed) { return resolve(condition(seed)).then(function(done) { return done ? seed : resolve(unspool(seed)).spread(next); }); }); function next(item, newSeed) { return resolve(handler(item)).then(function() { return unfold(unspool, condition, handler, newSeed); }); } } }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],119:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function progress(Promise) { /** * @deprecated * Register a progress handler for this promise * @param {function} onProgress * @returns {Promise} */ Promise.prototype.progress = function(onProgress) { return this.then(void 0, void 0, onProgress); }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],120:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(_dereq_) { var env = _dereq_('../env'); var TimeoutError = _dereq_('../TimeoutError'); function setTimeout(f, ms, x, y) { return env.setTimer(function() { f(x, y, ms); }, ms); } return function timed(Promise) { /** * Return a new promise whose fulfillment value is revealed only * after ms milliseconds * @param {number} ms milliseconds * @returns {Promise} */ Promise.prototype.delay = function(ms) { var p = this._beget(); this._handler.fold(handleDelay, ms, void 0, p._handler); return p; }; function handleDelay(ms, x, h) { setTimeout(resolveDelay, ms, x, h); } function resolveDelay(x, h) { h.resolve(x); } /** * Return a new promise that rejects after ms milliseconds unless * this promise fulfills earlier, in which case the returned promise * fulfills with the same value. * @param {number} ms milliseconds * @param {Error|*=} reason optional rejection reason to use, defaults * to a TimeoutError if not provided * @returns {Promise} */ Promise.prototype.timeout = function(ms, reason) { var p = this._beget(); var h = p._handler; var t = setTimeout(onTimeout, ms, reason, p._handler); this._handler.visit(h, function onFulfill(x) { env.clearTimer(t); this.resolve(x); // this = h }, function onReject(x) { env.clearTimer(t); this.reject(x); // this = h }, h.notify); return p; }; function onTimeout(reason, h, ms) { var e = typeof reason === 'undefined' ? new TimeoutError('timed out after ' + ms + 'ms') : reason; h.reject(e); } return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); },{"../TimeoutError":112,"../env":123}],121:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(_dereq_) { var setTimer = _dereq_('../env').setTimer; var format = _dereq_('../format'); return function unhandledRejection(Promise) { var logError = noop; var logInfo = noop; var localConsole; if(typeof console !== 'undefined') { // Alias console to prevent things like uglify's drop_console option from // removing console.log/error. Unhandled rejections fall into the same // category as uncaught exceptions, and build tools shouldn't silence them. localConsole = console; logError = typeof localConsole.error !== 'undefined' ? function (e) { localConsole.error(e); } : function (e) { localConsole.log(e); }; logInfo = typeof localConsole.info !== 'undefined' ? function (e) { localConsole.info(e); } : function (e) { localConsole.log(e); }; } Promise.onPotentiallyUnhandledRejection = function(rejection) { enqueue(report, rejection); }; Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) { enqueue(unreport, rejection); }; Promise.onFatalRejection = function(rejection) { enqueue(throwit, rejection.value); }; var tasks = []; var reported = []; var running = null; function report(r) { if(!r.handled) { reported.push(r); logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value)); } } function unreport(r) { var i = reported.indexOf(r); if(i >= 0) { reported.splice(i, 1); logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value)); } } function enqueue(f, x) { tasks.push(f, x); if(running === null) { running = setTimer(flush, 0); } } function flush() { running = null; while(tasks.length > 0) { tasks.shift()(tasks.shift()); } } return Promise; }; function throwit(e) { throw e; } function noop() {} }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); },{"../env":123,"../format":124}],122:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function addWith(Promise) { /** * Returns a promise whose handlers will be called with `this` set to * the supplied receiver. Subsequent promises derived from the * returned promise will also have their handlers called with receiver * as `this`. Calling `with` with undefined or no arguments will return * a promise whose handlers will again be called in the usual Promises/A+ * way (no `this`) thus safely undoing any previous `with` in the * promise chain. * * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+ * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41) * * @param {object} receiver `this` value for all handlers attached to * the returned promise. * @returns {Promise} */ Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) { var p = this._beget(); var child = p._handler; child.receiver = receiver; this._handler.chain(child, receiver); return p; }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],123:[function(_dereq_,module,exports){ (function (process){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/ (function(define) { 'use strict'; define(function(_dereq_) { /*jshint maxcomplexity:6*/ // Sniff "best" async scheduling option // Prefer process.nextTick or MutationObserver, then check for // setTimeout, and finally vertx, since its the only env that doesn't // have setTimeout var MutationObs; var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout; // Default env var setTimer = function(f, ms) { return setTimeout(f, ms); }; var clearTimer = function(t) { return clearTimeout(t); }; var asap = function (f) { return capturedSetTimeout(f, 0); }; // Detect specific env if (isNode()) { // Node asap = function (f) { return process.nextTick(f); }; } else if (MutationObs = hasMutationObserver()) { // Modern browser asap = initMutationObserver(MutationObs); } else if (!capturedSetTimeout) { // vert.x var vertxRequire = _dereq_; var vertx = vertxRequire('vertx'); setTimer = function (f, ms) { return vertx.setTimer(ms, f); }; clearTimer = vertx.cancelTimer; asap = vertx.runOnLoop || vertx.runOnContext; } return { setTimer: setTimer, clearTimer: clearTimer, asap: asap }; function isNode () { return typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]'; } function hasMutationObserver () { return (typeof MutationObserver === 'function' && MutationObserver) || (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver); } function initMutationObserver(MutationObserver) { var scheduled; var node = document.createTextNode(''); var o = new MutationObserver(run); o.observe(node, { characterData: true }); function run() { var f = scheduled; scheduled = void 0; f(); } var i = 0; return function (f) { scheduled = f; node.data = (i ^= 1); }; } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); }).call(this,_dereq_('_process')) },{"_process":76}],124:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return { formatError: formatError, formatObject: formatObject, tryStringify: tryStringify }; /** * Format an error into a string. If e is an Error and has a stack property, * it's returned. Otherwise, e is formatted using formatObject, with a * warning added about e not being a proper Error. * @param {*} e * @returns {String} formatted string, suitable for output to developers */ function formatError(e) { var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e); return e instanceof Error ? s : s + ' (WARNING: non-Error used)'; } /** * Format an object, detecting "plain" objects and running them through * JSON.stringify if possible. * @param {Object} o * @returns {string} */ function formatObject(o) { var s = String(o); if(s === '[object Object]' && typeof JSON !== 'undefined') { s = tryStringify(o, s); } return s; } /** * Try to return the result of JSON.stringify(x). If that fails, return * defaultValue * @param {*} x * @param {*} defaultValue * @returns {String|*} JSON.stringify(x) or defaultValue */ function tryStringify(x, defaultValue) { try { return JSON.stringify(x); } catch(e) { return defaultValue; } } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],125:[function(_dereq_,module,exports){ (function (process){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function makePromise(environment) { var tasks = environment.scheduler; var emitRejection = initEmitRejection(); var objectCreate = Object.create || function(proto) { function Child() {} Child.prototype = proto; return new Child(); }; /** * Create a promise whose fate is determined by resolver * @constructor * @returns {Promise} promise * @name Promise */ function Promise(resolver, handler) { this._handler = resolver === Handler ? handler : init(resolver); } /** * Run the supplied resolver * @param resolver * @returns {Pending} */ function init(resolver) { var handler = new Pending(); try { resolver(promiseResolve, promiseReject, promiseNotify); } catch (e) { promiseReject(e); } return handler; /** * Transition from pre-resolution state to post-resolution state, notifying * all listeners of the ultimate fulfillment or rejection * @param {*} x resolution value */ function promiseResolve (x) { handler.resolve(x); } /** * Reject this promise with reason, which will be used verbatim * @param {Error|*} reason rejection reason, strongly suggested * to be an Error type */ function promiseReject (reason) { handler.reject(reason); } /** * @deprecated * Issue a progress event, notifying all progress listeners * @param {*} x progress event payload to pass to all listeners */ function promiseNotify (x) { handler.notify(x); } } // Creation Promise.resolve = resolve; Promise.reject = reject; Promise.never = never; Promise._defer = defer; Promise._handler = getHandler; /** * Returns a trusted promise. If x is already a trusted promise, it is * returned, otherwise returns a new trusted Promise which follows x. * @param {*} x * @return {Promise} promise */ function resolve(x) { return isPromise(x) ? x : new Promise(Handler, new Async(getHandler(x))); } /** * Return a reject promise with x as its reason (x is used verbatim) * @param {*} x * @returns {Promise} rejected promise */ function reject(x) { return new Promise(Handler, new Async(new Rejected(x))); } /** * Return a promise that remains pending forever * @returns {Promise} forever-pending promise. */ function never() { return foreverPendingPromise; // Should be frozen } /** * Creates an internal {promise, resolver} pair * @private * @returns {Promise} */ function defer() { return new Promise(Handler, new Pending()); } // Transformation and flow control /** * Transform this promise's fulfillment value, returning a new Promise * for the transformed result. If the promise cannot be fulfilled, onRejected * is called with the reason. onProgress *may* be called with updates toward * this promise's fulfillment. * @param {function=} onFulfilled fulfillment handler * @param {function=} onRejected rejection handler * @param {function=} onProgress @deprecated progress handler * @return {Promise} new promise */ Promise.prototype.then = function(onFulfilled, onRejected, onProgress) { var parent = this._handler; var state = parent.join().state(); if ((typeof onFulfilled !== 'function' && state > 0) || (typeof onRejected !== 'function' && state < 0)) { // Short circuit: value will not change, simply share handler return new this.constructor(Handler, parent); } var p = this._beget(); var child = p._handler; parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress); return p; }; /** * If this promise cannot be fulfilled due to an error, call onRejected to * handle the error. Shortcut for .then(undefined, onRejected) * @param {function?} onRejected * @return {Promise} */ Promise.prototype['catch'] = function(onRejected) { return this.then(void 0, onRejected); }; /** * Creates a new, pending promise of the same type as this promise * @private * @returns {Promise} */ Promise.prototype._beget = function() { return begetFrom(this._handler, this.constructor); }; function begetFrom(parent, Promise) { var child = new Pending(parent.receiver, parent.join().context); return new Promise(Handler, child); } // Array combinators Promise.all = all; Promise.race = race; Promise._traverse = traverse; /** * Return a promise that will fulfill when all promises in the * input array have fulfilled, or will reject when one of the * promises rejects. * @param {array} promises array of promises * @returns {Promise} promise for array of fulfillment values */ function all(promises) { return traverseWith(snd, null, promises); } /** * Array<Promise<X>> -> Promise<Array<f(X)>> * @private * @param {function} f function to apply to each promise's value * @param {Array} promises array of promises * @returns {Promise} promise for transformed values */ function traverse(f, promises) { return traverseWith(tryCatch2, f, promises); } function traverseWith(tryMap, f, promises) { var handler = typeof f === 'function' ? mapAt : settleAt; var resolver = new Pending(); var pending = promises.length >>> 0; var results = new Array(pending); for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) { x = promises[i]; if (x === void 0 && !(i in promises)) { --pending; continue; } traverseAt(promises, handler, i, x, resolver); } if(pending === 0) { resolver.become(new Fulfilled(results)); } return new Promise(Handler, resolver); function mapAt(i, x, resolver) { if(!resolver.resolved) { traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver); } } function settleAt(i, x, resolver) { results[i] = x; if(--pending === 0) { resolver.become(new Fulfilled(results)); } } } function traverseAt(promises, handler, i, x, resolver) { if (maybeThenable(x)) { var h = getHandlerMaybeThenable(x); var s = h.state(); if (s === 0) { h.fold(handler, i, void 0, resolver); } else if (s > 0) { handler(i, h.value, resolver); } else { resolver.become(h); visitRemaining(promises, i+1, h); } } else { handler(i, x, resolver); } } Promise._visitRemaining = visitRemaining; function visitRemaining(promises, start, handler) { for(var i=start; i<promises.length; ++i) { markAsHandled(getHandler(promises[i]), handler); } } function markAsHandled(h, handler) { if(h === handler) { return; } var s = h.state(); if(s === 0) { h.visit(h, void 0, h._unreport); } else if(s < 0) { h._unreport(); } } /** * Fulfill-reject competitive race. Return a promise that will settle * to the same state as the earliest input promise to settle. * * WARNING: The ES6 Promise spec requires that race()ing an empty array * must return a promise that is pending forever. This implementation * returns a singleton forever-pending promise, the same singleton that is * returned by Promise.never(), thus can be checked with === * * @param {array} promises array of promises to race * @returns {Promise} if input is non-empty, a promise that will settle * to the same outcome as the earliest input promise to settle. if empty * is empty, returns a promise that will never settle. */ function race(promises) { if(typeof promises !== 'object' || promises === null) { return reject(new TypeError('non-iterable passed to race()')); } // Sigh, race([]) is untestable unless we return *something* // that is recognizable without calling .then() on it. return promises.length === 0 ? never() : promises.length === 1 ? resolve(promises[0]) : runRace(promises); } function runRace(promises) { var resolver = new Pending(); var i, x, h; for(i=0; i<promises.length; ++i) { x = promises[i]; if (x === void 0 && !(i in promises)) { continue; } h = getHandler(x); if(h.state() !== 0) { resolver.become(h); visitRemaining(promises, i+1, h); break; } else { h.visit(resolver, resolver.resolve, resolver.reject); } } return new Promise(Handler, resolver); } // Promise internals // Below this, everything is @private /** * Get an appropriate handler for x, without checking for cycles * @param {*} x * @returns {object} handler */ function getHandler(x) { if(isPromise(x)) { return x._handler.join(); } return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x); } /** * Get a handler for thenable x. * NOTE: You must only call this if maybeThenable(x) == true * @param {object|function|Promise} x * @returns {object} handler */ function getHandlerMaybeThenable(x) { return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x); } /** * Get a handler for potentially untrusted thenable x * @param {*} x * @returns {object} handler */ function getHandlerUntrusted(x) { try { var untrustedThen = x.then; return typeof untrustedThen === 'function' ? new Thenable(untrustedThen, x) : new Fulfilled(x); } catch(e) { return new Rejected(e); } } /** * Handler for a promise that is pending forever * @constructor */ function Handler() {} Handler.prototype.when = Handler.prototype.become = Handler.prototype.notify // deprecated = Handler.prototype.fail = Handler.prototype._unreport = Handler.prototype._report = noop; Handler.prototype._state = 0; Handler.prototype.state = function() { return this._state; }; /** * Recursively collapse handler chain to find the handler * nearest to the fully resolved value. * @returns {object} handler nearest the fully resolved value */ Handler.prototype.join = function() { var h = this; while(h.handler !== void 0) { h = h.handler; } return h; }; Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) { this.when({ resolver: to, receiver: receiver, fulfilled: fulfilled, rejected: rejected, progress: progress }); }; Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) { this.chain(failIfRejected, receiver, fulfilled, rejected, progress); }; Handler.prototype.fold = function(f, z, c, to) { this.when(new Fold(f, z, c, to)); }; /** * Handler that invokes fail() on any handler it becomes * @constructor */ function FailIfRejected() {} inherit(Handler, FailIfRejected); FailIfRejected.prototype.become = function(h) { h.fail(); }; var failIfRejected = new FailIfRejected(); /** * Handler that manages a queue of consumers waiting on a pending promise * @constructor */ function Pending(receiver, inheritedContext) { Promise.createContext(this, inheritedContext); this.consumers = void 0; this.receiver = receiver; this.handler = void 0; this.resolved = false; } inherit(Handler, Pending); Pending.prototype._state = 0; Pending.prototype.resolve = function(x) { this.become(getHandler(x)); }; Pending.prototype.reject = function(x) { if(this.resolved) { return; } this.become(new Rejected(x)); }; Pending.prototype.join = function() { if (!this.resolved) { return this; } var h = this; while (h.handler !== void 0) { h = h.handler; if (h === this) { return this.handler = cycle(); } } return h; }; Pending.prototype.run = function() { var q = this.consumers; var handler = this.handler; this.handler = this.handler.join(); this.consumers = void 0; for (var i = 0; i < q.length; ++i) { handler.when(q[i]); } }; Pending.prototype.become = function(handler) { if(this.resolved) { return; } this.resolved = true; this.handler = handler; if(this.consumers !== void 0) { tasks.enqueue(this); } if(this.context !== void 0) { handler._report(this.context); } }; Pending.prototype.when = function(continuation) { if(this.resolved) { tasks.enqueue(new ContinuationTask(continuation, this.handler)); } else { if(this.consumers === void 0) { this.consumers = [continuation]; } else { this.consumers.push(continuation); } } }; /** * @deprecated */ Pending.prototype.notify = function(x) { if(!this.resolved) { tasks.enqueue(new ProgressTask(x, this)); } }; Pending.prototype.fail = function(context) { var c = typeof context === 'undefined' ? this.context : context; this.resolved && this.handler.join().fail(c); }; Pending.prototype._report = function(context) { this.resolved && this.handler.join()._report(context); }; Pending.prototype._unreport = function() { this.resolved && this.handler.join()._unreport(); }; /** * Wrap another handler and force it into a future stack * @param {object} handler * @constructor */ function Async(handler) { this.handler = handler; } inherit(Handler, Async); Async.prototype.when = function(continuation) { tasks.enqueue(new ContinuationTask(continuation, this)); }; Async.prototype._report = function(context) { this.join()._report(context); }; Async.prototype._unreport = function() { this.join()._unreport(); }; /** * Handler that wraps an untrusted thenable and assimilates it in a future stack * @param {function} then * @param {{then: function}} thenable * @constructor */ function Thenable(then, thenable) { Pending.call(this); tasks.enqueue(new AssimilateTask(then, thenable, this)); } inherit(Pending, Thenable); /** * Handler for a fulfilled promise * @param {*} x fulfillment value * @constructor */ function Fulfilled(x) { Promise.createContext(this); this.value = x; } inherit(Handler, Fulfilled); Fulfilled.prototype._state = 1; Fulfilled.prototype.fold = function(f, z, c, to) { runContinuation3(f, z, this, c, to); }; Fulfilled.prototype.when = function(cont) { runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver); }; var errorId = 0; /** * Handler for a rejected promise * @param {*} x rejection reason * @constructor */ function Rejected(x) { Promise.createContext(this); this.id = ++errorId; this.value = x; this.handled = false; this.reported = false; this._report(); } inherit(Handler, Rejected); Rejected.prototype._state = -1; Rejected.prototype.fold = function(f, z, c, to) { to.become(this); }; Rejected.prototype.when = function(cont) { if(typeof cont.rejected === 'function') { this._unreport(); } runContinuation1(cont.rejected, this, cont.receiver, cont.resolver); }; Rejected.prototype._report = function(context) { tasks.afterQueue(new ReportTask(this, context)); }; Rejected.prototype._unreport = function() { if(this.handled) { return; } this.handled = true; tasks.afterQueue(new UnreportTask(this)); }; Rejected.prototype.fail = function(context) { this.reported = true; emitRejection('unhandledRejection', this); Promise.onFatalRejection(this, context === void 0 ? this.context : context); }; function ReportTask(rejection, context) { this.rejection = rejection; this.context = context; } ReportTask.prototype.run = function() { if(!this.rejection.handled && !this.rejection.reported) { this.rejection.reported = true; emitRejection('unhandledRejection', this.rejection) || Promise.onPotentiallyUnhandledRejection(this.rejection, this.context); } }; function UnreportTask(rejection) { this.rejection = rejection; } UnreportTask.prototype.run = function() { if(this.rejection.reported) { emitRejection('rejectionHandled', this.rejection) || Promise.onPotentiallyUnhandledRejectionHandled(this.rejection); } }; // Unhandled rejection hooks // By default, everything is a noop Promise.createContext = Promise.enterContext = Promise.exitContext = Promise.onPotentiallyUnhandledRejection = Promise.onPotentiallyUnhandledRejectionHandled = Promise.onFatalRejection = noop; // Errors and singletons var foreverPendingHandler = new Handler(); var foreverPendingPromise = new Promise(Handler, foreverPendingHandler); function cycle() { return new Rejected(new TypeError('Promise cycle')); } // Task runners /** * Run a single consumer * @constructor */ function ContinuationTask(continuation, handler) { this.continuation = continuation; this.handler = handler; } ContinuationTask.prototype.run = function() { this.handler.join().when(this.continuation); }; /** * Run a queue of progress handlers * @constructor */ function ProgressTask(value, handler) { this.handler = handler; this.value = value; } ProgressTask.prototype.run = function() { var q = this.handler.consumers; if(q === void 0) { return; } for (var c, i = 0; i < q.length; ++i) { c = q[i]; runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver); } }; /** * Assimilate a thenable, sending it's value to resolver * @param {function} then * @param {object|function} thenable * @param {object} resolver * @constructor */ function AssimilateTask(then, thenable, resolver) { this._then = then; this.thenable = thenable; this.resolver = resolver; } AssimilateTask.prototype.run = function() { var h = this.resolver; tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify); function _resolve(x) { h.resolve(x); } function _reject(x) { h.reject(x); } function _notify(x) { h.notify(x); } }; function tryAssimilate(then, thenable, resolve, reject, notify) { try { then.call(thenable, resolve, reject, notify); } catch (e) { reject(e); } } /** * Fold a handler value with z * @constructor */ function Fold(f, z, c, to) { this.f = f; this.z = z; this.c = c; this.to = to; this.resolver = failIfRejected; this.receiver = this; } Fold.prototype.fulfilled = function(x) { this.f.call(this.c, this.z, x, this.to); }; Fold.prototype.rejected = function(x) { this.to.reject(x); }; Fold.prototype.progress = function(x) { this.to.notify(x); }; // Other helpers /** * @param {*} x * @returns {boolean} true iff x is a trusted Promise */ function isPromise(x) { return x instanceof Promise; } /** * Test just enough to rule out primitives, in order to take faster * paths in some code * @param {*} x * @returns {boolean} false iff x is guaranteed *not* to be a thenable */ function maybeThenable(x) { return (typeof x === 'object' || typeof x === 'function') && x !== null; } function runContinuation1(f, h, receiver, next) { if(typeof f !== 'function') { return next.become(h); } Promise.enterContext(h); tryCatchReject(f, h.value, receiver, next); Promise.exitContext(); } function runContinuation3(f, x, h, receiver, next) { if(typeof f !== 'function') { return next.become(h); } Promise.enterContext(h); tryCatchReject3(f, x, h.value, receiver, next); Promise.exitContext(); } /** * @deprecated */ function runNotify(f, x, h, receiver, next) { if(typeof f !== 'function') { return next.notify(x); } Promise.enterContext(h); tryCatchReturn(f, x, receiver, next); Promise.exitContext(); } function tryCatch2(f, a, b) { try { return f(a, b); } catch(e) { return reject(e); } } /** * Return f.call(thisArg, x), or if it throws return a rejected promise for * the thrown exception */ function tryCatchReject(f, x, thisArg, next) { try { next.become(getHandler(f.call(thisArg, x))); } catch(e) { next.become(new Rejected(e)); } } /** * Same as above, but includes the extra argument parameter. */ function tryCatchReject3(f, x, y, thisArg, next) { try { f.call(thisArg, x, y, next); } catch(e) { next.become(new Rejected(e)); } } /** * @deprecated * Return f.call(thisArg, x), or if it throws, *return* the exception */ function tryCatchReturn(f, x, thisArg, next) { try { next.notify(f.call(thisArg, x)); } catch(e) { next.notify(e); } } function inherit(Parent, Child) { Child.prototype = objectCreate(Parent.prototype); Child.prototype.constructor = Child; } function snd(x, y) { return y; } function noop() {} function initEmitRejection() { /*global process, self, CustomEvent*/ if(typeof process !== 'undefined' && process !== null && typeof process.emit === 'function') { // Returning falsy here means to call the default // onPotentiallyUnhandledRejection API. This is safe even in // browserify since process.emit always returns falsy in browserify: // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46 return function(type, rejection) { return type === 'unhandledRejection' ? process.emit(type, rejection.value, rejection) : process.emit(type, rejection); }; } else if(typeof self !== 'undefined' && typeof CustomEvent === 'function') { return (function(noop, self, CustomEvent) { var hasCustomEvent = false; try { var ev = new CustomEvent('unhandledRejection'); hasCustomEvent = ev instanceof CustomEvent; } catch (e) {} return !hasCustomEvent ? noop : function(type, rejection) { var ev = new CustomEvent(type, { detail: { reason: rejection.value, key: rejection }, bubbles: false, cancelable: true }); return !self.dispatchEvent(ev); }; }(noop, self, CustomEvent)); } return noop; } return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); }).call(this,_dereq_('_process')) },{"_process":76}],126:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return { pending: toPendingState, fulfilled: toFulfilledState, rejected: toRejectedState, inspect: inspect }; function toPendingState() { return { state: 'pending' }; } function toRejectedState(e) { return { state: 'rejected', reason: e }; } function toFulfilledState(x) { return { state: 'fulfilled', value: x }; } function inspect(handler) { var state = handler.state(); return state === 0 ? toPendingState() : state > 0 ? toFulfilledState(handler.value) : toRejectedState(handler.value); } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],127:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** * Promises/A+ and when() implementation * when is part of the cujoJS family of libraries (http://cujojs.com/) * @author Brian Cavalier * @author John Hann */ (function(define) { 'use strict'; define(function (_dereq_) { var timed = _dereq_('./lib/decorators/timed'); var array = _dereq_('./lib/decorators/array'); var flow = _dereq_('./lib/decorators/flow'); var fold = _dereq_('./lib/decorators/fold'); var inspect = _dereq_('./lib/decorators/inspect'); var generate = _dereq_('./lib/decorators/iterate'); var progress = _dereq_('./lib/decorators/progress'); var withThis = _dereq_('./lib/decorators/with'); var unhandledRejection = _dereq_('./lib/decorators/unhandledRejection'); var TimeoutError = _dereq_('./lib/TimeoutError'); var Promise = [array, flow, fold, generate, progress, inspect, withThis, timed, unhandledRejection] .reduce(function(Promise, feature) { return feature(Promise); }, _dereq_('./lib/Promise')); var apply = _dereq_('./lib/apply')(Promise); // Public API when.promise = promise; // Create a pending promise when.resolve = Promise.resolve; // Create a resolved promise when.reject = Promise.reject; // Create a rejected promise when.lift = lift; // lift a function to return promises when['try'] = attempt; // call a function and return a promise when.attempt = attempt; // alias for when.try when.iterate = Promise.iterate; // DEPRECATED (use cujojs/most streams) Generate a stream of promises when.unfold = Promise.unfold; // DEPRECATED (use cujojs/most streams) Generate a stream of promises when.join = join; // Join 2 or more promises when.all = all; // Resolve a list of promises when.settle = settle; // Settle a list of promises when.any = lift(Promise.any); // One-winner race when.some = lift(Promise.some); // Multi-winner race when.race = lift(Promise.race); // First-to-settle race when.map = map; // Array.map() for promises when.filter = filter; // Array.filter() for promises when.reduce = lift(Promise.reduce); // Array.reduce() for promises when.reduceRight = lift(Promise.reduceRight); // Array.reduceRight() for promises when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable when.Promise = Promise; // Promise constructor when.defer = defer; // Create a {promise, resolve, reject} tuple // Error types when.TimeoutError = TimeoutError; /** * Get a trusted promise for x, or by transforming x with onFulfilled * * @param {*} x * @param {function?} onFulfilled callback to be called when x is * successfully fulfilled. If promiseOrValue is an immediate value, callback * will be invoked immediately. * @param {function?} onRejected callback to be called when x is * rejected. * @param {function?} onProgress callback to be called when progress updates * are issued for x. @deprecated * @returns {Promise} a new promise that will fulfill with the return * value of callback or errback or the completion value of promiseOrValue if * callback and/or errback is not supplied. */ function when(x, onFulfilled, onRejected, onProgress) { var p = Promise.resolve(x); if (arguments.length < 2) { return p; } return p.then(onFulfilled, onRejected, onProgress); } /** * Creates a new promise whose fate is determined by resolver. * @param {function} resolver function(resolve, reject, notify) * @returns {Promise} promise whose fate is determine by resolver */ function promise(resolver) { return new Promise(resolver); } /** * Lift the supplied function, creating a version of f that returns * promises, and accepts promises as arguments. * @param {function} f * @returns {Function} version of f that returns promises */ function lift(f) { return function() { for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) { a[i] = arguments[i]; } return apply(f, this, a); }; } /** * Call f in a future turn, with the supplied args, and return a promise * for the result. * @param {function} f * @returns {Promise} */ function attempt(f /*, args... */) { /*jshint validthis:true */ for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) { a[i] = arguments[i+1]; } return apply(f, this, a); } /** * Creates a {promise, resolver} pair, either or both of which * may be given out safely to consumers. * @return {{promise: Promise, resolve: function, reject: function, notify: function}} */ function defer() { return new Deferred(); } function Deferred() { var p = Promise._defer(); function resolve(x) { p._handler.resolve(x); } function reject(x) { p._handler.reject(x); } function notify(x) { p._handler.notify(x); } this.promise = p; this.resolve = resolve; this.reject = reject; this.notify = notify; this.resolver = { resolve: resolve, reject: reject, notify: notify }; } /** * Determines if x is promise-like, i.e. a thenable object * NOTE: Will return true for *any thenable object*, and isn't truly * safe, since it may attempt to access the `then` property of x (i.e. * clever/malicious getters may do weird things) * @param {*} x anything * @returns {boolean} true if x is promise-like */ function isPromiseLike(x) { return x && typeof x.then === 'function'; } /** * Return a promise that will resolve only once all the supplied arguments * have resolved. The resolution value of the returned promise will be an array * containing the resolution values of each of the arguments. * @param {...*} arguments may be a mix of promises and values * @returns {Promise} */ function join(/* ...promises */) { return Promise.all(arguments); } /** * Return a promise that will fulfill once all input promises have * fulfilled, or reject when any one input promise rejects. * @param {array|Promise} promises array (or promise for an array) of promises * @returns {Promise} */ function all(promises) { return when(promises, Promise.all); } /** * Return a promise that will always fulfill with an array containing * the outcome states of all input promises. The returned promise * will only reject if `promises` itself is a rejected promise. * @param {array|Promise} promises array (or promise for an array) of promises * @returns {Promise} promise for array of settled state descriptors */ function settle(promises) { return when(promises, Promise.settle); } /** * Promise-aware array map function, similar to `Array.prototype.map()`, * but input array may contain promises or values. * @param {Array|Promise} promises array of anything, may contain promises and values * @param {function(x:*, index:Number):*} mapFunc map function which may * return a promise or value * @returns {Promise} promise that will fulfill with an array of mapped values * or reject if any input promise rejects. */ function map(promises, mapFunc) { return when(promises, function(promises) { return Promise.map(promises, mapFunc); }); } /** * Filter the provided array of promises using the provided predicate. Input may * contain promises and values * @param {Array|Promise} promises array of promises and values * @param {function(x:*, index:Number):boolean} predicate filtering predicate. * Must return truthy (or promise for truthy) for items to retain. * @returns {Promise} promise that will fulfill with an array containing all items * for which predicate returned truthy. */ function filter(promises, predicate) { return when(promises, function(promises) { return Promise.filter(promises, predicate); }); } return when; }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); }); },{"./lib/Promise":110,"./lib/TimeoutError":112,"./lib/apply":113,"./lib/decorators/array":114,"./lib/decorators/flow":115,"./lib/decorators/fold":116,"./lib/decorators/inspect":117,"./lib/decorators/iterate":118,"./lib/decorators/progress":119,"./lib/decorators/timed":120,"./lib/decorators/unhandledRejection":121,"./lib/decorators/with":122}],128:[function(_dereq_,module,exports){ /* * Copyright 2013 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { return { /** * Find objects within a graph the contain a property of a certain name. * * NOTE: this method will not discover object graph cycles. * * @param {*} obj object to search on * @param {string} prop name of the property to search for * @param {Function} callback function to receive the found properties and their parent */ findProperties: function findProperties(obj, prop, callback) { if (typeof obj !== 'object' || obj === null) { return; } if (prop in obj) { callback(obj[prop], obj, prop); } Object.keys(obj).forEach(function (key) { findProperties(obj[key], prop, callback); }); } }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],129:[function(_dereq_,module,exports){ /* * Copyright 2013 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var when; when = _dereq_('when'); /** * Create a promise whose work is started only when a handler is registered. * * The work function will be invoked at most once. Thrown values will result * in promise rejection. * * @param {Function} work function whose ouput is used to resolve the * returned promise. * @returns {Promise} a lazy promise */ function lazyPromise(work) { var defer, started, resolver, promise, then; defer = when.defer(); started = false; resolver = defer.resolver; promise = defer.promise; then = promise.then; promise.then = function () { if (!started) { started = true; when.attempt(work).then(resolver.resolve, resolver.reject); } return then.apply(promise, arguments); }; return promise; } return lazyPromise; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"when":127}],130:[function(_dereq_,module,exports){ /* * Copyright 2012-2013 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; // derived from dojo.mixin define(function (/* require */) { var empty = {}; /** * Mix the properties from the source object into the destination object. * When the same property occurs in more then one object, the right most * value wins. * * @param {Object} dest the object to copy properties to * @param {Object} sources the objects to copy properties from. May be 1 to N arguments, but not an Array. * @return {Object} the destination object */ function mixin(dest /*, sources... */) { var i, l, source, name; if (!dest) { dest = {}; } for (i = 1, l = arguments.length; i < l; i += 1) { source = arguments[i]; for (name in source) { if (!(name in dest) || (dest[name] !== source[name] && (!(name in empty) || empty[name] !== source[name]))) { dest[name] = source[name]; } } } return dest; // Object } return mixin; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],131:[function(_dereq_,module,exports){ /* * Copyright 2012 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { /** * Normalize HTTP header names using the pseudo camel case. * * For example: * content-type -> Content-Type * accepts -> Accepts * x-custom-header-name -> X-Custom-Header-Name * * @param {string} name the raw header name * @return {string} the normalized header name */ function normalizeHeaderName(name) { return name.toLowerCase() .split('-') .map(function (chunk) { return chunk.charAt(0).toUpperCase() + chunk.slice(1); }) .join('-'); } return normalizeHeaderName; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],132:[function(_dereq_,module,exports){ /* * Copyright 2014-2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var when = _dereq_('when'), normalizeHeaderName = _dereq_('./normalizeHeaderName'); function property(promise, name) { return promise.then( function (value) { return value && value[name]; }, function (value) { return when.reject(value && value[name]); } ); } /** * Obtain the response entity * * @returns {Promise} for the response entity */ function entity() { /*jshint validthis:true */ return property(this, 'entity'); } /** * Obtain the response status * * @returns {Promise} for the response status */ function status() { /*jshint validthis:true */ return property(property(this, 'status'), 'code'); } /** * Obtain the response headers map * * @returns {Promise} for the response headers map */ function headers() { /*jshint validthis:true */ return property(this, 'headers'); } /** * Obtain a specific response header * * @param {String} headerName the header to retrieve * @returns {Promise} for the response header's value */ function header(headerName) { /*jshint validthis:true */ headerName = normalizeHeaderName(headerName); return property(this.headers(), headerName); } /** * Follow a related resource * * The relationship to follow may be define as a plain string, an object * with the rel and params, or an array containing one or more entries * with the previous forms. * * Examples: * response.follow('next') * * response.follow({ rel: 'next', params: { pageSize: 100 } }) * * response.follow([ * { rel: 'items', params: { projection: 'noImages' } }, * 'search', * { rel: 'findByGalleryIsNull', params: { projection: 'noImages' } }, * 'items' * ]) * * @param {String|Object|Array} rels one, or more, relationships to follow * @returns ResponsePromise<Response> related resource */ function follow(rels) { /*jshint validthis:true */ rels = [].concat(rels); return make(when.reduce(rels, function (response, rel) { if (typeof rel === 'string') { rel = { rel: rel }; } if (typeof response.entity.clientFor !== 'function') { throw new Error('Hypermedia response expected'); } var client = response.entity.clientFor(rel.rel); return client({ params: rel.params }); }, this)); } /** * Wrap a Promise as an ResponsePromise * * @param {Promise<Response>} promise the promise for an HTTP Response * @returns {ResponsePromise<Response>} wrapped promise for Response with additional helper methods */ function make(promise) { promise.status = status; promise.headers = headers; promise.header = header; promise.entity = entity; promise.follow = follow; return promise; } function responsePromise() { return make(when.apply(when, arguments)); } responsePromise.make = make; responsePromise.reject = function (val) { return make(when.reject(val)); }; responsePromise.promise = function (func) { return make(when.promise(func)); }; return responsePromise; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"./normalizeHeaderName":131,"when":127}],133:[function(_dereq_,module,exports){ /* * Copyright 2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { var charMap; charMap = (function () { var strings = { alpha: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', digit: '0123456789' }; strings.genDelims = ':/?#[]@'; strings.subDelims = '!$&\'()*+,;='; strings.reserved = strings.genDelims + strings.subDelims; strings.unreserved = strings.alpha + strings.digit + '-._~'; strings.url = strings.reserved + strings.unreserved; strings.scheme = strings.alpha + strings.digit + '+-.'; strings.userinfo = strings.unreserved + strings.subDelims + ':'; strings.host = strings.unreserved + strings.subDelims; strings.port = strings.digit; strings.pchar = strings.unreserved + strings.subDelims + ':@'; strings.segment = strings.pchar; strings.path = strings.segment + '/'; strings.query = strings.pchar + '/?'; strings.fragment = strings.pchar + '/?'; return Object.keys(strings).reduce(function (charMap, set) { charMap[set] = strings[set].split('').reduce(function (chars, myChar) { chars[myChar] = true; return chars; }, {}); return charMap; }, {}); }()); function encode(str, allowed) { if (typeof str !== 'string') { throw new Error('String required for URL encoding'); } return str.split('').map(function (myChar) { if (allowed.hasOwnProperty(myChar)) { return myChar; } var code = myChar.charCodeAt(0); if (code <= 127) { return '%' + code.toString(16).toUpperCase(); } else { return encodeURIComponent(myChar).toUpperCase(); } }).join(''); } function makeEncoder(allowed) { allowed = allowed || charMap.unreserved; return function (str) { return encode(str, allowed); }; } function decode(str) { return decodeURIComponent(str); } return { /* * Decode URL encoded strings * * @param {string} URL encoded string * @returns {string} URL decoded string */ decode: decode, /* * URL encode a string * * All but alpha-numerics and a very limited set of punctuation - . _ ~ are * encoded. * * @param {string} string to encode * @returns {string} URL encoded string */ encode: makeEncoder(), /* * URL encode a URL * * All character permitted anywhere in a URL are left unencoded even * if that character is not permitted in that portion of a URL. * * Note: This method is typically not what you want. * * @param {string} string to encode * @returns {string} URL encoded string */ encodeURL: makeEncoder(charMap.url), /* * URL encode the scheme portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodeScheme: makeEncoder(charMap.scheme), /* * URL encode the user info portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodeUserInfo: makeEncoder(charMap.userinfo), /* * URL encode the host portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodeHost: makeEncoder(charMap.host), /* * URL encode the port portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodePort: makeEncoder(charMap.port), /* * URL encode a path segment portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodePathSegment: makeEncoder(charMap.segment), /* * URL encode the path portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodePath: makeEncoder(charMap.path), /* * URL encode the query portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodeQuery: makeEncoder(charMap.query), /* * URL encode the fragment portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodeFragment: makeEncoder(charMap.fragment) }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],134:[function(_dereq_,module,exports){ /* * Copyright 2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; var undef; define(function (_dereq_) { var uriEncoder, operations, prefixRE; uriEncoder = _dereq_('./uriEncoder'); prefixRE = /^([^:]*):([0-9]+)$/; operations = { '': { first: '', separator: ',', named: false, empty: '', encoder: uriEncoder.encode }, '+': { first: '', separator: ',', named: false, empty: '', encoder: uriEncoder.encodeURL }, '#': { first: '#', separator: ',', named: false, empty: '', encoder: uriEncoder.encodeURL }, '.': { first: '.', separator: '.', named: false, empty: '', encoder: uriEncoder.encode }, '/': { first: '/', separator: '/', named: false, empty: '', encoder: uriEncoder.encode }, ';': { first: ';', separator: ';', named: true, empty: '', encoder: uriEncoder.encode }, '?': { first: '?', separator: '&', named: true, empty: '=', encoder: uriEncoder.encode }, '&': { first: '&', separator: '&', named: true, empty: '=', encoder: uriEncoder.encode }, '=': { reserved: true }, ',': { reserved: true }, '!': { reserved: true }, '@': { reserved: true }, '|': { reserved: true } }; function apply(operation, expression, params) { /*jshint maxcomplexity:11 */ return expression.split(',').reduce(function (result, variable) { var opts, value; opts = {}; if (variable.slice(-1) === '*') { variable = variable.slice(0, -1); opts.explode = true; } if (prefixRE.test(variable)) { var prefix = prefixRE.exec(variable); variable = prefix[1]; opts.maxLength = parseInt(prefix[2]); } variable = uriEncoder.decode(variable); value = params[variable]; if (value === undef || value === null) { return result; } if (Array.isArray(value)) { result += value.reduce(function (result, value) { if (result.length) { result += opts.explode ? operation.separator : ','; if (operation.named && opts.explode) { result += operation.encoder(variable); result += value.length ? '=' : operation.empty; } } else { result += operation.first; if (operation.named) { result += operation.encoder(variable); result += value.length ? '=' : operation.empty; } } result += operation.encoder(value); return result; }, ''); } else if (typeof value === 'object') { result += Object.keys(value).reduce(function (result, name) { if (result.length) { result += opts.explode ? operation.separator : ','; } else { result += operation.first; if (operation.named && !opts.explode) { result += operation.encoder(variable); result += value[name].length ? '=' : operation.empty; } } result += operation.encoder(name); result += opts.explode ? '=' : ','; result += operation.encoder(value[name]); return result; }, ''); } else { value = String(value); if (opts.maxLength) { value = value.slice(0, opts.maxLength); } result += result.length ? operation.separator : operation.first; if (operation.named) { result += operation.encoder(variable); result += value.length ? '=' : operation.empty; } result += operation.encoder(value); } return result; }, ''); } function expandExpression(expression, params) { var operation; operation = operations[expression.slice(0,1)]; if (operation) { expression = expression.slice(1); } else { operation = operations['']; } if (operation.reserved) { throw new Error('Reserved expression operations are not supported'); } return apply(operation, expression, params); } function expandTemplate(template, params) { var start, end, uri; uri = ''; end = 0; while (true) { start = template.indexOf('{', end); if (start === -1) { // no more expressions uri += template.slice(end); break; } uri += template.slice(end, start); end = template.indexOf('}', start) + 1; uri += expandExpression(template.slice(start + 1, end - 1), params); } return uri; } return { /** * Expand a URI Template with parameters to form a URI. * * Full implementation (level 4) of rfc6570. * @see https://tools.ietf.org/html/rfc6570 * * @param {string} template URI template * @param {Object} [params] params to apply to the template durring expantion * @returns {string} expanded URI */ expand: expandTemplate }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"./uriEncoder":133}]},{},[1]);
wil93/cdnjs
ajax/libs/forerunnerdb/1.3.477/fdb-all.js
JavaScript
mit
1,042,405
/* XLogin over portal body */ $PBJQ(document).ready(function(){ if( $PBJQ('#loginLink2').length == 1 ){ $PBJQ('#loginLink2').click( function( e ){ $PBJQ('body').append('<div id="Mrphs-xlogin-container" />'); $PBJQ('#Mrphs-xlogin-container').load('/portal/xlogin #Mrphs-xlogin',function(){ $PBJQ('#Mrphs-xlogin-container').addClass('loaded'); $PBJQ('#Mrphs-xlogin').addClass('loadedByAjax'); $PBJQ('#eid').focus(); }); $PBJQ('.Mrphs-portalWrapper').addClass('blurry'); $PBJQ('body').append('<div id="loginPortalMask" />'); $PBJQ('#loginPortalMask').bgiframe(); $PBJQ('#loginPortalMask').click(function(){ $PBJQ('#loginPortalMask').remove(); $PBJQ('#Mrphs-xlogin-container').remove(); $PBJQ('.Mrphs-portalWrapper').removeClass('blurry'); }); e.preventDefault(); }); } });
ouit0408/sakai
reference/library/src/morpheus-master/js/src/sakai.morpheus.xlogin.js
JavaScript
apache-2.0
898
'use strict' module.exports = Math.PI.toString().slice(0, 6)
wooorm/mdast-usage
test/fixtures/require-last/index.js
JavaScript
mit
62
/*! UIkit 2.24.2 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */ (function(addon) { var component; if (window.UIkit) { component = addon(UIkit); } if (typeof define == "function" && define.amd) { define("uikit-sticky", ["uikit"], function(){ return component || addon(UIkit); }); } })(function(UI){ "use strict"; var $win = UI.$win, $doc = UI.$doc, sticked = [], direction = 1; UI.component('sticky', { defaults: { top : 0, bottom : 0, animation : '', clsinit : 'uk-sticky-init', clsactive : 'uk-active', clsinactive : '', getWidthFrom : '', showup : false, boundary : false, media : false, target : false, disabled : false }, boot: function() { // should be more efficient than using $win.scroll(checkscrollposition): UI.$doc.on('scrolling.uk.document', function(e, data) { if (!data || !data.dir) return; direction = data.dir.y; checkscrollposition(); }); UI.$win.on('resize orientationchange', UI.Utils.debounce(function() { if (!sticked.length) return; for (var i = 0; i < sticked.length; i++) { sticked[i].reset(true); //sticked[i].self.computeWrapper(); } checkscrollposition(); }, 100)); // init code UI.ready(function(context) { setTimeout(function(){ UI.$("[data-uk-sticky]", context).each(function(){ var $ele = UI.$(this); if(!$ele.data("sticky")) { UI.sticky($ele, UI.Utils.options($ele.attr('data-uk-sticky'))); } }); checkscrollposition(); }, 0); }); }, init: function() { var wrapper = UI.$('<div class="uk-sticky-placeholder"></div>'), boundary = this.options.boundary, boundtoparent; this.wrapper = this.element.css('margin', 0).wrap(wrapper).parent(); this.computeWrapper(); if (boundary) { if (boundary === true || boundary[0] === '!') { boundary = boundary === true ? this.wrapper.parent() : this.wrapper.closest(boundary.substr(1)); boundtoparent = true; } else if (typeof boundary === "string") { boundary = UI.$(boundary); } } this.sticky = { self : this, options : this.options, element : this.element, currentTop : null, wrapper : this.wrapper, init : false, getWidthFrom : UI.$(this.options.getWidthFrom || this.wrapper), boundary : boundary, boundtoparent : boundtoparent, top : 0, calcTop : function() { var top = this.options.top; // dynamic top parameter if (this.options.top && typeof(this.options.top) == 'string') { // e.g. 50vh if (this.options.top.match(/^(-|)(\d+)vh$/)) { top = window.innerHeight * parseInt(this.options.top, 10)/100; // e.g. #elementId, or .class-1,class-2,.class-3 (first found is used) } else { var topElement = UI.$(this.options.top).first(); if (topElement.length && topElement.is(':visible')) { top = -1 * ((topElement.offset().top + topElement.outerHeight()) - this.wrapper.offset().top); } } } this.top = top; }, reset: function(force) { this.calcTop(); var finalize = function() { this.element.css({"position":"", "top":"", "width":"", "left":"", "margin":"0"}); this.element.removeClass([this.options.animation, 'uk-animation-reverse', this.options.clsactive].join(' ')); this.element.addClass(this.options.clsinactive); this.element.trigger('inactive.uk.sticky'); this.currentTop = null; this.animate = false; }.bind(this); if (!force && this.options.animation && UI.support.animation && !UI.Utils.isInView(this.wrapper)) { this.animate = true; this.element.removeClass(this.options.animation).one(UI.support.animation.end, function(){ finalize(); }).width(); // force redraw this.element.addClass(this.options.animation+' '+'uk-animation-reverse'); } else { finalize(); } }, check: function() { if (this.options.disabled) { return false; } if (this.options.media) { switch(typeof(this.options.media)) { case 'number': if (window.innerWidth < this.options.media) { return false; } break; case 'string': if (window.matchMedia && !window.matchMedia(this.options.media).matches) { return false; } break; } } var scrollTop = $win.scrollTop(), documentHeight = $doc.height(), dwh = documentHeight - window.innerHeight, extra = (scrollTop > dwh) ? dwh - scrollTop : 0, elementTop = this.wrapper.offset().top, etse = elementTop - this.top - extra, active = (scrollTop >= etse); if (active && this.options.showup) { // set inactiv if scrolling down if (direction == 1) { active = false; } // set inactive when wrapper is still in view if (direction == -1 && !this.element.hasClass(this.options.clsactive) && UI.Utils.isInView(this.wrapper)) { active = false; } } return active; } }; this.sticky.calcTop(); sticked.push(this.sticky); }, update: function() { checkscrollposition(this.sticky); }, enable: function() { this.options.disabled = false; this.update(); }, disable: function(force) { this.options.disabled = true; this.sticky.reset(force); }, computeWrapper: function() { this.wrapper.css({ 'height' : ['absolute','fixed'].indexOf(this.element.css('position')) == -1 ? this.element.outerHeight() : '', 'float' : this.element.css('float') != 'none' ? this.element.css('float') : '', 'margin' : this.element.css('margin') }); if (this.element.css('position') == 'fixed') { this.element.css({ width: this.sticky.getWidthFrom.length ? this.sticky.getWidthFrom.width() : this.element.width() }); } } }); function checkscrollposition(direction) { var stickies = arguments.length ? arguments : sticked; if (!stickies.length || $win.scrollTop() < 0) return; var scrollTop = $win.scrollTop(), documentHeight = $doc.height(), windowHeight = $win.height(), dwh = documentHeight - windowHeight, extra = (scrollTop > dwh) ? dwh - scrollTop : 0, newTop, containerBottom, stickyHeight, sticky; for (var i = 0; i < stickies.length; i++) { sticky = stickies[i]; if (!sticky.element.is(":visible") || sticky.animate) { continue; } if (!sticky.check()) { if (sticky.currentTop !== null) { sticky.reset(); } } else { if (sticky.top < 0) { newTop = 0; } else { stickyHeight = sticky.element.outerHeight(); newTop = documentHeight - stickyHeight - sticky.top - sticky.options.bottom - scrollTop - extra; newTop = newTop < 0 ? newTop + sticky.top : sticky.top; } if (sticky.boundary && sticky.boundary.length) { var bTop = sticky.boundary.offset().top; if (sticky.boundtoparent) { containerBottom = documentHeight - (bTop + sticky.boundary.outerHeight()) + parseInt(sticky.boundary.css('padding-bottom')); } else { containerBottom = documentHeight - bTop - parseInt(sticky.boundary.css('margin-top')); } newTop = (scrollTop + stickyHeight) > (documentHeight - containerBottom - (sticky.top < 0 ? 0 : sticky.top)) ? (documentHeight - containerBottom) - (scrollTop + stickyHeight) : newTop; } if (sticky.currentTop != newTop) { sticky.element.css({ position : "fixed", top : newTop, width : sticky.getWidthFrom.length ? sticky.getWidthFrom.width() : sticky.element.width(), left : sticky.wrapper.offset().left }); if (!sticky.init) { sticky.element.addClass(sticky.options.clsinit); if (location.hash && scrollTop > 0 && sticky.options.target) { var $target = UI.$(location.hash); if ($target.length) { setTimeout((function($target, sticky){ return function() { sticky.element.width(); // force redraw var offset = $target.offset(), maxoffset = offset.top + $target.outerHeight(), stickyOffset = sticky.element.offset(), stickyHeight = sticky.element.outerHeight(), stickyMaxOffset = stickyOffset.top + stickyHeight; if (stickyOffset.top < maxoffset && offset.top < stickyMaxOffset) { scrollTop = offset.top - stickyHeight - sticky.options.target; window.scrollTo(0, scrollTop); } }; })($target, sticky), 0); } } } sticky.element.addClass(sticky.options.clsactive).removeClass(sticky.options.clsinactive); sticky.element.trigger('active.uk.sticky'); sticky.element.css('margin', ''); if (sticky.options.animation && sticky.init && !UI.Utils.isInView(sticky.wrapper)) { sticky.element.addClass(sticky.options.animation); } sticky.currentTop = newTop; } } sticky.init = true; } } return UI.sticky; });
dumengnanbuaa/awesome-python-webapp
www/static/js/components/sticky.js
JavaScript
gpl-2.0
12,883
YUI.add('moodle-core-blocks', function (Y, NAME) { /** * Provides drag and drop functionality for blocks. * * @module moodle-core-blockdraganddrop */ var AJAXURL = '/lib/ajax/blocks.php', CSS = { BLOCK : 'block', BLOCKREGION : 'block-region', BLOCKADMINBLOCK : 'block_adminblock', EDITINGMOVE : 'editing_move', HEADER : 'header', LIGHTBOX : 'lightbox', REGIONCONTENT : 'region-content', SKIPBLOCK : 'skip-block', SKIPBLOCKTO : 'skip-block-to', MYINDEX : 'page-my-index', REGIONMAIN : 'region-main', BLOCKSMOVING : 'blocks-moving' }; var SELECTOR = { DRAGHANDLE : '.' + CSS.HEADER + ' .commands .moodle-core-dragdrop-draghandle' }; /** * Legacy drag and drop manager. * This drag and drop manager is specifically designed for themes using side-pre and side-post * that do not make use of the block output methods introduced by MDL-39824. * * @namespace M.core.blockdraganddrop * @class LegacyManager * @constructor * @extends M.core.dragdrop */ var DRAGBLOCK = function() { DRAGBLOCK.superclass.constructor.apply(this, arguments); }; Y.extend(DRAGBLOCK, M.core.dragdrop, { skipnodetop : null, skipnodebottom : null, dragsourceregion : null, initializer : function() { // Set group for parent class this.groups = ['block']; this.samenodeclass = CSS.BLOCK; this.parentnodeclass = CSS.REGIONCONTENT; // Add relevant classes and ID to 'content' block region on My Home page. var myhomecontent = Y.Node.all('body#'+CSS.MYINDEX+' #'+CSS.REGIONMAIN+' > .'+CSS.REGIONCONTENT); if (myhomecontent.size() > 0) { var contentregion = myhomecontent.item(0); contentregion.addClass(CSS.BLOCKREGION); contentregion.set('id', CSS.REGIONCONTENT); contentregion.one('div').addClass(CSS.REGIONCONTENT); } // Initialise blocks dragging // Find all block regions on the page var blockregionlist = Y.Node.all('div.'+CSS.BLOCKREGION); if (blockregionlist.size() === 0) { return false; } // See if we are missing either of block regions, // if yes we need to add an empty one to use as target if (blockregionlist.size() !== this.get('regions').length) { var blockregion = Y.Node.create('<div></div>') .addClass(CSS.BLOCKREGION); var regioncontent = Y.Node.create('<div></div>') .addClass(CSS.REGIONCONTENT); blockregion.appendChild(regioncontent); var pre = blockregionlist.filter('#region-pre'); var post = blockregionlist.filter('#region-post'); if (pre.size() === 0 && post.size() === 1) { // pre block is missing, instert it before post blockregion.setAttrs({id : 'region-pre'}); post.item(0).insert(blockregion, 'before'); blockregionlist.unshift(blockregion); } else if (post.size() === 0 && pre.size() === 1) { // post block is missing, instert it after pre blockregion.setAttrs({id : 'region-post'}); pre.item(0).insert(blockregion, 'after'); blockregionlist.push(blockregion); } } blockregionlist.each(function(blockregionnode) { // Setting blockregion as droptarget (the case when it is empty) // The region-post (the right one) // is very narrow, so add extra padding on the left to drop block on it. new Y.DD.Drop({ node: blockregionnode.one('div.'+CSS.REGIONCONTENT), groups: this.groups, padding: '40 240 40 240' }); // Make each div element in the list of blocks draggable var del = new Y.DD.Delegate({ container: blockregionnode, nodes: '.'+CSS.BLOCK, target: true, handles: [SELECTOR.DRAGHANDLE], invalid: '.block-hider-hide, .block-hider-show, .moveto', dragConfig: {groups: this.groups} }); del.dd.plug(Y.Plugin.DDProxy, { // Don't move the node at the end of the drag moveOnEnd: false }); del.dd.plug(Y.Plugin.DDWinScroll); var blocklist = blockregionnode.all('.'+CSS.BLOCK); blocklist.each(function(blocknode) { var move = blocknode.one('a.'+CSS.EDITINGMOVE); if (move) { move.replace(this.get_drag_handle(move.getAttribute('title'), '', 'iconsmall', true)); blocknode.one(SELECTOR.DRAGHANDLE).setStyle('cursor', 'move'); } }, this); }, this); }, get_block_id : function(node) { return Number(node.get('id').replace(/inst/i, '')); }, get_block_region : function(node) { var region = node.ancestor('div.'+CSS.BLOCKREGION).get('id').replace(/region-/i, ''); if (Y.Array.indexOf(this.get('regions'), region) === -1) { // Must be standard side-X if (right_to_left()) { if (region === 'post') { region = 'pre'; } else if (region === 'pre') { region = 'post'; } } return 'side-' + region; } // Perhaps custom region return region; }, get_region_id : function(node) { return node.get('id').replace(/region-/i, ''); }, drag_start : function(e) { // Get our drag object var drag = e.target; // Store the parent node of original drag node (block) // we will need it later for show/hide empty regions this.dragsourceregion = drag.get('node').ancestor('div.'+CSS.BLOCKREGION); // Determine skipnodes and store them if (drag.get('node').previous() && drag.get('node').previous().hasClass(CSS.SKIPBLOCK)) { this.skipnodetop = drag.get('node').previous(); } if (drag.get('node').next() && drag.get('node').next().hasClass(CSS.SKIPBLOCKTO)) { this.skipnodebottom = drag.get('node').next(); } // Add the blocks-moving class so that the theme can respond if need be. Y.one('body').addClass(CSS.BLOCKSMOVING); }, drop_over : function(e) { // Get a reference to our drag and drop nodes var drag = e.drag.get('node'); var drop = e.drop.get('node'); // We need to fix the case when parent drop over event has determined // 'goingup' and appended the drag node after admin-block. if (drop.hasClass(this.parentnodeclass) && drop.one('.'+CSS.BLOCKADMINBLOCK) && drop.one('.'+CSS.BLOCKADMINBLOCK).next('.'+CSS.BLOCK)) { drop.prepend(drag); } // Block is moved within the same region // stop here, no need to modify anything. if (this.dragsourceregion.contains(drop)) { return false; } // TODO: Hiding-displaying block region only works for base theme blocks // (region-pre, region-post) at the moment. It should be improved // to work with custom block regions as well. // TODO: Fix this for the case when user drag block towards empty section, // then the section appears, then user chnages his mind and moving back to // original section. The opposite section remains opened and empty. var documentbody = Y.one('body'); // Moving block towards hidden region-content, display it var regionname = this.get_region_id(this.dragsourceregion); if (documentbody.hasClass('side-'+regionname+'-only')) { documentbody.removeClass('side-'+regionname+'-only'); } // Moving from empty region-content towards the opposite one, // hide empty one (only for region-pre, region-post areas at the moment). regionname = this.get_region_id(drop.ancestor('div.'+CSS.BLOCKREGION)); if (this.dragsourceregion.all('.'+CSS.BLOCK).size() === 0 && this.dragsourceregion.get('id').match(/(region-pre|region-post)/i)) { if (!documentbody.hasClass('side-'+regionname+'-only')) { documentbody.addClass('side-'+regionname+'-only'); } } }, drag_end : function() { // clear variables this.skipnodetop = null; this.skipnodebottom = null; this.dragsourceregion = null; // Remove the blocks moving class once the drag-drop is over. Y.one('body').removeClass(CSS.BLOCKSMOVING); }, drag_dropmiss : function(e) { // Missed the target, but we assume the user intended to drop it // on the last last ghost node location, e.drag and e.drop should be // prepared by global_drag_dropmiss parent so simulate drop_hit(e). this.drop_hit(e); }, drop_hit : function(e) { var drag = e.drag; // Get a reference to our drag node var dragnode = drag.get('node'); var dropnode = e.drop.get('node'); // Amend existing skipnodes if (dragnode.previous() && dragnode.previous().hasClass(CSS.SKIPBLOCK)) { // the one that belongs to block below move below dragnode.insert(dragnode.previous(), 'after'); } // Move original skipnodes if (this.skipnodetop) { dragnode.insert(this.skipnodetop, 'before'); } if (this.skipnodebottom) { dragnode.insert(this.skipnodebottom, 'after'); } // Add lightbox if it not there var lightbox = M.util.add_lightbox(Y, dragnode); // Prepare request parameters var params = { sesskey : M.cfg.sesskey, courseid : this.get('courseid'), pagelayout : this.get('pagelayout'), pagetype : this.get('pagetype'), subpage : this.get('subpage'), contextid : this.get('contextid'), action : 'move', bui_moveid : this.get_block_id(dragnode), bui_newregion : this.get_block_region(dropnode) }; if (this.get('cmid')) { params.cmid = this.get('cmid'); } if (dragnode.next('.'+this.samenodeclass) && !dragnode.next('.'+this.samenodeclass).hasClass(CSS.BLOCKADMINBLOCK)) { params.bui_beforeid = this.get_block_id(dragnode.next('.'+this.samenodeclass)); } // Do AJAX request Y.io(M.cfg.wwwroot+AJAXURL, { method: 'POST', data: params, on: { start : function() { lightbox.show(); }, success: function(tid, response) { window.setTimeout(function() { lightbox.hide(); }, 250); try { var responsetext = Y.JSON.parse(response.responseText); if (responsetext.error) { new M.core.ajaxException(responsetext); } } catch (e) {} }, failure: function(tid, response) { this.ajax_failure(response); lightbox.hide(); } }, context:this }); } }, { NAME : 'core-blocks-dragdrop', ATTRS : { courseid : { value : null }, cmid : { value : null }, contextid : { value : null }, pagelayout : { value : null }, pagetype : { value : null }, subpage : { value : null }, regions : { value : null } } }); M.core = M.core || {}; M.core.blockdraganddrop = M.core.blockdraganddrop || {}; /** * True if the page is using the new blocks methods. * @private * @static * @property M.core.blockdraganddrop._isusingnewblocksmethod * @type Boolean * @default null */ M.core.blockdraganddrop._isusingnewblocksmethod = null; /** * Returns true if the page is using the new blocks methods. * @static * @method M.core.blockdraganddrop.is_using_blocks_render_method * @return Boolean */ M.core.blockdraganddrop.is_using_blocks_render_method = function() { if (this._isusingnewblocksmethod === null) { var goodregions = Y.all('.block-region[data-blockregion]').size(); var allregions = Y.all('.block-region').size(); this._isusingnewblocksmethod = (allregions === goodregions); if (goodregions > 0 && allregions > 0 && goodregions !== allregions) { } } return this._isusingnewblocksmethod; }; /** * Initialises a drag and drop manager. * This should only ever be called once for a page. * @static * @method M.core.blockdraganddrop.init * @param {Object} params * @return Manager */ M.core.blockdraganddrop.init = function(params) { if (this.is_using_blocks_render_method()) { new MANAGER(params); } else { new DRAGBLOCK(params); } }; /* * Legacy code to keep things working. */ M.core_blocks = M.core_blocks || {}; M.core_blocks.init_dragdrop = function(params) { M.core.blockdraganddrop.init(params); }; /** * This file contains the drag and drop manager class. * * Provides drag and drop functionality for blocks. * * @module moodle-core-blockdraganddrop */ /** * Constructs a new Block drag and drop manager. * * @namespace M.core.blockdraganddrop * @class Manager * @constructor * @extends M.core.dragdrop */ var MANAGER = function() { MANAGER.superclass.constructor.apply(this, arguments); }; MANAGER.prototype = { /** * The skip block link from above the block being dragged while a drag is in progress. * Required by the M.core.dragdrop from whom this class extends. * @private * @property skipnodetop * @type Node * @default null */ skipnodetop : null, /** * The skip block link from below the block being dragged while a drag is in progress. * Required by the M.core.dragdrop from whom this class extends. * @private * @property skipnodebottom * @type Node * @default null */ skipnodebottom : null, /** * An associative object of regions and the * @property regionobjects * @type {Object} Primitive object mocking an associative array. * @type {BLOCKREGION} [regionname]* Each item uses the region name as the key with the value being * an instance of the BLOCKREGION class. */ regionobjects : {}, /** * Called during the initialisation process of the object. * @method initializer */ initializer : function() { var regionnames = this.get('regions'), i = 0, region, regionname, dragdelegation; // Evil required by M.core.dragdrop. this.groups = ['block']; this.samenodeclass = CSS.BLOCK; this.parentnodeclass = CSS.BLOCKREGION; // Add relevant classes and ID to 'content' block region on My Home page. var myhomecontent = Y.Node.all('body#'+CSS.MYINDEX+' #'+CSS.REGIONMAIN+' > .'+CSS.REGIONCONTENT); if (myhomecontent.size() > 0) { var contentregion = myhomecontent.item(0); contentregion.addClass(CSS.BLOCKREGION); contentregion.set('id', CSS.REGIONCONTENT); contentregion.one('div').addClass(CSS.REGIONCONTENT); } for (i in regionnames) { regionname = regionnames[i]; region = new BLOCKREGION({ manager : this, region : regionname, node : Y.one('#block-region-'+regionname) }); this.regionobjects[regionname] = region; // Setting blockregion as droptarget (the case when it is empty) // The region-post (the right one) // is very narrow, so add extra padding on the left to drop block on it. new Y.DD.Drop({ node: region.get_droptarget(), groups: this.groups, padding: '40 240 40 240' }); // Make each div element in the list of blocks draggable dragdelegation = new Y.DD.Delegate({ container: region.get_droptarget(), nodes: '.'+CSS.BLOCK, target: true, handles: [SELECTOR.DRAGHANDLE], invalid: '.block-hider-hide, .block-hider-show, .moveto, .block_fake', dragConfig: {groups: this.groups} }); dragdelegation.dd.plug(Y.Plugin.DDProxy, { // Don't move the node at the end of the drag moveOnEnd: false }); dragdelegation.dd.plug(Y.Plugin.DDWinScroll); // On the DD Manager start operation, we enable all block regions so that they can be drop targets. This // must be done *before* drag:start but after dragging has been initialised. Y.DD.DDM.on('ddm:start', this.enable_all_regions, this); region.change_block_move_icons(this); } }, /** * Returns the ID of the block the given node represents. * @method get_block_id * @param {Node} node * @return {int} The blocks ID in the database. */ get_block_id : function(node) { return Number(node.get('id').replace(/inst/i, '')); }, /** * Returns the block region that the node is part of or belonging to. * @method get_block_region * @param {Y.Node} node * @return {string} The region name. */ get_block_region : function(node) { if (!node.test('[data-blockregion]')) { node = node.ancestor('[data-blockregion]'); } return node.getData('blockregion'); }, /** * Returns the BLOCKREGION instance that represents the block region the given node is part of. * @method get_region_object * @param {Y.Node} node * @return {BLOCKREGION} */ get_region_object : function(node) { return this.regionobjects[this.get_block_region(node)]; }, /** * Enables all fo the regions so that they are all visible while dragging is occuring. * * @method enable_all_regions */ enable_all_regions : function() { var groups = Y.DD.DDM.activeDrag.get('groups'); // As we're called by Y.DD.DDM, we can't be certain that the call // relates specifically to a block drag/drop operation. Test // whether the relevant group applies here. if (!groups || Y.Array.indexOf(groups, 'block') === -1) { return; } var i; for (i in this.regionobjects) { if (!this.regionobjects.hasOwnProperty(i)) { continue; } this.regionobjects[i].enable(); } }, /** * Disables enabled regions if they contain no blocks. * @method disable_regions_if_required */ disable_regions_if_required : function() { var i = 0; for (i in this.regionobjects) { this.regionobjects[i].disable_if_required(); } }, /** * Called by M.core.dragdrop.global_drag_start when dragging starts. * @method drag_start * @param {Event} e */ drag_start : function(e) { // Get our drag object var drag = e.target; // Store the parent node of original drag node (block) // we will need it later for show/hide empty regions // Determine skipnodes and store them if (drag.get('node').previous() && drag.get('node').previous().hasClass(CSS.SKIPBLOCK)) { this.skipnodetop = drag.get('node').previous(); } if (drag.get('node').next() && drag.get('node').next().hasClass(CSS.SKIPBLOCKTO)) { this.skipnodebottom = drag.get('node').next(); } }, /** * Called by M.core.dragdrop.global_drop_over when something is dragged over a drop target. * @method drop_over * @param {Event} e */ drop_over : function(e) { // Get a reference to our drag and drop nodes var drag = e.drag.get('node'); var drop = e.drop.get('node'); // We need to fix the case when parent drop over event has determined // 'goingup' and appended the drag node after admin-block. if (drop.hasClass(CSS.REGIONCONTENT) && drop.one('.'+CSS.BLOCKADMINBLOCK) && drop.one('.'+CSS.BLOCKADMINBLOCK).next('.'+CSS.BLOCK)) { drop.prepend(drag); } }, /** * Called by M.core.dragdrop.global_drop_end when a drop has been completed. * @method drop_end */ drop_end : function() { // Clear variables. this.skipnodetop = null; this.skipnodebottom = null; this.disable_regions_if_required(); }, /** * Called by M.core.dragdrop.global_drag_dropmiss when something has been dropped on a node that isn't contained by a drop target. * @method drag_dropmiss * @param {Event} e */ drag_dropmiss : function(e) { // Missed the target, but we assume the user intended to drop it // on the last ghost node location, e.drag and e.drop should be // prepared by global_drag_dropmiss parent so simulate drop_hit(e). this.drop_hit(e); }, /** * Called by M.core.dragdrop.global_drag_hit when something has been dropped on a drop target. * @method drop_hit * @param {Event} e */ drop_hit : function(e) { // Get a reference to our drag node var dragnode = e.drag.get('node'); var dropnode = e.drop.get('node'); // Amend existing skipnodes if (dragnode.previous() && dragnode.previous().hasClass(CSS.SKIPBLOCK)) { // the one that belongs to block below move below dragnode.insert(dragnode.previous(), 'after'); } // Move original skipnodes if (this.skipnodetop) { dragnode.insert(this.skipnodetop, 'before'); } if (this.skipnodebottom) { dragnode.insert(this.skipnodebottom, 'after'); } // Add lightbox if it not there var lightbox = M.util.add_lightbox(Y, dragnode); // Prepare request parameters var params = { sesskey : M.cfg.sesskey, courseid : this.get('courseid'), pagelayout : this.get('pagelayout'), pagetype : this.get('pagetype'), subpage : this.get('subpage'), contextid : this.get('contextid'), action : 'move', bui_moveid : this.get_block_id(dragnode), bui_newregion : this.get_block_region(dropnode) }; if (this.get('cmid')) { params.cmid = this.get('cmid'); } if (dragnode.next('.'+CSS.BLOCK) && !dragnode.next('.'+CSS.BLOCK).hasClass(CSS.BLOCKADMINBLOCK)) { params.bui_beforeid = this.get_block_id(dragnode.next('.'+CSS.BLOCK)); } // Do AJAX request Y.io(M.cfg.wwwroot+AJAXURL, { method: 'POST', data: params, on: { start : function() { lightbox.show(); }, success: function(tid, response) { window.setTimeout(function() { lightbox.hide(); }, 250); try { var responsetext = Y.JSON.parse(response.responseText); if (responsetext.error) { new M.core.ajaxException(responsetext); } } catch (e) {} }, failure: function(tid, response) { this.ajax_failure(response); lightbox.hide(); }, complete : function() { this.disable_regions_if_required(); } }, context:this }); } }; Y.extend(MANAGER, M.core.dragdrop, MANAGER.prototype, { NAME : 'core-blocks-dragdrop-manager', ATTRS : { /** * The Course ID if there is one. * @attribute courseid * @type int|null * @default null */ courseid : { value : null }, /** * The Course Module ID if there is one. * @attribute cmid * @type int|null * @default null */ cmid : { value : null }, /** * The Context ID. * @attribute contextid * @type int|null * @default null */ contextid : { value : null }, /** * The current page layout. * @attribute pagelayout * @type string|null * @default null */ pagelayout : { value : null }, /** * The page type string, should be used as the id for the body tag in the theme. * @attribute pagetype * @type string|null * @default null */ pagetype : { value : null }, /** * The subpage identifier, if any. * @attribute subpage * @type string|null * @default null */ subpage : { value : null }, /** * An array of block regions that are present on the page. * @attribute regions * @type array|null * @default Array[] */ regions : { value : [] } } }); /** * This file contains the Block Region class used by the drag and drop manager. * * Provides drag and drop functionality for blocks. * * @module moodle-core-blockdraganddrop */ /** * Constructs a new block region object. * * @namespace M.core.blockdraganddrop * @class BlockRegion * @constructor * @extends Base */ var BLOCKREGION = function() { BLOCKREGION.superclass.constructor.apply(this, arguments); }; BLOCKREGION.prototype = { /** * Called during the initialisation process of the object. * @method initializer */ initializer : function() { var node = this.get('node'); if (!node) { node = this.create_and_add_node(); } var body = Y.one('body'), hasblocks = node.all('.'+CSS.BLOCK).size() > 0, hasregionclass = this.get_has_region_class(); this.set('hasblocks', hasblocks); if (!body.hasClass(hasregionclass)) { body.addClass(hasregionclass); } body.addClass((hasblocks) ? this.get_used_region_class() : this.get_empty_region_class()); body.removeClass((hasblocks) ? this.get_empty_region_class() : this.get_used_region_class()); }, /** * Creates a generic block region node and adds it to the DOM at the best guess location. * Any calling of this method is an unfortunate circumstance. * @method create_and_add_node * @return Node The newly created Node */ create_and_add_node : function() { var c = Y.Node.create, region = this.get('region'), node = c('<div id="block-region-'+region+'" data-droptarget="1"></div>') .addClass(CSS.BLOCKREGION) .setData('blockregion', region), regions = this.get('manager').get('regions'), i, haspre = false, haspost = false, added = false, pre, post; for (i in regions) { if (regions[i].match(/(pre|left)/)) { haspre = regions[i]; } else if (regions[i].match(/(post|right)/)) { haspost = regions[i]; } } if (haspre !== false && haspost !== false) { if (region === haspre) { post = Y.one('#block-region-'+haspost); if (post) { post.insert(node, 'before'); added = true; } } else { pre = Y.one('#block-region-'+haspre); if (pre) { pre.insert(node, 'after'); added = true; } } } if (added === false) { Y.one('body').append(node); } this.set('node', node); return node; }, /** * Change the move icons to enhanced drag handles and changes the cursor to a move icon when over the header. * @param M.core.dragdrop the block manager * @method change_block_move_icons */ change_block_move_icons : function(manager) { var handle, icon; this.get('node').all('.'+CSS.BLOCK+' a.'+CSS.EDITINGMOVE).each(function(moveicon){ moveicon.setStyle('cursor', 'move'); handle = manager.get_drag_handle(moveicon.getAttribute('title'), '', 'icon', true); icon = handle.one('img'); icon.addClass('iconsmall'); icon.removeClass('icon'); moveicon.replace(handle); }); }, /** * Returns the class name on the body that signifies the document knows about this region. * @method get_has_region_class * @return String */ get_has_region_class : function() { return 'has-region-'+this.get('region'); }, /** * Returns the class name to use on the body if the region contains no blocks. * @method get_empty_region_class * @return String */ get_empty_region_class : function() { return 'empty-region-'+this.get('region'); }, /** * Returns the class name to use on the body if the region contains blocks. * @method get_used_region_class * @return String */ get_used_region_class : function() { return 'used-region-'+this.get('region'); }, /** * Returns the node to use as the drop target for this region. * @method get_droptarget * @return Node */ get_droptarget : function() { var node = this.get('node'); if (node.test('[data-droptarget="1"]')) { return node; } return node.one('[data-droptarget="1"]'); }, /** * Enables the block region so that we can be sure the user can see it. * This is done even if it is empty. * @method enable */ enable : function() { Y.one('body').addClass(this.get_used_region_class()).removeClass(this.get_empty_region_class()); }, /** * Disables the region if it contains no blocks, essentially hiding it from the user. * @method disable_if_required */ disable_if_required : function() { if (this.get('node').all('.'+CSS.BLOCK).size() === 0) { Y.one('body').addClass(this.get_empty_region_class()).removeClass(this.get_used_region_class()); } } }; Y.extend(BLOCKREGION, Y.Base, BLOCKREGION.prototype, { NAME : 'core-blocks-dragdrop-blockregion', ATTRS : { /** * The drag and drop manager that created this block region instance. * @attribute manager * @type M.core.blockdraganddrop.Manager * @writeOnce */ manager : { // Can only be set during initialisation and must be set then. writeOnce : 'initOnly', validator : function (value) { return Y.Lang.isObject(value) && value instanceof MANAGER; } }, /** * The name of the block region this object represents. * @attribute region * @type String * @writeOnce */ region : { // Can only be set during initialisation and must be set then. writeOnce : 'initOnly', validator : function (value) { return Y.Lang.isString(value); } }, /** * The node the block region HTML starts at.s * @attribute region * @type Y.Node */ node : { validator : function (value) { return Y.Lang.isObject(value) || Y.Lang.isNull(value); } }, /** * True if the block region currently contains blocks. * @attribute hasblocks * @type Boolean * @default false */ hasblocks : { value : false, validator : function (value) { return Y.Lang.isBoolean(value); } } } }); }, '@VERSION@', { "requires": [ "base", "node", "io", "dom", "dd", "dd-scroll", "moodle-core-dragdrop", "moodle-core-notification" ] });
sameertechworks/wpmoodle
moodle/lib/yui/build/moodle-core-blocks/moodle-core-blocks.js
JavaScript
gpl-2.0
33,181
/* =========================================================== * by.js * Belarusian translation for Trumbowyg * http://alex-d.github.com/Trumbowyg * =========================================================== * Author : Yury Karalkou */ jQuery.trumbowyg.langs.by = { viewHTML: 'Паглядзець HTML', undo: 'Скасаваць', redo: 'Паўтарыць', formatting: 'Фарматаванне', p: 'Звычайны', blockquote: 'Цытата', code: 'Код', header: 'Загаловак', bold: 'Паўтлусты', italic: 'Курсіў', strikethrough: 'Закрэслены', underline: 'Падкрэслены', strong: 'Паўтлусты', em: 'Курсіў', del: 'Закрэслены', superscript: 'Верхні індэкс', subscript: 'Індэкс', unorderedList: 'Звычайны спіс', orderedList: 'Нумараваны спіс', insertImage: 'Уставіць выяву', insertVideo: 'Уставіць відэа', link: 'Спасылка', createLink: 'Уставіць спасылку', unlink: 'Выдаліць спасылку', justifyLeft: 'Па леваму боку', justifyCenter: 'У цэнтры', justifyRight: 'Па праваму боку', justifyFull: 'Па шырыні', horizontalRule: 'Гарызантальная лінія', removeformat: 'Ачысціць фарматаванне', fullscreen: 'На ўвесь экран', close: 'Зачыніць', submit: 'Уставіць', reset: 'Скасаваць', required: 'Абавязкова', description: 'Апісанне', title: 'Падказка', text: 'Тэкст' };
sandino/django-trumbowyg
trumbowyg/static/trumbowyg/langs/by.js
JavaScript
mit
1,762
var booleanCondition = require('esmangle-evaluator').booleanCondition; var recast = require('recast'); var types = recast.types; var b = types.builders; var VISITOR_METHODS = { visitLogicalExpression: visitLogicalExp, visitIfStatement: visitCondition, visitConditionalExpression: visitCondition }; module.exports = function(branch) { recast.visit(branch, VISITOR_METHODS); return branch; }; /** * "||" and "&&" */ function visitLogicalExp(path) { var leftEval = booleanCondition(path.node.left); if (typeof leftEval !== 'boolean') { // console.log('___ %s ___', path.node.operator); this.traverse(path); return; } if (leftEval === true && path.node.operator === '||') { // console.log('true || ___'); path.replace(b.literal(true)); recast.visit(path, VISITOR_METHODS); return false; } if (leftEval === true && path.node.operator === '&&') { // console.log('true && ___'); path.replace(path.node.right); recast.visit(path, VISITOR_METHODS); return false; } if (leftEval === false && path.node.operator === '&&') { // console.log('false && ___'); path.replace(b.literal(false)); recast.visit(path, VISITOR_METHODS); return false; } if (leftEval === false && path.node.operator === '||') { // console.log('false || ___'); path.replace(path.node.right); recast.visit(path, VISITOR_METHODS); return false; } } /** * "if" and ternary "?" */ function visitCondition(path) { var testEval = booleanCondition(path.node.test); if (typeof testEval !== 'boolean') { // console.log('if/? ___'); this.traverse(path); return; } if (testEval === true) { // console.log('if/? (true)'); path.replace(path.value.consequent); recast.visit(path, VISITOR_METHODS); return false; } if (testEval === false) { // console.log('if/? (false)'); path.replace(path.value.alternate); recast.visit(path, VISITOR_METHODS); return false; } }
Phalanstere/WritersStudio
writers_studio-win32-ia32/resources/app/node_modules/unreachable-branch-transform/unreachableBranchTransformer.js
JavaScript
mit
1,993
/** * Module dependencies. */ var fs = require('fs'); var path = require('path'); var assert = require('assert'); var degenerator = require('../'); describe('degenerator()', function () { describe('"expected" fixture tests', function () { fs.readdirSync(__dirname).forEach(function (n) { if ('test.js' == n) return; if (/\.expected\.js$/.test(n)) return; var expectedName = path.basename(n, '.js') + '.expected.js'; it(n + ' → ' + expectedName, function () { var sourceName = path.resolve(__dirname, n); var compiledName = path.resolve(__dirname, expectedName); var js = fs.readFileSync(sourceName, 'utf8'); var expected = fs.readFileSync(compiledName, 'utf8'); // the test case can define the `names` to use as a // comment on the first line of the file var names = js.match(/\/\/\s*(.*)/); if (names) { // the comment should be a comma-separated list of function names names = names[1].split(/,\s*/); } else { // if no function names were passed in then convert them all names = [ /.*/ ]; } var compiled = degenerator(js, names); assert.equal(expected.trim(), compiled.trim()); }); }); }); });
jphacks/TK_23
web/node_modules/degenerator/test/test.js
JavaScript
mit
1,288
/* MIT License (c) copyright B Cavalier & J Hann */ var p=!0,t=!1; (function(g){function l(){}function s(a,b){return 0==P.call(a).indexOf("[object "+b)}function k(a){return a&&"/"==a.charAt(a.length-1)?a.substr(0,a.length-1):a}function A(a,b){var c,f,d;f=1;a=a.replace(Q,function(a,b,c){c&&f++;d=p;return""});return d?(c=b.split("/"),c.splice(c.length-f,f),c.concat(a||[]).join("/")):a}function z(a){var b=a.indexOf("!");return{K:a.substr(b+1),g:0<=b&&a.substr(0,b)}}function B(){}function C(a){B.prototype=a;a=new B;B.prototype=K;return a}function u(){function a(a,b, c){f.push([a,b,c])}function b(a,b){for(var c,d=0;c=f[d++];)(c=c[a])&&c(b)}var c,f,d;c=this;f=[];d=function(c,j){a=c?function(a){a&&a(j)}:function(a,b){b&&b(j)};d=l;b(c?0:1,j);b=l;f=m};this.W=function(b,c,f){a(b,c,f)};this.h=function(a){c.$=a;d(p,a)};this.c=function(a){c.Z=a;d(t,a)};this.q=function(a){b(2,a)}}function q(a,b,c,f){a instanceof u?a.W(b,c,f):b(a)}function w(a,b,c){return function(){var f;0<=--a&&b&&(f=b.apply(m,arguments));0==a&&c&&c(f);return f}}function v(){function a(b,f,d){var e;e= i.e(h,m,[].concat(b));this.then=b=function(a,b){q(e,function(b){a&&a.apply(m,b)},function(a){if(b)b(a);else throw a;});return this};this.next=function(b,c){return new a(b,c,e)};f&&b(f);q(d,function(){i.i(e)})}var b=[].slice.call(arguments);s(b[0],"Object")&&(h=i.C(b.shift()),i.t(h));return new a(b[0],b[1])}function D(a){var b=a.id;if(b==m)if(E!==m)E={A:"Multiple anonymous defines in url"};else if(!(b=i.T()))E=a;if(b!=m){var c=o[b];b in o||(c=i.k(b,h).d,c=o[b]=i.v(c,b));c instanceof u&&(c.Y=t,i.w(c, a))}}var h=g.curl,x=g.document,F=x&&(x.head||x.getElementsByTagName("head")[0]),y={},r={},L={},G={},K={},P=K.toString,m,M={loaded:1,interactive:L,complete:1},o={},I=t,E,R=/\?/,N=/^\/|^[^:]+:\/\//,Q=/(?:^|\/)(\.)(\.?)\/?/g,S=/\/\*[\s\S]*?\*\/|(?:[^\\])\/\/.*?[\n\r]/g,T=/require\s*\(\s*["']([^"']+)["']\s*\)|(?:[^\\]?)(["'])/g,J,i;i={e:function(a,b,c,f){function d(a){return A(a,j.m)}function e(b,c){var f,e,n,h;f=c&&function(a){c.apply(m,a)};if(s(b,"String")){e=d(b);n=o[e];h=n instanceof u&&n.a;if(!(e in o))throw Error("Module not resolved: "+e);if(f)throw Error("require(id, callback) not allowed");return h||n}q(i.i(i.e(a,j.id,b)),f)}var j;j=new u;j.m=j.id=b||"";j.G=f;j.z=c;j.j=e;e.toUrl=function(b){return i.k(d(b),a).url};j.X=d;return j},v:function(a,b,c,f){var d,e,j,H;d=i.e(a,b,m,c);d.m=f==m?b:f;e=d.h;j=w(1,function(a){d.n=a;try{H=i.o(d)}catch(b){d.c(b)}});d.h=function(a){j(a);o[d.id]=H;e(H)};d.B=function(a){d.a&&(j(a),d.q(r))};return d},M:function(a,b,c,f){a=i.e(a,b,m,c);a.m=f;return a},S:function(a){return a.j}, D:function(a){return a.a||(a.a={})},R:function(a){var b=a.p;b||(b=a.p={id:a.id,uri:i.F(a),exports:i.D(a)},b.a=b.exports);return b},F:function(a){return a.url||(a.url=i.u(a.j.toUrl(a.id)))},C:function(a){function b(b,c){var d,e,h,n,m;for(m in b){h=b[m];n=a;e=z(k(h.id||h.name||m));d=e.K;if(e=e.g)n=f[e],n||(n=f[e]=C(a),n.f=C(a.f),n.b=[]),delete b[m];if(c){e=h;var r=void 0,g=void 0,r=e.path=k(e.path||e.location||""),g=e.main||"main";e.d=e.config;e.H="."==g.charAt(0)?k(A(g,r)):k(r)+"/"+g}else e={path:k(h)}; e.L=d.split("/").length;d?(n.f[d]=e,n.b.push(d)):n.s=i.J(h,a)}}function c(a){var b=a.f;a.V=RegExp("^("+a.b.sort(function(a,c){return b[a].L<b[c].L}).join("|").replace(/\//g,"\\/")+")(?=\\/|$)");delete a.b}var f;a.s=a.baseUrl||"";a.I="pluginPath"in a?a.pluginPath:"curl/plugin";a.f={};f=a.plugins=a.plugins||{};a.b=[];b(a.paths,t);b(a.packages,p);for(var d in f){var e=f[d].b;e&&(f[d].b=e.concat(a.b),c(f[d]))}c(a);return a},t:function(a){var b;(b=a.preloads)&&0<b.length&&q(I,function(){I=i.i(i.e(a,m, b,p))})},k:function(a,b,c){var f,d,e;f=b.f;c&&b.I&&0>a.indexOf("/")&&!(a in f)&&(a=k(b.I)+"/"+a);c=N.test(a)?a:a.replace(b.V,function(b){d=f[b]||{};e=d.d;return d.H&&b==a?d.H:d.path||""});return{path:c,d:e||h,url:i.J(c,b)}},J:function(a,b){var c=b.s;return c&&!N.test(a)?k(c)+"/"+a:a},u:function(a){return a+(R.test(a)?"":".js")},U:function(a,b,c){var f=x.createElement("script");f.onload=f.onreadystatechange=function(c){c=c||g.event;if("load"==c.type||M[f.readyState])delete G[a.id],f.onload=f.onreadystatechange= f.onerror="",b()};f.onerror=function(){c(Error("Syntax or http error: "+a.url))};f.charset="utf-8";f.async=p;f.src=a.url;G[a.id]=f;F.insertBefore(f,F.firstChild)},N:function(a){var b=[],c;("string"==typeof a?a:a.toSource?a.toSource():a.toString()).replace(S,"").replace(T,function(a,d,e){e?c=c==e?m:c:c||b.push(d);return a});return b},Q:function(a){var b,c,f,d,e,j;e=a.length;f=a[e-1];d=s(f,"Function")?f.length:-1;2==e?s(a[0],"Array")?c=a[0]:b=a[0]:3==e&&(b=a[0],c=a[1]);!c&&0<d&&(j=p,c=["require","exports", "module"].slice(0,d).concat(i.N(f)));return{id:b,n:c||[],r:0<=d?f:function(){return f},l:j}},o:function(a){var b;b=a.r.apply(a.l?a.a:m,a.n);b===m&&a.a&&(b=a.p?a.a=a.p.a:a.a);return b},w:function(a,b){q(a.G||I,function(){a.r=b.r;a.l=b.l;a.z=b.n;i.i(a)})},i:function(a){function b(a,b,c){j[b]=a;c&&k(a,b)}function c(b,c){var f,d,e,j;f=w(1,function(a){d(a);l(a,c)});d=w(1,function(a){k(a,c)});e=i.O(b,a);(j=e instanceof u&&e.a)&&d(j);q(e,f,a.c,a.a&&function(a){e.a&&(a==y?d(e.a):a==r&&f(e.a))})}function f(){a.h(j)} var d,e,j,h,g,k,l;j=[];e=a.z;h=e.length;0==e.length&&f();k=w(h,b,function(){a.B&&a.B(j)});l=w(h,b,f);for(d=0;d<h;d++)g=e[d],g in J?(l(J[g](a),d,p),a.a&&a.q(y)):g?c(g,d):l(m,d,p);return a},P:function(a){i.F(a);i.U(a,function(){var b=E;E=m;a.Y!==t&&(!b||b.A?a.c(Error((b&&b.A||"define() missing or duplicated: url").replace("url",a.url))):i.w(a,b))},a.c);return a},O:function(a,b){var c,f,d,e,j,g,k,r,l,n;c=b.X;f=b.G;d=z(a);g=d.K;e=c(d.g||g);k=i.k(e,h,!!d.g);if(d.g)j=e;else if(j=k.d.moduleLoader)g=e,e= j,k=i.k(j,h);r=o[e];e in o||(r=o[e]=i.v(k.d,e,f,d.g?k.path:m),r.url=i.u(k.url),i.P(r));e==j&&(l=new u,n=h.plugins[j]||h,q(r,function(a){var b,d,e;e=a.dynamic;g="normalize"in a?a.normalize(g,c,n)||"":c(g);d=j+"!"+g;b=o[d];if(!(d in o)){b=i.M(n,d,f,g);e||(o[d]=b);var h=function(a){b.h(a);e||(o[d]=a)};h.resolve=h;h.reject=b.c;a.load(g,b.j,h,n)}l!=b&&q(b,l.h,l.c,l.q)},l.c));return l||r},T:function(){var a;if(!s(g.opera,"Opera"))for(var b in G)if(M[G[b].readyState]==L){a=b;break}return a}};J={require:i.S, exports:i.D,module:i.R};if(!s(h,"Function")){h=i.C(h||{});i.t(h);var O;(h.apiContext||g)[h.apiName||"curl"]=v;o.curl=v;O=g.define=function(){var a=i.Q(arguments);D(a)};v.version="0.6.2";O.amd={plugins:p,jQuery:p,curl:"0.6.2"};o["curl/_privileged"]={core:i,cache:o,cfg:h,_define:D,_curl:v,Promise:u}}})(this); (function(g,l){function s(){if(!l.body)return t;y||(y=l.createTextNode(""));try{return l.body.removeChild(l.body.appendChild(y)),y=F,p}catch(h){return t}}function k(){var g;g=B[l[z]]&&s();if(!q&&g){q=p;for(clearTimeout(x);D=h.pop();)D();u&&(l[z]="complete");for(var k;k=C.shift();)k()}return g}function A(){k();q||(x=setTimeout(A,w))}var z="readyState",B={loaded:1,interactive:1,complete:1},C=[],u=l&&"string"!=typeof l[z],q=t,w=10,v,D,h=[],x,F,y;v="addEventListener"in g?function(g,h){g.addEventListener(h, k,t);return function(){g.removeEventListener(h,k,t)}}:function(g,h){g.attachEvent("on"+h,k);return function(){g.detachEvent(h,k)}};l&&!k()&&(h=[v(g,"load"),v(l,"readystatechange"),v(g,"DOMContentLoaded")],x=setTimeout(A,w));define("curl/domReady",function(){function g(h){q?h():C.push(h)}g.then=g;g.amd=p;return g})})(this,this.document); define("curl/shim/dojo16",["curl/_privileged","curl/domReady"],function(g,l){function s(g){g.ready||(g.ready=function(g){l(g)});g.nameToUrl||(g.nameToUrl=function(k,l){return g.toUrl(k+(l||""))})}var k=g.core.o;s(g._curl);g.core.o=function(g){s(g.j);return k(g)};return p});define("domReady",["curl/domReady"],function(g){return{load:function(l,s,k){g(k)}}});
BenjaminVanRyseghem/cdnjs
ajax/libs/curl/0.6.2a/curl-for-dojo1.6/curl.js
JavaScript
mit
7,678
export class DOMSerializer { elementSelector(element) { // iterate up the dom var selectors = []; while (element.tagName !== 'HTML') { var selector = element.tagName.toLowerCase(); var id = element.getAttribute('id'); if (id) { selector += "#" + id; } var className = element.className; if (className) { var classes = className.split(' '); for (var i = 0; i < classes.length; i++) { var c = classes[i]; if (c) { selector += '.' + c; } } } if (!element.parentNode) { return null; } var childIndex = Array.prototype.indexOf.call(element.parentNode.children, element); selector += ':nth-child(' + (childIndex + 1) + ')'; element = element.parentNode; selectors.push(selector); } return selectors.reverse().join('>'); } elementName(element) { // 1. ion-track-name directive var name = element.getAttribute('ion-track-name'); if (name) { return name; } // 2. id var id = element.getAttribute('id'); if (id) { return id; } // 3. no unique identifier --> return null return null; } }
IsaacMiguel/aidaScan-App
www/lib/ionic-platform-web-client/src/analytics/serializers.js
JavaScript
mit
1,227
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var important = function important(node) { return node.important; }; var unimportant = function unimportant(node) { return !node.important; }; var hasInherit = function hasInherit(node) { return ~node.value.indexOf('inherit'); }; var hasInitial = function hasInitial(node) { return ~node.value.indexOf('initial'); }; exports['default'] = function () { for (var _len = arguments.length, props = Array(_len), _key = 0; _key < _len; _key++) { props[_key] = arguments[_key]; } if (props.some(hasInherit) || props.some(hasInitial)) { return false; } return props.every(important) || props.every(unimportant); }; module.exports = exports['default'];
puyanLiu/LPYFramework
前端练习/autoFramework/webpack-demo3/node_modules/postcss-merge-longhand/dist/lib/canMerge.js
JavaScript
apache-2.0
780
var assert = require('assert'); var cp = require('child_process'); var fs = require('fs'); var fs_extra = require('fs-extra'); var curDir = fs.realpathSync('.'); var exec_path = process.execPath; var app_path = path.join(curDir, 'internal'); describe('chromium-args', function() { describe('--disable-javascript', function() { var child; before(function(done) { this.timeout(0); fs_extra.copy(path.join(app_path, 'package1.json'), path.join(app_path, 'package.json'), function (err) { if (err) { throw err; } child = spawnChildProcess(path.join(curDir, 'internal')); }); setTimeout(function(){done();}, 2500); }); after(function() { if (child) child.kill(); fs.unlink(path.join(app_path, 'hi'), function(err) {if(err && err.code !== 'ENOENT') throw err}); fs.unlink(path.join(app_path, 'package.json'), function(err) {if(err && err.code !== 'ENOENT') throw err}); }); it('javascript should not be executed', function() { var result = fs.existsSync(path.join(app_path, 'hi')); assert.equal(result, false); }); }); describe('--app=url', function() { var result = false, result2 = false; var child, server; before(function(done) { this.timeout(0); fs_extra.copy(path.join(app_path, 'package2.json'), path.join(app_path, 'package.json'), function (err) { if (err) { throw err; } server = createTCPServer(13013); server.on('connection', function(socket) { socket.setEncoding('utf8'); socket.on('data', function(data) { result2 = data; result = true; done(); }); }); child = spawnChildProcess(path.join(curDir, 'internal')); setTimeout(function() { if (!result) { child.kill(); done('timeout'); } }, 4500); }); }); after(function(done) { this.timeout(0); child.kill(); server.close(); fs.unlink(path.join(app_path, 'package.json'), function(err) {if(err && err.code !== 'ENOENT') throw err}); fs.unlink(path.join(app_path, 'hi'), function(err) {if(err && err.code !== 'ENOENT') throw err}); done(); }); it('website should be the url', function() { assert.equal(result2, true); }); }); });
280455936/nw.js
tests/automation/chromium-args/mocha_test.js
JavaScript
mit
2,565
!function(t){t.datepick.regional.hy={clearText:"Մաքրել",clearStatus:"",closeText:"Փակել",closeStatus:"",prevText:"&#x3c;Նախ.",prevStatus:"",prevBigText:"&#x3c;&#x3c;",prevBigStatus:"",nextText:"Հաջ.&#x3e;",nextStatus:"",nextBigText:"&#x3e;&#x3e;",nextBigStatus:"",currentText:"Այսօր",currentStatus:"",monthNames:["Հունվար","Փետրվար","Մարտ","Ապրիլ","Մայիս","Հունիս","Հուլիս","Օգոստոս","Սեպտեմբեր","Հոկտեմբեր","Նոյեմբեր","Դեկտեմբեր"],monthNamesShort:["Հունվ","Փետր","Մարտ","Ապր","Մայիս","Հունիս","Հուլ","Օգս","Սեպ","Հոկ","Նոյ","Դեկ"],monthStatus:"",yearStatus:"",weekHeader:"ՇԲՏ",weekStatus:"",dayNames:["կիրակի","եկուշաբթի","երեքշաբթի","չորեքշաբթի","հինգշաբթի","ուրբաթ","շաբաթ"],dayNamesShort:["կիր","երկ","երք","չրք","հնգ","ուրբ","շբթ"],dayNamesMin:["կիր","երկ","երք","չրք","հնգ","ուրբ","շբթ"],dayStatus:"DD",dateStatus:"D, M d",dateFormat:"dd.mm.yy",firstDay:1,initStatus:"",isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepick.setDefaults(t.datepick.regional.hy)}(jQuery); //# sourceMappingURL=jquery.datepick-hy.min.js.map
kiwi89/cdnjs
ajax/libs/datepick/3.7.5/js/jquery.datepick-hy.min.js
JavaScript
mit
1,280
/** * jQRangeSlider * A javascript slider selector that supports dates * * Copyright (C) Guillaume Gautreau 2012 * Dual licensed under the MIT or GPL Version 2 licenses. */ (function($, undefined){ "use strict"; $.widget("ui.rangeSliderDraggable", $.ui.rangeSliderMouseTouch, { cache: null, options: { containment: null }, _create: function(){ setTimeout($.proxy(this._initElement, this), 10); }, _initElement: function(){ this._mouseInit(); this._cache(); }, _setOption: function(key, value){ if (key == "containment"){ if (value === null || $(value).length == 0){ this.options.containment = null }else{ this.options.containment = $(value); } } }, /* * UI mouse widget */ _mouseStart: function(event){ this._cache(); this.cache.click = { left: event.pageX, top: event.pageY }; this.cache.initialOffset = this.element.offset(); this._triggerMouseEvent("mousestart"); return true; }, _mouseDrag: function(event){ var position = event.pageX - this.cache.click.left; position = this._constraintPosition(position + this.cache.initialOffset.left); this._applyPosition(position); this._triggerMouseEvent("drag"); return false; }, _mouseStop: function(event){ this._triggerMouseEvent("stop"); }, /* * To be overriden */ _constraintPosition: function(position){ if (this.element.parent().length !== 0 && this.cache.parent.offset != null){ position = Math.min(position, this.cache.parent.offset.left + this.cache.parent.width - this.cache.width.outer); position = Math.max(position, this.cache.parent.offset.left); } return position; }, _applyPosition: function(position){ var offset = { top: this.cache.offset.top, left: position } this.element.offset({left:position}); this.cache.offset = offset; }, /* * Private utils */ _cacheIfNecessary: function(){ if (this.cache === null){ this._cache(); } }, _cache: function(){ this.cache = {}; this._cacheMargins(); this._cacheParent(); this._cacheDimensions(); this.cache.offset = this.element.offset(); }, _cacheMargins: function(){ this.cache.margin = { left: this._parsePixels(this.element, "marginLeft"), right: this._parsePixels(this.element, "marginRight"), top: this._parsePixels(this.element, "marginTop"), bottom: this._parsePixels(this.element, "marginBottom") }; }, _cacheParent: function(){ if (this.options.parent !== null){ var container = this.element.parent(); this.cache.parent = { offset: container.offset(), width: container.width() } }else{ this.cache.parent = null; } }, _cacheDimensions: function(){ this.cache.width = { outer: this.element.outerWidth(), inner: this.element.width() } }, _parsePixels: function(element, string){ return parseInt(element.css(string), 10) || 0; }, _triggerMouseEvent: function(event){ var data = this._prepareEventData(); this.element.trigger(event, data); }, _prepareEventData: function(){ return { element: this.element, offset: this.cache.offset || null }; } }); })(jQuery);
gaearon/cdnjs
ajax/libs/jQRangeSlider/4.2.4/jQRangeSliderDraggable.js
JavaScript
mit
3,375
module.exports={title:"TensorFlow",slug:"tensorflow",svg:'<svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>TensorFlow icon</title><path d="M19.6 12l.1 4.7-3.1-1.8v6.7L12.5 24V0l10.2 5.9v5.3l-6.1-3.6v2.7zM1.3 5.9L11.5 0v24l-4.1-2.4v-14l-6.1 3.6z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://www.tensorflow.org/extras/tensorflow_brand_guidelines.pdf",hex:"FF6F00"};
cdnjs/cdnjs
ajax/libs/simple-icons/4.4.0/tensorflow.min.js
JavaScript
mit
432
/*! * Backbone.Notifier 3D Module v0.0.3 * Copyright 2012, Eyal Weiss * Backbone.Notifier 3D Module be freely distributed under the MIT license. */ (function (Notifier, $) { Notifier.regModule({ name: '3d', enabled: false, extend: { defaults: { '3d': true } }, events: { 'beforeAnimateInMsgEl': function (settings, msgEl, msgInner, msgView) { if (settings['3d']) { var module = this.module, fn = msgView.handle3d = function () { module.mouseMoveHandler.apply(module, arguments) }; $('body').bind('mousemove', {msgInner: msgInner}, fn); } }, 'beforeHideMsgEl': function (settings, msgEl, msgInner, msgView) { if (settings['3d']) { $('body').unbind('mousemove', msgView.handle3d); } } }, mouseMoveHandler: function (e) { var winH = $(window).innerHeight(), winW = $(window).innerWidth(), pX = (.5 - (e.clientX / winW)) * 2, degX = -(pX * 10).toFixed(2), pY = (.5 - (e.clientY / winH)) * 2, degY = (pY * 20).toFixed(2), sX = (pX * 10), sY = (pY * 10), sD = Math.abs(sX) + Math.abs(sY), sA = .8 - ((Math.abs(pX) + Math.abs(pY)) / 2) * .4, shadow = sX.toFixed(2) + 'px ' + sY.toFixed(2) + 'px' + ' ' + sD.toFixed(2) + 'px rgba(0,0,0,' + sA.toFixed(2) + ')', css = {}; css[this.transformAttr] = 'perspective(800px) rotateX(' + degY + 'deg) rotateY(' + degX + 'deg)'; css[this.shadowAttr] = shadow; e.data.msgInner.css(css); }, getVendorPrefix: function (prefix) { var prefixes = $.map(['', '-webkit-', '-moz-', '-ms-', '-o-'], function (attr) { return attr + prefix; }); var tmp = document.createElement("div"), res = prefix; for (var i = 0; i < prefixes.length; ++i) { if (typeof tmp.style[prefixes[i]] !== 'undefined') { res = prefixes[i]; break; } } return res; }, register: function () { this.transformAttr = this.getVendorPrefix('transform'); this.shadowAttr = this.getVendorPrefix('box-shadow'); //console.log(this.name + ' module was registered'); }, enable: function () { //console.log(this.name + ' module was activated'); }, disable: function () { //console.log(this.name + ' module was stopped'); } }); })(Backbone.Notifier, jQuery);
gregorypratt/jsdelivr
files/backbone.notifier/0.2.5/js/modules/3d.js
JavaScript
mit
2,876
// Copyright 2013 the V8 project authors. All rights reserved. // Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. description( "This tests that passing an inconsistent compareFn to sort() doesn't cause a crash." ); for (var attempt = 0; attempt < 100; ++attempt) { var arr = []; for (var i = 0; i < 64; ++i) arr[i] = i; arr.sort(function() { return 0.5 - Math.random(); }); } // Sorting objects that change each time sort() looks at them is the same as using a random compareFn. function RandomObject() { this.toString = function() { return (Math.random() * 100).toString(); } } for (var attempt = 0; attempt < 100; ++attempt) { var arr = []; for (var i = 0; i < 64; ++i) arr[i] = new RandomObject; arr.sort(); }
zero-ui/miniblink49
v8_7_5/test/webkit/sort-randomly.js
JavaScript
gpl-3.0
2,084
keyboard:function(){var f=this;d(a).keydown(function(h){if(typeof f.options.callforwardFunction==="function"){f.animationCallForward(true)}var g=h.keyCode||h.which;if(h.target.type!=="textarea"&&h.target.type!=="textbox"){if(g===f.options.leftKey){f.setCurrent("right");f.clickable=false}if(g===f.options.rightKey){f.setCurrent("left");f.clickable=false}d.each(f.options.panelKeys,function(i,j){if(g===j){f.setCurrent(i-1);f.clickable=false}})}if(f.options.autoSlide){f.checkAutoSlideStop();}if(typeof f.options.callbackFunction==="function"){f.animationCallback(true)}})},
wynandkok/andanonymous
workspace/modules/liquid-slider-keyboard.js
JavaScript
mit
573
'use strict'; !function($) { /** * DropdownMenu module. * @module foundation.dropdown-menu * @requires foundation.util.keyboard * @requires foundation.util.box * @requires foundation.util.nest */ class DropdownMenu { /** * Creates a new instance of DropdownMenu. * @class * @fires DropdownMenu#init * @param {jQuery} element - jQuery object to make into a dropdown menu. * @param {Object} options - Overrides to the default plugin settings. */ constructor(element, options) { this.$element = element; this.options = $.extend({}, DropdownMenu.defaults, this.$element.data(), options); Foundation.Nest.Feather(this.$element, 'dropdown'); this._init(); Foundation.registerPlugin(this, 'DropdownMenu'); Foundation.Keyboard.register('DropdownMenu', { 'ENTER': 'open', 'SPACE': 'open', 'ARROW_RIGHT': 'next', 'ARROW_UP': 'up', 'ARROW_DOWN': 'down', 'ARROW_LEFT': 'previous', 'ESCAPE': 'close' }); } /** * Initializes the plugin, and calls _prepareMenu * @private * @function */ _init() { var subs = this.$element.find('li.is-dropdown-submenu-parent'); this.$element.children('.is-dropdown-submenu-parent').children('.is-dropdown-submenu').addClass('first-sub'); this.$menuItems = this.$element.find('[role="menuitem"]'); this.$tabs = this.$element.children('[role="menuitem"]'); this.$tabs.find('ul.is-dropdown-submenu').addClass(this.options.verticalClass); if (this.$element.hasClass(this.options.rightClass) || this.options.alignment === 'right' || Foundation.rtl() || this.$element.parents('.top-bar-right').is('*')) { this.options.alignment = 'right'; subs.addClass('opens-left'); } else { subs.addClass('opens-right'); } this.changed = false; this._events(); }; /** * Adds event listeners to elements within the menu * @private * @function */ _events() { var _this = this, hasTouch = 'ontouchstart' in window || (typeof window.ontouchstart !== 'undefined'), parClass = 'is-dropdown-submenu-parent'; // used for onClick and in the keyboard handlers var handleClickFn = function(e) { var $elem = $(e.target).parentsUntil('ul', `.${parClass}`), hasSub = $elem.hasClass(parClass), hasClicked = $elem.attr('data-is-click') === 'true', $sub = $elem.children('.is-dropdown-submenu'); if (hasSub) { if (hasClicked) { if (!_this.options.closeOnClick || (!_this.options.clickOpen && !hasTouch) || (_this.options.forceFollow && hasTouch)) { return; } else { e.stopImmediatePropagation(); e.preventDefault(); _this._hide($elem); } } else { e.preventDefault(); e.stopImmediatePropagation(); _this._show($elem.children('.is-dropdown-submenu')); $elem.add($elem.parentsUntil(_this.$element, `.${parClass}`)).attr('data-is-click', true); } } else { return; } }; if (this.options.clickOpen || hasTouch) { this.$menuItems.on('click.zf.dropdownmenu touchstart.zf.dropdownmenu', handleClickFn); } if (!this.options.disableHover) { this.$menuItems.on('mouseenter.zf.dropdownmenu', function(e) { var $elem = $(this), hasSub = $elem.hasClass(parClass); if (hasSub) { clearTimeout(_this.delay); _this.delay = setTimeout(function() { _this._show($elem.children('.is-dropdown-submenu')); }, _this.options.hoverDelay); } }).on('mouseleave.zf.dropdownmenu', function(e) { var $elem = $(this), hasSub = $elem.hasClass(parClass); if (hasSub && _this.options.autoclose) { if ($elem.attr('data-is-click') === 'true' && _this.options.clickOpen) { return false; } clearTimeout(_this.delay); _this.delay = setTimeout(function() { _this._hide($elem); }, _this.options.closingTime); } }); } this.$menuItems.on('keydown.zf.dropdownmenu', function(e) { var $element = $(e.target).parentsUntil('ul', '[role="menuitem"]'), isTab = _this.$tabs.index($element) > -1, $elements = isTab ? _this.$tabs : $element.siblings('li').add($element), $prevElement, $nextElement; $elements.each(function(i) { if ($(this).is($element)) { $prevElement = $elements.eq(i-1); $nextElement = $elements.eq(i+1); return; } }); var nextSibling = function() { if (!$element.is(':last-child')) { $nextElement.children('a:first').focus(); e.preventDefault(); } }, prevSibling = function() { $prevElement.children('a:first').focus(); e.preventDefault(); }, openSub = function() { var $sub = $element.children('ul.is-dropdown-submenu'); if ($sub.length) { _this._show($sub); $element.find('li > a:first').focus(); e.preventDefault(); } else { return; } }, closeSub = function() { //if ($element.is(':first-child')) { var close = $element.parent('ul').parent('li'); close.children('a:first').focus(); _this._hide(close); e.preventDefault(); //} }; var functions = { open: openSub, close: function() { _this._hide(_this.$element); _this.$menuItems.find('a:first').focus(); // focus to first element e.preventDefault(); }, handled: function() { e.stopImmediatePropagation(); } }; if (isTab) { if (_this.$element.hasClass(_this.options.verticalClass)) { // vertical menu if (_this.options.alignment === 'left') { // left aligned $.extend(functions, { down: nextSibling, up: prevSibling, next: openSub, previous: closeSub }); } else { // right aligned $.extend(functions, { down: nextSibling, up: prevSibling, next: closeSub, previous: openSub }); } } else { // horizontal menu $.extend(functions, { next: nextSibling, previous: prevSibling, down: openSub, up: closeSub }); } } else { // not tabs -> one sub if (_this.options.alignment === 'left') { // left aligned $.extend(functions, { next: openSub, previous: closeSub, down: nextSibling, up: prevSibling }); } else { // right aligned $.extend(functions, { next: closeSub, previous: openSub, down: nextSibling, up: prevSibling }); } } Foundation.Keyboard.handleKey(e, 'DropdownMenu', functions); }); } /** * Adds an event handler to the body to close any dropdowns on a click. * @function * @private */ _addBodyHandler() { var $body = $(document.body), _this = this; $body.off('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu') .on('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu', function(e) { var $link = _this.$element.find(e.target); if ($link.length) { return; } _this._hide(); $body.off('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu'); }); } /** * Opens a dropdown pane, and checks for collisions first. * @param {jQuery} $sub - ul element that is a submenu to show * @function * @private * @fires DropdownMenu#show */ _show($sub) { var idx = this.$tabs.index(this.$tabs.filter(function(i, el) { return $(el).find($sub).length > 0; })); var $sibs = $sub.parent('li.is-dropdown-submenu-parent').siblings('li.is-dropdown-submenu-parent'); this._hide($sibs, idx); $sub.css('visibility', 'hidden').addClass('js-dropdown-active').attr({'aria-hidden': false}) .parent('li.is-dropdown-submenu-parent').addClass('is-active') .attr({'aria-expanded': true}); var clear = Foundation.Box.ImNotTouchingYou($sub, null, true); if (!clear) { var oldClass = this.options.alignment === 'left' ? '-right' : '-left', $parentLi = $sub.parent('.is-dropdown-submenu-parent'); $parentLi.removeClass(`opens${oldClass}`).addClass(`opens-${this.options.alignment}`); clear = Foundation.Box.ImNotTouchingYou($sub, null, true); if (!clear) { $parentLi.removeClass(`opens-${this.options.alignment}`).addClass('opens-inner'); } this.changed = true; } $sub.css('visibility', ''); if (this.options.closeOnClick) { this._addBodyHandler(); } /** * Fires when the new dropdown pane is visible. * @event DropdownMenu#show */ this.$element.trigger('show.zf.dropdownmenu', [$sub]); } /** * Hides a single, currently open dropdown pane, if passed a parameter, otherwise, hides everything. * @function * @param {jQuery} $elem - element with a submenu to hide * @param {Number} idx - index of the $tabs collection to hide * @private */ _hide($elem, idx) { var $toClose; if ($elem && $elem.length) { $toClose = $elem; } else if (idx !== undefined) { $toClose = this.$tabs.not(function(i, el) { return i === idx; }); } else { $toClose = this.$element; } var somethingToClose = $toClose.hasClass('is-active') || $toClose.find('.is-active').length > 0; if (somethingToClose) { $toClose.find('li.is-active').add($toClose).attr({ 'aria-expanded': false, 'data-is-click': false }).removeClass('is-active'); $toClose.find('ul.js-dropdown-active').attr({ 'aria-hidden': true }).removeClass('js-dropdown-active'); if (this.changed || $toClose.find('opens-inner').length) { var oldClass = this.options.alignment === 'left' ? 'right' : 'left'; $toClose.find('li.is-dropdown-submenu-parent').add($toClose) .removeClass(`opens-inner opens-${this.options.alignment}`) .addClass(`opens-${oldClass}`); this.changed = false; } /** * Fires when the open menus are closed. * @event DropdownMenu#hide */ this.$element.trigger('hide.zf.dropdownmenu', [$toClose]); } } /** * Destroys the plugin. * @function */ destroy() { this.$menuItems.off('.zf.dropdownmenu').removeAttr('data-is-click') .removeClass('is-right-arrow is-left-arrow is-down-arrow opens-right opens-left opens-inner'); $(document.body).off('.zf.dropdownmenu'); Foundation.Nest.Burn(this.$element, 'dropdown'); Foundation.unregisterPlugin(this); } } /** * Default settings for plugin */ DropdownMenu.defaults = { /** * Disallows hover events from opening submenus * @option * @example false */ disableHover: false, /** * Allow a submenu to automatically close on a mouseleave event, if not clicked open. * @option * @example true */ autoclose: true, /** * Amount of time to delay opening a submenu on hover event. * @option * @example 50 */ hoverDelay: 50, /** * Allow a submenu to open/remain open on parent click event. Allows cursor to move away from menu. * @option * @example true */ clickOpen: false, /** * Amount of time to delay closing a submenu on a mouseleave event. * @option * @example 500 */ closingTime: 500, /** * Position of the menu relative to what direction the submenus should open. Handled by JS. * @option * @example 'left' */ alignment: 'left', /** * Allow clicks on the body to close any open submenus. * @option * @example true */ closeOnClick: true, /** * Class applied to vertical oriented menus, Foundation default is `vertical`. Update this if using your own class. * @option * @example 'vertical' */ verticalClass: 'vertical', /** * Class applied to right-side oriented menus, Foundation default is `align-right`. Update this if using your own class. * @option * @example 'align-right' */ rightClass: 'align-right', /** * Boolean to force overide the clicking of links to perform default action, on second touch event for mobile. * @option * @example false */ forceFollow: true }; // Window exports Foundation.plugin(DropdownMenu, 'DropdownMenu'); }(jQuery);
mj-wilson/Rachel-Marc-Wedding
wp-content/themes/RachelMarcWedding/assets/components/foundation-sites/js/foundation.dropdownMenu.js
JavaScript
gpl-2.0
12,679
/* YUI 3.16.0 (build 76f0e08) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('event-touch', function (Y, NAME) { /** Adds touch event facade normalization properties (touches, changedTouches, targetTouches etc.) to the DOM event facade. Adds touch events to the DOM events whitelist. @example YUI().use('event-touch', function (Y) { Y.one('#myDiv').on('touchstart', function(e) { ... }); }); @module event @submodule event-touch */ var SCALE = "scale", ROTATION = "rotation", IDENTIFIER = "identifier", win = Y.config.win, GESTURE_MAP = {}; /** * Adds touch event facade normalization properties to the DOM event facade * * @method _touch * @for DOMEventFacade * @private * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {CustomEvent} the custom event wrapper for this DOM event */ Y.DOMEventFacade.prototype._touch = function(e, currentTarget, wrapper) { var i,l, etCached, et,touchCache; if (e.touches) { /** * Array of individual touch events for touch points that are still in * contact with the touch surface. * * @property touches * @type {DOMEventFacade[]} */ this.touches = []; touchCache = {}; for (i = 0, l = e.touches.length; i < l; ++i) { et = e.touches[i]; touchCache[Y.stamp(et)] = this.touches[i] = new Y.DOMEventFacade(et, currentTarget, wrapper); } } if (e.targetTouches) { /** * Array of individual touch events still in contact with the touch * surface and whose `touchstart` event occurred inside the same taregt * element as the current target element. * * @property targetTouches * @type {DOMEventFacade[]} */ this.targetTouches = []; for (i = 0, l = e.targetTouches.length; i < l; ++i) { et = e.targetTouches[i]; etCached = touchCache && touchCache[Y.stamp(et, true)]; this.targetTouches[i] = etCached || new Y.DOMEventFacade(et, currentTarget, wrapper); } } if (e.changedTouches) { /** An array of event-specific touch events. For `touchstart`, the touch points that became active with the current event. For `touchmove`, the touch points that have changed since the last event. For `touchend`, the touch points that have been removed from the touch surface. @property changedTouches @type {DOMEventFacade[]} **/ this.changedTouches = []; for (i = 0, l = e.changedTouches.length; i < l; ++i) { et = e.changedTouches[i]; etCached = touchCache && touchCache[Y.stamp(et, true)]; this.changedTouches[i] = etCached || new Y.DOMEventFacade(et, currentTarget, wrapper); } } if (SCALE in e) { this[SCALE] = e[SCALE]; } if (ROTATION in e) { this[ROTATION] = e[ROTATION]; } if (IDENTIFIER in e) { this[IDENTIFIER] = e[IDENTIFIER]; } }; //Adding MSPointer events to whitelisted DOM Events. MSPointer event payloads //have the same properties as mouse events. if (Y.Node.DOM_EVENTS) { Y.mix(Y.Node.DOM_EVENTS, { touchstart:1, touchmove:1, touchend:1, touchcancel:1, gesturestart:1, gesturechange:1, gestureend:1, MSPointerDown:1, MSPointerUp:1, MSPointerMove:1, MSPointerCancel:1, pointerdown:1, pointerup:1, pointermove:1, pointercancel:1 }); } //Add properties to Y.EVENT.GESTURE_MAP based on feature detection. if ((win && ("ontouchstart" in win)) && !(Y.UA.chrome && Y.UA.chrome < 6)) { GESTURE_MAP.start = ["touchstart", "mousedown"]; GESTURE_MAP.end = ["touchend", "mouseup"]; GESTURE_MAP.move = ["touchmove", "mousemove"]; GESTURE_MAP.cancel = ["touchcancel", "mousecancel"]; } else if (win && win.PointerEvent) { GESTURE_MAP.start = "pointerdown"; GESTURE_MAP.end = "pointerup"; GESTURE_MAP.move = "pointermove"; GESTURE_MAP.cancel = "pointercancel"; } else if (win && ("msPointerEnabled" in win.navigator)) { GESTURE_MAP.start = "MSPointerDown"; GESTURE_MAP.end = "MSPointerUp"; GESTURE_MAP.move = "MSPointerMove"; GESTURE_MAP.cancel = "MSPointerCancel"; } else { GESTURE_MAP.start = "mousedown"; GESTURE_MAP.end = "mouseup"; GESTURE_MAP.move = "mousemove"; GESTURE_MAP.cancel = "mousecancel"; } /** * A object literal with keys "start", "end", and "move". The value for each key is a * string representing the event for that environment. For touch environments, the respective * values are "touchstart", "touchend" and "touchmove". Mouse and MSPointer environments are also * supported via feature detection. * * @property _GESTURE_MAP * @type Object * @static */ Y.Event._GESTURE_MAP = GESTURE_MAP; }, '3.16.0', {"requires": ["node-base"]});
dandv/jsdelivr
files/yui/3.16.0/event-touch/event-touch.js
JavaScript
mit
5,190
/* * DOM event listener abstraction layer * @module event * @submodule event-base */ (function() { // Unlike most of the library, this code has to be executed as soon as it is // introduced into the page -- and it should only be executed one time // regardless of the number of instances that use it. var stateChangeListener, GLOBAL_ENV = YUI.Env, config = YUI.config, doc = config.doc, docElement = doc.documentElement, doScrollCap = docElement.doScroll, add = YUI.Env.add, remove = YUI.Env.remove, targetEvent = (doScrollCap) ? 'onreadystatechange' : 'DOMContentLoaded', pollInterval = config.pollInterval || 40, _ready = function(e) { GLOBAL_ENV._ready(); }; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { if (!GLOBAL_ENV.DOMReady) { GLOBAL_ENV.DOMReady = true; remove(doc, targetEvent, _ready); // remove DOMContentLoaded listener } }; /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */ // Internet Explorer: use the doScroll() method on the root element. This isolates what // appears to be a safe moment to manipulate the DOM prior to when the document's readyState // suggests it is safe to do so. if (doScrollCap) { if (self !== self.top) { stateChangeListener = function() { if (doc.readyState == 'complete') { remove(doc, targetEvent, stateChangeListener); // remove onreadystatechange listener _ready(); } }; add(doc, targetEvent, stateChangeListener); // add onreadystatechange listener } else { GLOBAL_ENV._dri = setInterval(function() { try { docElement.doScroll('left'); clearInterval(GLOBAL_ENV._dri); GLOBAL_ENV._dri = null; _ready(); } catch (domNotReady) { } }, pollInterval); } } else { // FireFox, Opera, Safari 3+ provide an event for this moment. add(doc, targetEvent, _ready); // add DOMContentLoaded listener } } })(); YUI.add('event-base', function(Y) { (function() { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ var GLOBAL_ENV = YUI.Env, yready = function() { Y.fire('domready'); }; /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true }); if (GLOBAL_ENV.DOMReady) { // console.log('DOMReady already fired', 'info', 'event'); yready(); } else { // console.log('setting up before listener', 'info', 'event'); // console.log('env: ' + YUI.Env.windowLoaded, 'info', 'event'); Y.before(yready, GLOBAL_ENV, "_ready"); } })(); (function() { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ /* * @TODO constants? LEFTBUTTON, MIDDLEBUTTON, RIGHTBUTTON, keys */ /* var whitelist = { altKey : 1, // "button" : 1, // we supply // "bubbles" : 1, // needed? // "cancelable" : 1, // needed? // "charCode" : 1, // we supply cancelBubble : 1, // "currentTarget" : 1, // we supply ctrlKey : 1, clientX : 1, // needed? clientY : 1, // needed? detail : 1, // not fully implemented // "fromElement" : 1, keyCode : 1, // "height" : 1, // needed? // "initEvent" : 1, // need the init events? // "initMouseEvent" : 1, // "initUIEvent" : 1, // "layerX" : 1, // needed? // "layerY" : 1, // needed? metaKey : 1, // "modifiers" : 1, // needed? // "offsetX" : 1, // needed? // "offsetY" : 1, // needed? // "preventDefault" : 1, // we supply // "reason" : 1, // IE proprietary // "relatedTarget" : 1, // "returnValue" : 1, // needed? shiftKey : 1, // "srcUrn" : 1, // IE proprietary // "srcElement" : 1, // "srcFilter" : 1, IE proprietary // "stopPropagation" : 1, // we supply // "target" : 1, // "timeStamp" : 1, // needed? // "toElement" : 1, type : 1, // "view" : 1, // "which" : 1, // we supply // "width" : 1, // needed? x : 1, y : 1 }, */ var ua = Y.UA, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }; // provide a single event with browser abstractions resolved // // include all properties for both browers? // include only DOM2 spec properties? // provide browser-specific facade? Y.DOMEventFacade = function(ev, currentTarget, wrapper) { wrapper = wrapper || {}; var e = ev, ot = currentTarget, d = Y.config.doc, b = d.body, x = e.pageX, y = e.pageY, c, t, overrides = wrapper.overrides || {}; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = overrides.type || e.type; this.clientX = e.clientX; this.clientY = e.clientY; ////////////////////////////////////////////////////// if (!x && 0 !== x) { x = e.clientX || 0; y = e.clientY || 0; if (ua.ie) { x += Math.max(d.documentElement.scrollLeft, b.scrollLeft); y += Math.max(d.documentElement.scrollTop, b.scrollTop); } } this._yuifacade = true; /** * The native event * @property _event */ this._event = e; /** * The X location of the event on the page (including scroll) * @property pageX * @type int */ this.pageX = x; /** * The Y location of the event on the page (including scroll) * @property pageY * @type int */ this.pageY = y; ////////////////////////////////////////////////////// c = e.keyCode || e.charCode || 0; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type int */ this.keyCode = c; /** * The charCode for key events. Same as keyCode * @property charCode * @type int */ this.charCode = c; ////////////////////////////////////////////////////// /** * The button that was pushed. * @property button * @type int */ this.button = e.which || e.button; /** * The button that was pushed. Same as button. * @property which * @type int */ this.which = this.button; ////////////////////////////////////////////////////// /** * Node reference for the targeted element * @propery target * @type Node */ this.target = resolve(e.target || e.srcElement); /** * Node reference for the element that the listener was attached to. * @propery currentTarget * @type Node */ this.currentTarget = resolve(ot); t = e.relatedTarget; if (!t) { if (e.type == "mouseout") { t = e.toElement; } else if (e.type == "mouseover") { t = e.fromElement; } } /** * Node reference to the relatedTarget * @propery relatedTarget * @type Node */ this.relatedTarget = resolve(t); /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type int */ if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } ////////////////////////////////////////////////////// // methods /** * Stops the propagation to the next bubble target * @method stopPropagation */ this.stopPropagation = function() { if (e.stopPropagation) { e.stopPropagation(); } else { e.cancelBubble = true; } wrapper.stopped = 1; }; /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ this.stopImmediatePropagation = function() { if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } wrapper.stopped = 2; }; /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ this.preventDefault = function(returnValue) { if (e.preventDefault) { e.preventDefault(); } e.returnValue = returnValue || false; wrapper.prevented = 1; }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ this.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; }; })(); (function() { /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var _eventenv = Y.Env.evt, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(window, "load", onLoad); }, onUnload = function() { Y.Event._unload(); remove(window, "unload", onUnload); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !o.alert); } catch(ex) { Y.log("collection check failure", "warn", "event"); return false; } }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Y.bind(Event._poll, Event), Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; // Y.log('onAvailable registered for: ' + id); for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Y.bind(Event._poll, Event), 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, p_obj, p_override, compat) { return this.onAvailable(id, fn, p_obj, p_override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == Y.config.win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, config) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || Y.config.win, facade = config && config.facade, capture = config && config.capture, overrides = config && config.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; // trimmedArgs.pop(); } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); Y.log(type + " attach call failed, invalid callback", "error", "event"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args, config)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = Y.DOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, config); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { // Y.log(el + ' not found'); ret = this.onAvailable(el, function() { // Y.log('lazy attach: ' + args); ret.handle = Event._attach(args, config); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { Y.log("unable to attach event " + type, "warn", "event"); return false; } if (Y.Node && el instanceof Y.Node) { el = Y.Node.getDOMNode(el); } cewrapper = this._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == Y.config.win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = Y.DOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return this.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || window.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { // Y.log('Load Complete', 'info', 'event'); _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (this.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. this.startInterval(); return; } this.locked = true; // Y.log.debug("poll"); // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // Y.log('avail: ' + el); executeItem(el, item); _avail[i] = null; } else { // Y.log('NOT avail: ' + el); notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here this.startInterval(); } else { clearInterval(this._interval); this._interval = null; } this.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = this.getListeners(oEl, type), i, len, props, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); i = 0; len = children.length; for (; i < len; ++i) { child = this.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { i = 0; len = lis.length; for (; i < len; ++i) { props = lis[i]; props.detachAll(); remove(props.el, props.type, props.fn, props.capture); delete _wrappers[props.key]; delete _el_events[props.domkey][props.key]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {Y.Custom.Event} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null; if (!evts) { return null; } if (key) { if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { v.detachAll(); remove(v.el, v.type, v.fn, v.capture); delete _wrappers[k]; delete _el_events[v.domkey][k]; }); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (Y.config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(window, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll, Event, true); } Y.on("unload", onUnload); Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); })(); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string|HTMLElement|collection} the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : []; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available) * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string|HTMLElement|collection} the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : []; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '@VERSION@' ,{requires:['event-custom-base']}); YUI.add('event-delegate', function(Y) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var Event = Y.Event, Lang = Y.Lang, delegates = {}, specialTypes = { mouseenter: "mouseover", mouseleave: "mouseout" }, resolveTextNode = function(n) { try { if (n && 3 == n.nodeType) { return n.parentNode; } } catch(e) { } return n; }, delegateHandler = function(delegateKey, e, el) { var target = resolveTextNode((e.target || e.srcElement)), tests = delegates[delegateKey], spec, ename, matched, fn, ev; var getMatch = function(el, selector, container) { var returnVal; if (!el || el === container) { returnVal = false; } else { returnVal = Y.Selector.test(el, selector, container) ? el: getMatch(el.parentNode, selector, container); } return returnVal; }; for (spec in tests) { if (tests.hasOwnProperty(spec)) { ename = tests[spec]; fn = tests.fn; matched = null; if (Y.Selector.test(target, spec, el)) { matched = target; } else if (Y.Selector.test(target, ((spec.replace(/,/gi, " *,")) + " *"), el)) { // The target is a descendant of an element matching // the selector, so crawl up to find the ancestor that // matches the selector matched = getMatch(target, spec, el); } if (matched) { if (!ev) { ev = new Y.DOMEventFacade(e, el); ev.container = ev.currentTarget; } ev.currentTarget = Y.one(matched); Y.publish(ename, { contextFn: function() { return ev.currentTarget; } }); if (fn) { fn(ev, ename); } else { Y.fire(ename, ev); } } } } }, attach = function (type, key, element) { var focusMethods = { focus: Event._attachFocus, blur: Event._attachBlur }, attachFn = focusMethods[type], args = [type, function (e) { delegateHandler(key, (e || window.event), element); }, element]; if (attachFn) { return attachFn(args, { capture: true, facade: false }); } else { return Event._attach(args, { facade: false }); } }, sanitize = Y.cached(function(str) { return str.replace(/[|,:]/g, '~'); }); /** * Sets up event delegation on a container element. The delegated event * will use a supplied selector to test if the target or one of the * descendants of the target match it. The supplied callback function * will only be executed if a match was encountered, and, in fact, * will be executed for each element that matches if you supply an * ambiguous selector. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the delegation specifcation. 'container' is * set to the element that the listener is bound to (this normally would * be the 'currentTarget'). * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param spec {string} a selector that must match the target of the * event. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Event.delegate = function (type, fn, el, spec) { if (!spec) { Y.log('delegate: no spec, nothing to do', 'warn', 'event'); return false; } var args = Y.Array(arguments, 0, true), element = el, // HTML element serving as the delegation container availHandle; if (Lang.isString(el)) { // Y.Selector.query returns an array of matches unless specified // to return just the first match. Since the primary use case for // event delegation is to use a single event handler on a container, // Y.delegate doesn't currently support being able to bind a // single listener to multiple containers. element = Y.Selector.query(el, null, true); if (!element) { // Not found, check using onAvailable availHandle = Event.onAvailable(el, function() { availHandle.handle = Event.delegate.apply(Event, args); }, Event, true, false); return availHandle; } } element = Y.Node.getDOMNode(element); var guid = Y.stamp(element), // The Custom Event for the delegation spec ename = 'delegate:' + guid + type + sanitize(spec), // The key to the listener for the event type and container delegateKey = type + guid, delegate = delegates[delegateKey], domEventHandle, ceHandle, listeners; if (!delegate) { delegate = {}; if (specialTypes[type]) { if (!Event._fireMouseEnter) { Y.log("Delegating a " + type + " event requires the event-mouseenter submodule.", "error", "Event"); return false; } type = specialTypes[type]; delegate.fn = Event._fireMouseEnter; } // Create the DOM Event wrapper that will fire the Custom Event domEventHandle = attach(type, delegateKey, element); // Hook into the _delete method for the Custom Event wrapper of this // DOM Event in order to clean up the 'delegates' map and unsubscribe // the associated Custom Event listeners fired by this DOM event // listener if/when the user calls "purgeElement" OR removes all // listeners of the Custom Event. Y.after(function (sub) { if (domEventHandle.sub == sub) { // Delete this event from the map of known delegates delete delegates[delegateKey]; Y.log("DOM event listener associated with the " + ename + " Custom Event removed. Removing all " + ename + " listeners.", "info", "Event"); // Unsubscribe all listeners of the Custom Event fired // by this DOM event. Y.detachAll(ename); } }, domEventHandle.evt, "_delete"); delegate.handle = domEventHandle; delegates[delegateKey] = delegate; } listeners = delegate.listeners; delegate.listeners = listeners ? (listeners + 1) : 1; delegate[spec] = ename; args[0] = ename; // Remove element, delegation spec args.splice(2, 2); // Subscribe to the Custom Event for the delegation spec ceHandle = Y.on.apply(Y, args); // Hook into the detach method of the handle in order to clean up the // 'delegates' map and remove the associated DOM event handler // responsible for firing this Custom Event if all listener for this // event have been removed. Y.after(function () { delegate.listeners = (delegate.listeners - 1); if (delegate.listeners === 0) { Y.log("No more listeners for the " + ename + " Custom Event. Removing its associated DOM event listener.", "info", "Event"); delegate.handle.detach(); } }, ceHandle, "detach"); return ceHandle; }; Y.delegate = Event.delegate; }, '@VERSION@' ,{requires:['node-base']}); YUI.add('event-mousewheel', function(Y) { /** * Adds mousewheel event support * @module event * @submodule event-mousewheel */ var DOM_MOUSE_SCROLL = 'DOMMouseScroll', fixArgs = function(args) { var a = Y.Array(args, 0, true), target; if (Y.UA.gecko) { a[0] = DOM_MOUSE_SCROLL; target = Y.config.win; } else { target = Y.config.doc; } if (a.length < 3) { a[2] = target; } else { a.splice(2, 0, target); } return a; }; /** * Mousewheel event. This listener is automatically attached to the * correct target, so one should not be supplied. Mouse wheel * direction and velocity is stored in the 'mouseDelta' field. * @event mousewheel * @param type {string} 'mousewheel' * @param fn {function} the callback to execute * @param context optional context object * @param args 0..n additional arguments to provide to the listener. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.mousewheel = { on: function() { return Y.Event._attach(fixArgs(arguments)); }, detach: function() { return Y.Event.detach.apply(Y.Event, fixArgs(arguments)); } }; }, '@VERSION@' ,{requires:['node-base']}); YUI.add('event-mouseenter', function(Y) { /** * Adds support for mouseenter/mouseleave events * @module event * @submodule event-mouseenter */ var Event = Y.Event, Lang = Y.Lang, plugins = Y.Env.evt.plugins, listeners = {}, eventConfig = { on: function(type, fn, el) { var args = Y.Array(arguments, 0, true), element = el, availHandle; if (Lang.isString(el)) { // Need to use Y.all because if el is a string it could be a // selector that returns a NodeList element = Y.all(el); if (element.size() === 0) { // Not found, check using onAvailable availHandle = Event.onAvailable(el, function() { availHandle.handle = Y.on.apply(Y, args); }, Event, true, false); return availHandle; } } var sDOMEvent = (type === "mouseenter") ? "mouseover" : "mouseout", // The name of the custom event sEventName = type + ":" + Y.stamp(element) + sDOMEvent, listener = listeners[sEventName], domEventHandle, ceHandle, nListeners; // Bind an actual DOM event listener that will call the // the custom event if (!listener) { domEventHandle = Y.on(sDOMEvent, Y.rbind(Event._fireMouseEnter, Y, sEventName), element); // Hook into the _delete method for the Custom Event wrapper of this // DOM Event in order to clean up the 'listeners' map and unsubscribe // the associated Custom Event listeners fired by this DOM event // listener if/when the user calls "purgeElement" OR removes all // listeners of the Custom Event. Y.after(function (sub) { if (domEventHandle.sub == sub) { // Delete this event from the map of known mouseenter // and mouseleave listeners delete listeners[sEventName]; Y.log("DOM event listener associated with the " + sEventName + " Custom Event removed. Removing all " + sEventName + " listeners.", "info", "Event"); // Unsubscribe all listeners of the Custom Event fired // by this DOM event. Y.detachAll(sEventName); } }, domEventHandle.evt, "_delete"); listener = {}; listener.handle = domEventHandle; listeners[sEventName] = listener; } nListeners = listener.count; listener.count = nListeners ? (nListeners + 1) : 1; args[0] = sEventName; // Remove the element from the args args.splice(2, 1); // Subscribe to the custom event ceHandle = Y.on.apply(Y, args); // Hook into the detach method of the handle in order to clean up the // 'listeners' map and remove the associated DOM event handler // responsible for firing this Custom Event if all listener for this // event have been removed. Y.after(function () { listener.count = (listener.count - 1); if (listener.count === 0) { Y.log("No more listeners for the " + sEventName + " Custom Event. Removing its associated DOM event listener.", "info", "Event"); listener.handle.detach(); } }, ceHandle, "detach"); return ceHandle; } }; Event._fireMouseEnter = function (e, eventName) { var relatedTarget = e.relatedTarget, currentTarget = e.currentTarget; if (currentTarget !== relatedTarget && !currentTarget.contains(relatedTarget)) { Y.publish(eventName, { contextFn: function() { return currentTarget; } }); Y.fire(eventName, e); } }; /** * Sets up a "mouseenter" listener&#151;a listener that is called the first time * the user's mouse enters the specified element(s). * * @event mouseenter * @param type {string} "mouseenter" * @param fn {function} The method the event invokes. * @param el {string|node} The element(s) to assign the listener to. * @param spec {string} Optional. String representing a selector that must * match the target of the event in order for the listener to be called. * @return {EventHandle} the detach handle * @for YUI */ plugins.mouseenter = eventConfig; /** * Sets up a "mouseleave" listener&#151;a listener that is called the first time * the user's mouse leaves the specified element(s). * * @event mouseleave * @param type {string} "mouseleave" * @param fn {function} The method the event invokes. * @param el {string|node} The element(s) to assign the listener to. * @param spec {string} Optional. String representing a selector that must * match the target of the event in order for the listener to be called. * @return {EventHandle} the detach handle * @for YUI */ plugins.mouseleave = eventConfig; }, '@VERSION@' ,{requires:['node-base']}); YUI.add('event-key', function(Y) { /** * Functionality to listen for one or more specific key combinations. * @module event * @submodule event-key */ /** * Add a key listener. The listener will only be notified if the * keystroke detected meets the supplied specification. The * spec consists of the key event type, followed by a colon, * followed by zero or more comma separated key codes, followed * by zero or more modifiers delimited by a plus sign. Ex: * press:12,65+shift+ctrl * @event key * @for YUI * @param type {string} 'key' * @param fn {function} the function to execute * @param id {string|HTMLElement|collection} the element(s) to bind * @param spec {string} the keyCode and modifier specification * @param o optional context object * @param args 0..n additional arguments to provide to the listener. * @return {Event.Handle} the detach handle */ Y.Env.evt.plugins.key = { on: function(type, fn, id, spec, o) { var a = Y.Array(arguments, 0, true), parsed, etype, criteria, ename; parsed = spec && spec.split(':'); if (!spec || spec.indexOf(':') == -1 || !parsed[1]) { Y.log('Illegal key spec, creating a regular keypress listener instead.', 'info', 'event'); a[0] = 'key' + ((parsed && parsed[0]) || 'press'); return Y.on.apply(Y, a); } // key event type: 'down', 'up', or 'press' etype = parsed[0]; // list of key codes optionally followed by modifiers criteria = (parsed[1]) ? parsed[1].split(/,|\+/) : null; // the name of the custom event that will be created for the spec ename = (Y.Lang.isString(id) ? id : Y.stamp(id)) + spec; ename = ename.replace(/,/g, '_'); if (!Y.getEvent(ename)) { // subscribe spec validator to the DOM event Y.on(type + etype, function(e) { // Y.log('keylistener: ' + e.keyCode); var passed = false, failed = false, i, crit, critInt; for (i=0; i<criteria.length; i=i+1) { crit = criteria[i]; critInt = parseInt(crit, 10); // pass this section if any supplied keyCode // is found if (Y.Lang.isNumber(critInt)) { if (e.charCode === critInt) { // Y.log('passed: ' + crit); passed = true; } else { failed = true; // Y.log('failed: ' + crit); } // only check modifier if no keyCode was specified // or the keyCode check was successful. pass only // if every modifier passes } else if (passed || !failed) { passed = (e[crit + 'Key']); failed = !passed; // Y.log(crit + ": " + passed); } } // fire spec custom event if spec if met if (passed) { Y.fire(ename, e); } }, id); } // subscribe supplied listener to custom event for spec validator // remove element and spec. a.splice(2, 2); a[0] = ename; return Y.on.apply(Y, a); } }; }, '@VERSION@' ,{requires:['node-base']}); YUI.add('event-focus', function(Y) { /** * Adds focus and blur event listener support. These events normally * do not bubble, so this adds support for that so these events * can be used in event delegation scenarios. * * @module event * @submodule event-focus */ (function() { var UA = Y.UA, Event = Y.Event, plugins = Y.Env.evt.plugins, ie = UA.ie, bUseMutation = (UA.opera || UA.webkit), eventNames = { focus: (ie ? 'focusin' : (bUseMutation ? 'DOMFocusIn' : 'focus')), blur: (ie ? 'focusout' : (bUseMutation ? 'DOMFocusOut' : 'blur')) }, // Only need to use capture phase for Gecko since it doesn't support // focusin, focusout, DOMFocusIn, or DOMFocusOut CAPTURE_CONFIG = { capture: (UA.gecko ? true : false) }, attach = function (args, config) { var a = Y.Array(args, 0, true), el = args[2]; config.overrides = config.overrides || {}; config.overrides.type = args[0]; if (el) { if (Y.DOM.isWindow(el)) { config.capture = false; } else { a[0] = eventNames[a[0]]; } } return Event._attach(a, config); }, eventAdapter = { on: function () { return attach(arguments, CAPTURE_CONFIG); } }; Event._attachFocus = attach; Event._attachBlur = attach; /** * Adds a DOM focus listener. Uses the focusin event in IE, * DOMFocusIn for Opera and Webkit, and the capture phase for Gecko so that * the event propagates in a way that enables event delegation. * * @for YUI * @event focus * @param type {string} 'focus' * @param fn {function} the callback function to execute * @param o {string|HTMLElement|collection} the element(s) to bind * @param context optional context object * @param args 0..n additional arguments to provide to the listener. * @return {EventHandle} the detach handle */ plugins.focus = eventAdapter; /** * Adds a DOM blur listener. Uses the focusout event in IE, * DOMFocusOut for Opera and Webkit, and the capture phase for Gecko so that * the event propagates in a way that enables event delegation. * * @for YUI * @event blur * @param type {string} 'blur' * @param fn {function} the callback function to execute * @param o {string|HTMLElement|collection} the element(s) to bind * @param context optional context object * @param args 0..n additional arguments to provide to the listener. * @return {EventHandle} the detach handle */ plugins.blur = eventAdapter; })(); }, '@VERSION@' ,{requires:['node-base']}); YUI.add('event-resize', function(Y) { /** * Adds a window resize event that has its behavior normalized to fire at the * end of the resize rather than constantly during the resize. * @module event * @submodule event-resize */ (function() { var detachHandle, timerHandle, CE_NAME = 'window:resize', handler = function(e) { if (Y.UA.gecko) { Y.fire(CE_NAME, e); } else { if (timerHandle) { timerHandle.cancel(); } timerHandle = Y.later(Y.config.windowResizeDelay || 40, Y, function() { Y.fire(CE_NAME, e); }); } }; /** * Firefox fires the window resize event once when the resize action * finishes, other browsers fire the event periodically during the * resize. This code uses timeout logic to simulate the Firefox * behavior in other browsers. * @event windowresize * @for YUI */ Y.Env.evt.plugins.windowresize = { on: function(type, fn) { // check for single window listener and add if needed if (!detachHandle) { detachHandle = Y.Event._attach(['resize', handler]); } var a = Y.Array(arguments, 0, true); a[0] = CE_NAME; return Y.on.apply(Y, a); } }; })(); }, '@VERSION@' ,{requires:['node-base']}); YUI.add('event', function(Y){}, '@VERSION@' ,{use:['event-base', 'event-delegate', 'event-mousewheel', 'event-mouseenter', 'event-key', 'event-focus', 'event-resize']});
pcarrier/cdnjs
ajax/libs/yui/3.1.0pr2/event/event-debug.js
JavaScript
mit
64,193
IntlMessageFormat.__addLocaleData({"locale":"gv","pluralRuleFunction":function (n,ord){var s=String(n).split("."),i=s[0],v0=!s[1],i10=i.slice(-1),i100=i.slice(-2);if(ord)return"other";return v0&&i10==1?"one":v0&&i10==2?"two":v0&&(i100==0||i100==20||i100==40||i100==60||i100==80)?"few":!v0?"many":"other"}});
Jorginho211/TFG
web/node_modules/intl-messageformat/dist/locale-data/gv.js
JavaScript
gpl-3.0
308
/* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ (function (root, $, _, Backbone) { "use strict"; /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ var window = root; var Backgrid = root.Backgrid = { VERSION: "0.1.3", Extension: {} }; // Copyright 2009, 2010 Kristopher Michael Kowal // https://github.com/kriskowal/es5-shim // ES5 15.5.4.20 // http://es5.github.com/#x15.5.4.20 var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { if (this === undefined || this === null) { throw new TypeError("can't convert " + this + " to object"); } return String(this) .replace(trimBeginRegexp, "") .replace(trimEndRegexp, ""); }; } function capitalize(s) { return String.fromCharCode(s.charCodeAt(0) - 32) + s.slice(1); } function lpad(str, length, padstr) { var paddingLen = length - (str + '').length; paddingLen = paddingLen < 0 ? 0 : paddingLen; var padding = ''; for (var i = 0; i < paddingLen; i++) { padding = padding + padstr; } return padding + str; } function requireOptions(options, requireOptionKeys) { for (var i = 0; i < requireOptionKeys.length; i++) { var key = requireOptionKeys[i]; if (_.isUndefined(options[key])) { throw new TypeError("'" + key + "' is required"); } } } function resolveNameToClass(name, suffix) { if (_.isString(name)) { var key = capitalize(name) + suffix; var klass = Backgrid[key] || Backgrid.Extension[key]; if (_.isUndefined(klass)) { throw new ReferenceError("Class '" + key + "' not found"); } return klass; } return name; } /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** Just a convenient class for interested parties to subclass. The default Cell classes don't require the formatter to be a subclass of Formatter as long as the fromRaw(rawData) and toRaw(formattedData) methods are defined. @abstract @class Backgrid.CellFormatter @constructor */ var CellFormatter = Backgrid.CellFormatter = function () {}; _.extend(CellFormatter.prototype, { /** Takes a raw value from a model and returns a formatted string for display. @member Backgrid.CellFormatter @param {*} rawData @return {string} */ fromRaw: function (rawData) { return rawData; }, /** Takes a formatted string, usually from user input, and returns a appropriately typed value for persistence in the model. If the user input is invalid or unable to be converted to a raw value suitable for persistence in the model, toRaw must return `undefined`. @member Backgrid.CellFormatter @param {string} formattedData @return {*|undefined} */ toRaw: function (formattedData) { return formattedData; } }); /** A floating point number formatter. Doesn't understand notation at the moment. @class Backgrid.NumberFormatter @extends Backgrid.CellFormatter @constructor @throws {RangeError} If decimals < 0 or > 20. */ var NumberFormatter = Backgrid.NumberFormatter = function (options) { options = options ? _.clone(options) : {}; _.extend(this, this.defaults, options); if (this.decimals < 0 || this.decimals > 20) { throw new RangeError("decimals must be between 0 and 20"); } }; NumberFormatter.prototype = new CellFormatter; _.extend(NumberFormatter.prototype, { /** @member Backgrid.NumberFormatter @cfg {Object} options @cfg {number} [options.decimals=2] Number of decimals to display. Must be an integer. @cfg {string} [options.decimalSeparator='.'] The separator to use when displaying decimals. @cfg {string} [options.orderSeparator=','] The separator to use to separator thousands. May be an empty string. */ defaults: { decimals: 2, decimalSeparator: '.', orderSeparator: ',' }, HUMANIZED_NUM_RE: /(\d)(?=(?:\d{3})+$)/g, /** Takes a floating point number and convert it to a formatted string where every thousand is separated by `orderSeparator`, with a `decimal` number of decimals separated by `decimalSeparator`. The number returned is rounded the usual way. @member Backgrid.NumberFormatter @param {number} number @return {string} */ fromRaw: function (number) { if (isNaN(number) || number === null) return ''; number = number.toFixed(~~this.decimals); var parts = number.split('.'); var integerPart = parts[0]; var decimalPart = parts[1] ? (this.decimalSeparator || '.') + parts[1] : ''; return integerPart.replace(this.HUMANIZED_NUM_RE, '$1' + this.orderSeparator) + decimalPart; }, /** Takes a string, possibly formatted with `orderSeparator` and/or `decimalSeparator`, and convert it back to a number. @member Backgrid.NumberFormatter @param {string} formattedData @return {number|undefined} Undefined if the string cannot be converted to a number. */ toRaw: function (formattedData) { var rawData = ''; var thousands = formattedData.trim().split(this.orderSeparator); for (var i = 0; i < thousands.length; i++) { rawData += thousands[i]; } var decimalParts = rawData.split(this.decimalSeparator); rawData = ''; for (var i = 0; i < decimalParts.length; i++) { rawData = rawData + decimalParts[i] + '.'; } if (rawData[rawData.length - 1] === '.') { rawData = rawData.slice(0, rawData.length - 1); } var result = (rawData * 1).toFixed(~~this.decimals) * 1; if (_.isNumber(result) && !_.isNaN(result)) return result; } }); /** Formatter to converts between various datetime string formats. This class only understands ISO-8601 formatted datetime strings. See Backgrid.Extension.MomentFormatter if you need a much more flexible datetime formatter. @class Backgrid.DatetimeFormatter @extends Backgrid.CellFormatter @constructor @throws {Error} If both `includeDate` and `includeTime` are false. */ var DatetimeFormatter = Backgrid.DatetimeFormatter = function (options) { options = options ? _.clone(options) : {}; _.extend(this, this.defaults, options); if (!this.includeDate && !this.includeTime) { throw new Error("Either includeDate or includeTime must be true"); } }; DatetimeFormatter.prototype = new CellFormatter; _.extend(DatetimeFormatter.prototype, { /** @member Backgrid.DatetimeFormatter @cfg {Object} options @cfg {boolean} [options.includeDate=true] Whether the values include the date part. @cfg {boolean} [options.includeTime=true] Whether the values include the time part. @cfg {boolean} [options.includeMilli=false] If `includeTime` is true, whether to include the millisecond part, if it exists. */ defaults: { includeDate: true, includeTime: true, includeMilli: false }, DATE_RE: /^([+\-]?\d{4})-(\d{2})-(\d{2})$/, TIME_RE: /^(\d{2}):(\d{2}):(\d{2})(\.(\d{3}))?$/, ISO_SPLITTER_RE: /T|Z| +/, _convert: function (data, validate) { if (_.isNull(data) || _.isUndefined(data)) return data; data = data.trim(); var parts = data.split(this.ISO_SPLITTER_RE) || []; var date = this.DATE_RE.test(parts[0]) ? parts[0] : ''; var time = date && parts[1] ? parts[1] : this.TIME_RE.test(parts[0]) ? parts[0] : ''; var YYYYMMDD = this.DATE_RE.exec(date) || []; var HHmmssSSS = this.TIME_RE.exec(time) || []; if (validate) { if (this.includeDate && _.isUndefined(YYYYMMDD[0])) return; if (this.includeTime && _.isUndefined(HHmmssSSS[0])) return; if (!this.includeDate && date) return; if (!this.includeTime && time) return; } var jsDate = new Date(Date.UTC(YYYYMMDD[1] * 1 || 0, YYYYMMDD[2] * 1 - 1 || 0, YYYYMMDD[3] * 1 || 0, HHmmssSSS[1] * 1 || null, HHmmssSSS[2] * 1 || null, HHmmssSSS[3] * 1 || null, HHmmssSSS[5] * 1 || null)); var result = ''; if (this.includeDate) { result = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0); } if (this.includeTime) { result = result + (this.includeDate ? 'T' : '') + lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0); if (this.includeMilli) { result = result + '.' + lpad(jsDate.getUTCMilliseconds(), 3, 0); } } if (this.includeDate && this.includeTime) { result += "Z"; } return result; }, /** Converts an ISO-8601 formatted datetime string to a datetime string, date string or a time string. The timezone is ignored if supplied. @member Backgrid.DatetimeFormatter @param {string} rawData @return {string|null|undefined} ISO-8601 string in UTC. Null and undefined values are returned as is. */ fromRaw: function (rawData) { return this._convert(rawData); }, /** Converts an ISO-8601 formatted datetime string to a datetime string, date string or a time string. The timezone is ignored if supplied. This method parses the input values exactly the same way as Backgrid.Extension.MomentFormatter#fromRaw(), in addition to doing some sanity checks. @member Backgrid.DatetimeFormatter @param {string} formattedData @return {string|undefined} ISO-8601 string in UTC. Undefined if a date is found `includeDate` is false, or a time is found if `includeTime` is false, or if `includeDate` is true and a date is not found, or if `includeTime` is true and a time is not found. */ toRaw: function (formattedData) { return this._convert(formattedData, true); } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** Generic cell editor base class. Only defines an initializer for a number of required parameters. @abstract @class Backgrid.CellEditor @extends Backbone.View */ var CellEditor = Backgrid.CellEditor = Backbone.View.extend({ /** Initializer. @param {Object} options @param {*} options.parent @param {Backgrid.CellFormatter} options.formatter @param {Backgrid.Column} options.column @param {Backbone.Model} options.model @throws {TypeError} If `formatter` is not a formatter instance, or when `model` or `column` are undefined. */ initialize: function (options) { requireOptions(options, ["formatter", "column", "model"]); this.parent = options.parent; this.formatter = options.formatter; this.column = options.column; if (!(this.column instanceof Column)) { this.column = new Column(this.column); } if (this.parent && _.isFunction(this.parent.on)) { this.listenTo(this.parent, "editing", this.postRender); } }, /** Post-rendering setup and initialization. Focuses the cell editor's `el` in this default implementation. **Should** be called by Cell classes after calling Backgrid.CellEditor#render. */ postRender: function () { this.$el.focus(); return this; } }); /** InputCellEditor the cell editor type used by most core cell types. This cell editor renders a text input box as its editor. The input will render a placeholder if the value is empty on supported browsers. @class Backgrid.InputCellEditor @extends Backgrid.CellEditor */ var InputCellEditor = Backgrid.InputCellEditor = CellEditor.extend({ /** @property */ tagName: "input", /** @property */ attributes: { type: "text" }, /** @property */ events: { "blur": "saveOrCancel", "keydown": "saveOrCancel" }, /** Initializer. Removes this `el` from the DOM when a `done` event is triggered. @param {Object} options @param {Backgrid.CellFormatter} options.formatter @param {Backgrid.Column} options.column @param {Backbone.Model} options.model @param {string} [options.placeholder] */ initialize: function (options) { CellEditor.prototype.initialize.apply(this, arguments); if (options.placeholder) { this.$el.attr("placeholder", options.placeholder); } this.listenTo(this, "done", this.remove); }, /** Renders a text input with the cell value formatted for display, if it exists. */ render: function () { this.$el.val(this.formatter.fromRaw(this.model.get(this.column.get("name")))); return this; }, /** If the key pressed is `enter` or `tab`, converts the value in the editor to a raw value for the model using the formatter. If the key pressed is `esc` the changes are undone. If the editor's value was changed and goes out of focus (`blur`), the event is intercepted, cancelled so the cell remains in focus pending for further action. Triggers a Backbone `done` event when successful. `error` if the value cannot be converted. Classes listening to the `error` event, usually the Cell classes, should respond appropriately, usually by rendering some kind of error feedback. @param {Event} e */ saveOrCancel: function (e) { if (e.type === "keydown") { // enter or tab if (e.keyCode === 13 || e.keyCode === 9) { e.preventDefault(); var valueToSet = this.formatter.toRaw(this.$el.val()); if (_.isUndefined(valueToSet) || !this.model.set(this.column.get("name"), valueToSet, {validate: true})) { this.trigger("error"); } else { this.trigger("done"); } } // esc else if (e.keyCode === 27) { // undo e.stopPropagation(); this.trigger("done"); } } else if (e.type === "blur") { if (this.formatter.fromRaw(this.model.get(this.column.get("name"))) === this.$el.val()) { this.trigger("done"); } else { var self = this; var timeout = window.setTimeout(function () { self.$el.focus(); window.clearTimeout(timeout); }, 1); } } }, postRender: function () { // move the cursor to the end on firefox if text is right aligned if (this.$el.css("text-align") === "right") { var val = this.$el.val(); this.$el.focus().val(null).val(val); } else { this.$el.focus(); } return this; } }); /** The super-class for all Cell types. By default, this class renders a plain table cell with the model value converted to a string using the formatter. The table cell is clickable, upon which the cell will go into editor mode, which is rendered by a Backgrid.InputCellEditor instance by default. Upon any formatting errors, this class will add a `error` CSS class to the table cell. @abstract @class Backgrid.Cell @extends Backbone.View */ var Cell = Backgrid.Cell = Backbone.View.extend({ /** @property */ tagName: "td", /** @property {Backgrid.CellFormatter|Object|string} [formatter=new CellFormatter()] */ formatter: new CellFormatter(), /** @property {Backgrid.CellEditor} [editor=Backgrid.InputCellEditor] The default editor for all cell instances of this class. This value must be a class, it will be automatically instantiated upon entering edit mode. See Backgrid.CellEditor */ editor: InputCellEditor, /** @property */ events: { "click": "enterEditMode" }, /** Initializer. @param {Object} options @param {Backbone.Model} options.model @param {Backgrid.Column} options.column @throws {ReferenceError} If formatter is a string but a formatter class of said name cannot be found in the Backgrid module. */ initialize: function (options) { requireOptions(options, ["model", "column"]); this.column = options.column; if (!(this.column instanceof Column)) { this.column = new Column(this.column); } this.formatter = resolveNameToClass(this.formatter, "Formatter"); this.editor = resolveNameToClass(this.editor, "CellEditor"); this.listenTo(this.model, "change:" + this.column.get("name"), function () { if (!this.$el.hasClass("editor")) this.render(); }); }, /** Render a text string in a table cell. The text is converted from the model's raw value for this cell's column. */ render: function () { this.$el.empty().text(this.formatter.fromRaw(this.model.get(this.column.get("name")))); return this; }, /** If this column is editable, a new CellEditor instance is instantiated with its required parameters and listens on the editor's `done` and `error` events. When the editor is `done`, edit mode is exited. When the editor triggers an `error` event, it means the editor is unable to convert the current user input to an apprpriate value for the model's column. An `editor` CSS class is added to the cell upon entering edit mode. */ enterEditMode: function (e) { if (this.column.get("editable")) { this.currentEditor = new this.editor({ parent: this, column: this.column, model: this.model, formatter: this.formatter }); /** Backbone Event. Fired when a cell is entering edit mode and an editor instance has been constructed, but before it is rendered and inserted into the DOM. @event edit @param {Backgrid.Cell} cell This cell instance. @param {Backgrid.CellEditor} editor The cell editor constructed. */ this.trigger("edit", this, this.currentEditor); this.listenTo(this.currentEditor, "done", this.exitEditMode); this.listenTo(this.currentEditor, "error", this.renderError); this.$el.empty(); this.undelegateEvents(); this.$el.append(this.currentEditor.$el); this.currentEditor.render(); this.$el.addClass("editor"); /** Backbone Event. Fired when a cell has finished switching to edit mode. @event editing @param {Backgrid.Cell} cell This cell instance. @param {Backgrid.CellEditor} editor The cell editor constructed. */ this.trigger("editing", this, this.currentEditor); } }, /** Put an `error` CSS class on the table cell. */ renderError: function () { this.$el.addClass("error"); }, /** Removes the editor and re-render in display mode. */ exitEditMode: function () { this.$el.removeClass("error"); this.currentEditor.off(null, null, this); this.currentEditor.remove(); delete this.currentEditor; this.$el.removeClass("editor"); this.render(); this.delegateEvents(); }, /** Clean up this cell. @chainable */ remove: function () { if (this.currentEditor) { this.currentEditor.remove.apply(this, arguments); delete this.currentEditor; } return Backbone.View.prototype.remove.apply(this, arguments); } }); /** StringCell displays HTML escaped strings and accepts anything typed in. @class Backgrid.StringCell @extends Backgrid.Cell */ var StringCell = Backgrid.StringCell = Cell.extend({ /** @property */ className: "string-cell" // No formatter needed. Strings call auto-escaped by jQuery on insertion. }); /** UriCell renders an HTML `<a>` anchor for the value and accepts URIs as user input values. A URI input is URI encoded using `encodeURI()` before writing to the underlying model. @class Backgrid.UriCell @extends Backgrid.Cell */ var UriCell = Backgrid.UriCell = Cell.extend({ /** @property */ className: "uri-cell", formatter: { fromRaw: function (rawData) { return rawData; }, toRaw: function (formattedData) { var result = encodeURI(formattedData); return result === "undefined" ? undefined : result; } }, render: function () { this.$el.empty(); var formattedValue = this.formatter.fromRaw(this.model.get(this.column.get("name"))); this.$el.append($("<a>", { href: formattedValue, title: formattedValue, target: "_blank" }).text(formattedValue)); return this; } }); /** Like Backgrid.UriCell, EmailCell renders an HTML `<a>` anchor for the value. The `href` in the anchor is prefixed with `mailto:`. EmailCell will complain if the user enters a string that doesn't contain the `@` sign. @class Backgrid.EmailCell @extends Backgrid.Cell */ var EmailCell = Backgrid.EmailCell = Cell.extend({ /** @property */ className: "email-cell", formatter: { fromRaw: function (rawData) { return rawData; }, toRaw: function (formattedData) { var parts = formattedData.split("@"); if (parts.length === 2 && _.all(parts)) { return formattedData; } } }, render: function () { this.$el.empty(); var formattedValue = this.formatter.fromRaw(this.model.get(this.column.get("name"))); this.$el.append($("<a>", { href: "mailto:" + formattedValue, title: formattedValue }).text(formattedValue)); return this; } }); /** NumberCell is a generic cell that renders all numbers. Numbers are formatted using a Backgrid.NumberFormatter. @class Backgrid.NumberCell @extends Backgrid.Cell */ var NumberCell = Backgrid.NumberCell = Cell.extend({ /** @property */ className: "number-cell", /** @property {number} [decimals=2] Must be an integer. */ decimals: NumberFormatter.prototype.defaults.decimals, /** @property {string} [decimalSeparator='.'] */ decimalSeparator: NumberFormatter.prototype.defaults.decimalSeparator, /** @property {string} [orderSeparator=','] */ orderSeparator: NumberFormatter.prototype.defaults.orderSeparator, /** @property {Backgrid.CellFormatter} [formatter=Backgrid.NumberFormatter] */ formatter: NumberFormatter, /** Initializes this cell and the number formatter. @param {Object} options @param {Backbone.Model} options.model @param {Backgrid.Column} options.column */ initialize: function (options) { Cell.prototype.initialize.apply(this, arguments); this.formatter = new this.formatter({ decimals: this.decimals, decimalSeparator: this.decimalSeparator, orderSeparator: this.orderSeparator }); } }); /** An IntegerCell is just a Backgrid.NumberCell with 0 decimals. If a floating point number is supplied, the number is simply rounded the usual way when displayed. @class Backgrid.IntegerCell @extends Backgrid.NumberCell */ var IntegerCell = Backgrid.IntegerCell = NumberCell.extend({ /** @property */ className: "integer-cell", /** @property {number} decimals Must be an integer. */ decimals: 0 }); /** DatetimeCell is a basic cell that accepts datetime string values in RFC-2822 or W3C's subset of ISO-8601 and displays them in ISO-8601 format. For a much more sophisticated date time cell with better datetime formatting, take a look at the Backgrid.Extension.MomentCell extension. @class Backgrid.DatetimeCell @extends Backgrid.Cell See: - Backgrid.Extension.MomentCell - Backgrid.DatetimeFormatter */ var DatetimeCell = Backgrid.DatetimeCell = Cell.extend({ /** @property */ className: "datetime-cell", /** @property {boolean} [includeDate=true] */ includeDate: DatetimeFormatter.prototype.defaults.includeDate, /** @property {boolean} [includeTime=true] */ includeTime: DatetimeFormatter.prototype.defaults.includeTime, /** @property {boolean} [includeMilli=false] */ includeMilli: DatetimeFormatter.prototype.defaults.includeMilli, /** @property {Backgrid.CellFormatter} [formatter=Backgrid.DatetimeFormatter] */ formatter: DatetimeFormatter, /** Initializes this cell and the datetime formatter. @param {Object} options @param {Backbone.Model} options.model @param {Backgrid.Column} options.column */ initialize: function (options) { Cell.prototype.initialize.apply(this, arguments); this.formatter = new this.formatter({ includeDate: this.includeDate, includeTime: this.includeTime, includeMilli: this.includeMilli }); var placeholder = this.includeDate ? "YYYY-MM-DD" : ""; placeholder += (this.includeDate && this.includeTime) ? "T" : ""; placeholder += this.includeTime ? "HH:mm:ss" : ""; placeholder += (this.includeTime && this.includeMilli) ? ".SSS" : ""; this.editor = this.editor.extend({ attributes: _.extend({}, this.editor.prototype.attributes, this.editor.attributes, { placeholder: placeholder }) }); } }); /** DateCell is a Backgrid.DatetimeCell without the time part. @class Backgrid.DateCell @extends Backgrid.DatetimeCell */ var DateCell = Backgrid.DateCell = DatetimeCell.extend({ /** @property */ className: "date-cell", /** @property */ includeTime: false }); /** TimeCell is a Backgrid.DatetimeCell without the date part. @class Backgrid.TimeCell @extends Backgrid.DatetimeCell */ var TimeCell = Backgrid.TimeCell = DatetimeCell.extend({ /** @property */ className: "time-cell", /** @property */ includeDate: false }); /** BooleanCell is a different kind of cell in that there's no difference between display mode and edit mode and this cell type always renders a checkbox for selection. @class Backgrid.BooleanCell @extends Backgrid.Cell */ var BooleanCell = Backgrid.BooleanCell = Cell.extend({ /** @property */ className: "boolean-cell", /** BooleanCell simple uses a default HTML checkbox template instead of a CellEditor instance. @property {function(Object, ?Object=): string} editor The Underscore.js template to render the editor. */ editor: _.template("<input type='checkbox'<%= checked ? checked='checked' : '' %> />'"), /** Since the editor is not an instance of a CellEditor subclass, more things need to be done in BooleanCell class to listen to editor mode events. */ events: { "click": "enterEditMode", "blur input[type=checkbox]": "exitEditMode", "change input[type=checkbox]": "save" }, /** Renders a checkbox and check it if the model value of this column is true, uncheck otherwise. */ render: function () { this.$el.empty(); this.currentEditor = $(this.editor({ checked: this.formatter.fromRaw(this.model.get(this.column.get("name"))) })); this.$el.append(this.currentEditor); return this; }, /** Simple focuses the checkbox and add an `editor` CSS class to the cell. */ enterEditMode: function (e) { this.$el.addClass("editor"); this.currentEditor.focus(); }, /** Removed the `editor` CSS class from the cell. */ exitEditMode: function (e) { this.$el.removeClass("editor"); }, /** Set true to the model attribute if the checkbox is checked, false otherwise. */ save: function (e) { var val = this.formatter.toRaw(this.currentEditor.prop("checked")); this.model.set(this.column.get("name"), val); } }); /** SelectCellEditor renders an HTML `<select>` fragment as the editor. @class Backgrid.SelectCellEditor @extends Backgrid.CellEditor */ var SelectCellEditor = Backgrid.SelectCellEditor = CellEditor.extend({ /** @property */ tagName: "select", /** @property */ events: { "change": "save", "blur": "save" }, /** @property {function(Object, ?Object=): string} template */ template: _.template('<option value="<%- value %>" <%= selected ? \'selected="selected"\' : "" %>><%- text %></option>'), setOptionValues: function (optionValues) { this.optionValues = optionValues; }, _renderOptions: function (nvps, currentValue) { var options = ''; for (var i = 0; i < nvps.length; i++) { options = options + this.template({ text: nvps[i][0], value: nvps[i][1], selected: currentValue == nvps[i][1] }); } return options; }, /** Renders the options if `optionValues` is a list of name-value pairs. The options are contained inside option groups if `optionValues` is a list of object hashes. The name is rendered at the option text and the value is the option value. If `optionValues` is a function, it is called without a parameter. */ render: function () { this.$el.empty(); var optionValues = _.result(this, "optionValues"); var currentValue = this.model.get(this.column.get("name")); if (!_.isArray(optionValues)) throw TypeError("optionValues must be an array"); var optionValue = null; var optionText = null; var optionValue = null; var optgroupName = null; var optgroup = null; for (var i = 0; i < optionValues.length; i++) { var optionValue = optionValues[i]; if (_.isArray(optionValue)) { optionText = optionValue[0]; optionValue = optionValue[1]; this.$el.append(this.template({ text: optionText, value: optionValue, selected: optionValue == currentValue })); } else if (_.isObject(optionValue)) { optgroupName = optionValue.name; optgroup = $("<optgroup></optgroup>", { label: optgroupName }); optgroup.append(this._renderOptions(optionValue.values, currentValue)); this.$el.append(optgroup); } else { throw TypeError("optionValues elements must be a name-value pair or an object hash of { name: 'optgroup label', value: [option name-value pairs] }"); } } return this; }, /** Saves the value of the selected option to the model attribute. Triggers a `done` Backbone event. */ save: function (e) { this.model.set(this.column.get("name"), this.formatter.toRaw(this.$el.val())); this.trigger("done"); } }); /** SelectCell is also a different kind of cell in that upon going into edit mode the cell renders a list of options for to pick from, as opposed to an input box. SelectCell cannot be referenced by its string name when used in a column definition because requires an `optionValues` class attribute to be defined. `optionValues` can either be a list of name-value pairs, to be rendered as options, or a list of object hashes which consist of a key *name* which is the option group name, and a key *values* which is a list of name-value pairs to be rendered as options under that option group. In addition, `optionValues` can also be a parameter-less function that returns one of the above. If the options are static, it is recommended the returned values to be memoized. _.memoize() is a good function to help with that. @class Backgrid.SelectCell @extends Backgrid.Cell */ var SelectCell = Backgrid.SelectCell = Cell.extend({ /** @property */ className: "select-cell", /** @property */ editor: SelectCellEditor, /** @property {Array.<Array>|Array.<{name: string, values: Array.<Array>}>} optionValues */ optionValues: undefined, /** Initializer. @param {Object} options @param {Backbone.Model} options.model @param {Backgrid.Column} options.column @throws {TypeError} If `optionsValues` is undefined. */ initialize: function (options) { Cell.prototype.initialize.apply(this, arguments); requireOptions(this, ["optionValues"]); this.optionValues = _.result(this, "optionValues"); this.listenTo(this, "edit", this.setOptionValues); }, setOptionValues: function (cell, editor) { editor.setOptionValues(this.optionValues); }, /** Renders the label using the raw value as key to look up from `optionValues`. @throws {TypeError} If `optionValues` is malformed. */ render: function () { this.$el.empty(); var optionValues = this.optionValues; var rawData = this.formatter.fromRaw(this.model.get(this.column.get("name"))); try { if (!_.isArray(optionValues) || _.isEmpty(optionValues)) throw new TypeError; for (var i = 0; i < optionValues.length; i++) { var optionValue = optionValues[i]; if (_.isArray(optionValue)) { var optionText = optionValue[0]; var optionValue = optionValue[1]; if (optionValue == rawData) { this.$el.append(optionText); break; } } else if (_.isObject(optionValue)) { var optionGroupValues = optionValue.values; for (var j = 0; j < optionGroupValues.length; j++) { var optionGroupValue = optionGroupValues[j]; if (optionGroupValue[1] == rawData) { this.$el.append(optionGroupValue[0]); break; } } } else { throw new TypeError; } } } catch (ex) { if (ex instanceof TypeError) { throw TypeError("'optionValues' must be of type {Array.<Array>|Array.<{name: string, values: Array.<Array>}>}"); } throw ex; } return this; } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** A Column is a placeholder for column metadata. You usually don't need to create an instance of this class yourself as a collection of column instances will be created for you from a list of column attributes in the Backgrid.js view class constructors. @class Backgrid.Column @extends Backbone.Model */ var Column = Backgrid.Column = Backbone.Model.extend({ defaults: { name: undefined, label: undefined, sortable: true, editable: true, renderable: true, formatter: undefined, cell: undefined, headerCell: undefined }, /** Initializes this Column instance. @param {Object} attrs Column attributes. @param {string} attrs.name The name of the model attribute. @param {string|Backgrid.Cell} attrs.cell The cell type. If this is a string, the capitalized form will be used to look up a cell class in Backbone, i.e.: string => StringCell. If a Cell subclass is supplied, it is initialized with a hash of parameters. If a Cell instance is supplied, it is used directly. @param {string|Backgrid.HeaderCell} [attrs.headerCell] The header cell type. @param {string} [attrs.label] The label to show in the header. @param {boolean} [attrs.sortable=true] @param {boolean} [attrs.editable=true] @param {boolean} [attrs.renderable=true] @param {Backgrid.CellFormatter|Object|string} [attrs.formatter] The formatter to use to convert between raw model values and user input. @throws {TypeError} If attrs.cell or attrs.options are not supplied. @throws {ReferenceError} If attrs.cell is a string but a cell class of said name cannot be found in the Backgrid module. See: - Backgrid.Cell - Backgrid.CellFormatter */ initialize: function (attrs) { requireOptions(attrs, ["cell", "name"]); if (!this.has("label")) { this.set({ label: this.get("name") }, { silent: true }); } var cell = resolveNameToClass(this.get("cell"), "Cell"); this.set({ cell: cell }, { silent: true }); } }); /** A Backbone collection of Column instances. @class Backgrid.Columns @extends Backbone.Collection */ var Columns = Backgrid.Columns = Backbone.Collection.extend({ /** @property {Backgrid.Column} model */ model: Column }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** Row is a simple container view that takes a model instance and a list of column metadata describing how each of the model's attribute is to be rendered, and apply the appropriate cell to each attribute. @class Backgrid.Row @extends Backbone.View */ var Row = Backgrid.Row = Backbone.View.extend({ /** @property */ tagName: "tr", /** Initializes a row view instance. @param {Object} options @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Model} options.model The model instance to render. @throws {TypeError} If options.columns or options.model is undefined. */ initialize: function (options) { requireOptions(options, ["columns", "model"]); var columns = this.columns = options.columns; if (!(columns instanceof Backbone.Collection)) { columns = this.columns = new Columns(columns); } this.listenTo(columns, "change:renderable", this.renderColumn); var cells = this.cells = []; for (var i = 0; i < columns.length; i++) { var column = columns.at(i); cells.push(new (column.get("cell"))({ column: column, model: this.model })); } this.listenTo(columns, "add", function (column, columns, options) { options = _.defaults(options || {}, {render: true}); var at = columns.indexOf(column); var cell = new (column.get("cell"))({ column: column, model: this.model }); cells.splice(at, 0, cell); this.renderColumn(column, column.get("renderable") && options.render); }); this.listenTo(columns, "remove", function (column) { this.renderColumn(column, false); }); }, /** Backbone event handler. Insert a table cell to the right column in the row if renderable is true, detach otherwise. @param {Backgrid.Column} column @param {boolean} renderable */ renderColumn: function (column, renderable) { var cells = this.cells; var columns = this.columns; var spliceIndex = -1; for (var i = 0; i < cells.length; i++) { var cell = cells[i]; if (cell.column.get("name") == column.get("name")) { spliceIndex = i; break; } } if (spliceIndex != -1) { var $el = this.$el; if (renderable) { var cell = cells[spliceIndex]; if (spliceIndex === 0) { $el.prepend(cell.render().$el); } else if (spliceIndex === columns.length - 1) { $el.append(cell.render().$el); } else { $el.children().eq(spliceIndex).before(cell.render().$el); } } else { $el.children().eq(spliceIndex).detach(); } } }, /** Renders a row of cells for this row's model. */ render: function () { this.$el.empty(); var fragment = document.createDocumentFragment(); for (var i = 0; i < this.cells.length; i++) { var cell = this.cells[i]; if (cell.column.get("renderable")) { fragment.appendChild(cell.render().el); } } this.el.appendChild(fragment); return this; }, /** Clean up this row and its cells. @chainable */ remove: function () { for (var i = 0; i < this.cells.length; i++) { var cell = this.cells[i]; cell.remove.apply(cell, arguments); } return Backbone.View.prototype.remove.apply(this, arguments); } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** HeaderCell is a special cell class that renders a column header cell. If the column is sortable, a sorter is also rendered and will trigger a table refresh after sorting. @class Backgrid.HeaderCell @extends Backbone.View */ var HeaderCell = Backgrid.HeaderCell = Backbone.View.extend({ /** @property */ tagName: "th", /** @property */ events: { "click a": "onClick" }, /** @property {null|"ascending"|"descending"} _direction The current sorting direction of this column. */ _direction: null, /** Initializer. @param {Object} options @param {Backgrid.Column|Object} options.column @throws {TypeError} If options.column or options.collection is undefined. */ initialize: function (options) { requireOptions(options, ["column", "collection"]); this.column = options.column; if (!(this.column instanceof Column)) { this.column = new Column(this.column); } this.listenTo(Backbone, "backgrid:sort", this._resetCellDirection); }, /** Gets or sets the direction of this cell. If called directly without parameters, returns the current direction of this cell, otherwise sets it. If a `null` is given, sets this cell back to the default order. @param {null|"ascending"|"descending"} dir @return {null|string} The current direction or the changed direction. */ direction: function (dir) { if (arguments.length) { if (this._direction) this.$el.removeClass(this._direction); if (dir) this.$el.addClass(dir); this._direction = dir; } return this._direction; }, /** Event handler for the Backbone `backgrid:sort` event. Resets this cell's direction to default if sorting is being done on another column. @private */ _resetCellDirection: function (sortByColName, direction, comparator, collection) { if (collection == this.collection) { if (sortByColName !== this.column.get("name")) this.direction(null); else this.direction(direction); } }, /** Event handler for the `click` event on the cell's anchor. If the column is sortable, clicking on the anchor will cycle through 3 sorting orderings - `ascending`, `descending`, and default. */ onClick: function (e) { e.preventDefault(); var columnName = this.column.get("name"); if (this.column.get("sortable")) { if (this.direction() === "ascending") { this.sort(columnName, "descending", function (left, right) { var leftVal = left.get(columnName); var rightVal = right.get(columnName); if (leftVal === rightVal) { return 0; } else if (leftVal > rightVal) { return -1; } return 1; }); } else if (this.direction() === "descending") { this.sort(columnName, null); } else { this.sort(columnName, "ascending", function (left, right) { var leftVal = left.get(columnName); var rightVal = right.get(columnName); if (leftVal === rightVal) { return 0; } else if (leftVal < rightVal) { return -1; } return 1; }); } } }, /** If the underlying collection is a Backbone.PageableCollection in server-mode or infinite-mode, a page of models is fetched after sorting is done on the server. If the underlying collection is a Backbone.PageableCollection in client-mode, or any [Backbone.Collection](http://backbonejs.org/#Collection) instance, sorting is done on the client side. If the collection is an instance of a Backbone.PageableCollection, sorting will be done globally on all the pages and the current page will then be returned. Triggers a Backbone `backgrid:sort` event when done. @param {string} columnName @param {null|"ascending"|"descending"} direction @param {function(*, *): number} [comparator] See [Backbone.Collection#comparator](http://backbonejs.org/#Collection-comparator) */ sort: function (columnName, direction, comparator) { comparator = comparator || this._cidComparator; var collection = this.collection; if (Backbone.PageableCollection && collection instanceof Backbone.PageableCollection) { var order; if (direction === "ascending") order = -1; else if (direction === "descending") order = 1; else order = null; collection.setSorting(order ? columnName : null, order); if (collection.mode == "client") { if (!collection.fullCollection.comparator) { collection.fullCollection.comparator = comparator; } collection.fullCollection.sort(); } else collection.fetch(); } else { collection.comparator = comparator; collection.sort(); } /** Global Backbone event. Fired when the sorter is clicked on a sortable column. @event backgrid:sort @param {string} columnName @param {null|"ascending"|"descending"} direction @param {function(*, *): number} comparator A Backbone.Collection#comparator. @param {Backbone.Collection} collection */ Backbone.trigger("backgrid:sort", columnName, direction, comparator, this.collection); }, /** Default comparator for Backbone.Collections. Sorts cids in ascending order. The cids of the models are assumed to be in insertion order. @private @param {*} left @param {*} right */ _cidComparator: function (left, right) { var lcid = left.cid, rcid = right.cid; if (!_.isUndefined(lcid) && !_.isUndefined(rcid)) { lcid = lcid.slice(1) * 1, rcid = rcid.slice(1) * 1; if (lcid < rcid) return -1; else if (lcid > rcid) return 1; } return 0; }, /** Renders a header cell with a sorter and a label. */ render: function () { this.$el.empty(); var $label = $("<a>").text(this.column.get("label")).append("<b class='sort-caret'></b>"); this.$el.append($label); return this; } }); /** HeaderRow is a controller for a row of header cells. @class Backgrid.HeaderRow @extends Backgrid.Row */ var HeaderRow = Backgrid.HeaderRow = Backgrid.Row.extend({ /** Initializer. @param {Object} options @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns @param {Backgrid.HeaderCell} [options.headerCell] Customized default HeaderCell for all the columns. Supply a HeaderCell class or instance to a the `headerCell` key in a column definition for column-specific header rendering. @throws {TypeError} If options.columns or options.collection is undefined. */ initialize: function (options) { requireOptions(options, ["columns", "collection"]); var columns = this.columns = options.columns; if (!(columns instanceof Backbone.Collection)) { columns = this.columns = new Columns(columns); } this.listenTo(columns, "change:renderable", this.renderColumn); var cells = this.cells = []; for (var i = 0; i < columns.length; i++) { var column = columns.at(i); var headerCell = column.get("headerCell") || options.headerCell || HeaderCell; cells.push(new headerCell({ column: column, collection: this.collection })); } this.listenTo(columns, "add", function (column, columns, opts) { opts = _.defaults(opts || {}, {render: true}); var at = columns.indexOf(column); var headerCell = column.get("headerCell") || options.headerCell || HeaderCell; headerCell = new headerCell({ column: column, collection: this.collection }); cells.splice(at, 0, headerCell); this.renderColumn(column, column.get("renderable") && opts.render); }); this.listenTo(columns, "remove", function (column) { this.renderColumn(column, false); }); } }); /** Header is a special structural view class that renders a table head with a single row of header cells. @class Backgrid.Header @extends Backbone.View */ var Header = Backgrid.Header = Backbone.View.extend({ /** @property */ tagName: "thead", /** Initializer. Initializes this table head view to contain a single header row view. @param {Object} options @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Model} options.model The model instance to render. @throws {TypeError} If options.columns or options.model is undefined. */ initialize: function (options) { requireOptions(options, ["columns", "collection"]); this.columns = options.columns; if (!(this.columns instanceof Backbone.Collection)) { this.columns = new Columns(this.columns); } this.row = new Backgrid.HeaderRow({ columns: this.columns, collection: this.collection }); }, /** Renders this table head with a single row of header cells. */ render: function () { this.$el.append(this.row.render().$el); return this; }, /** Clean up this header and its row. @chainable */ remove: function () { this.row.remove.apply(this.row, arguments); return Backbone.View.prototype.remove.apply(this, arguments); } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** Body is the table body which contains the rows inside a table. Body is responsible for refreshing the rows after sorting, insertion and removal. @class Backgrid.Body @extends Backbone.View */ var Body = Backgrid.Body = Backbone.View.extend({ /** @property */ tagName: "tbody", /** Initializer. @param {Object} options @param {Backbone.Collection} options.collection @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata @param {Backgrid.Row} [options.row=Backgrid.Row] The Row class to use. @throws {TypeError} If options.columns or options.collection is undefined. See Backgrid.Row. */ initialize: function (options) { requireOptions(options, ["columns", "collection"]); this.columns = options.columns; if (!(this.columns instanceof Backbone.Collection)) { this.columns = new Columns(this.columns); } this.row = options.row || Row; this.rows = this.collection.map(function (model) { var row = new this.row({ columns: this.columns, model: model }); return row; }, this); var collection = this.collection; this.listenTo(collection, "add", this.insertRow); this.listenTo(collection, "remove", this.removeRow); this.listenTo(collection, "sort", this.refresh); this.listenTo(collection, "reset", this.refresh); }, /** This method can be called either directly or as a callback to a [Backbone.Collecton#add](http://backbonejs.org/#Collection-add) event. When called directly, it accepts a model or an array of models and an option hash just like [Backbone.Collection#add](http://backbonejs.org/#Collection-add) and delegates to it. Once the model is added, a new row is inserted into the body and automatically rendered. When called as a callback of an `add` event, splices a new row into the body and renders it. @param {Backbone.Model} model The model to render as a row. @param {Backbone.Collection} collection When called directly, this parameter is actually the options to [Backbone.Collection#add](http://backbonejs.org/#Collection-add). @param {Object} options When called directly, this must be null. See: - [Backbone.Collection#add](http://backbonejs.org/#Collection-add) */ insertRow: function (model, collection, options) { // insertRow() is called directly if (!(collection instanceof Backbone.Collection) && !options) { this.collection.add(model, (options = collection)); return; } options = _.extend({render: true}, options || {}); var row = new this.row({ columns: this.columns, model: model }); var index = collection.indexOf(model); this.rows.splice(index, 0, row); var $el = this.$el; var $children = $el.children(); var $rowEl = row.render().$el; if (options.render) { if (index >= $children.length) { $el.append($rowEl); } else { $children.eq(index).before($rowEl); } } }, /** The method can be called either directly or as a callback to a [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove) event. When called directly, it accepts a model or an array of models and an option hash just like [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove) and delegates to it. Once the model is removed, a corresponding row is removed from the body. When called as a callback of a `remove` event, splices into the rows and removes the row responsible for rendering the model. @param {Backbone.Model} model The model to remove from the body. @param {Backbone.Collection} collection When called directly, this parameter is actually the options to [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove). @param {Object} options When called directly, this must be null. See: - [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove) */ removeRow: function (model, collection, options) { // removeRow() is called directly if (!options) { this.collection.remove(model, (options = collection)); return; } if (_.isUndefined(options.render) || options.render) { this.rows[options.index].remove(); } this.rows.splice(options.index, 1); }, /** Reinitialize all the rows inside the body and re-render them. @chainable */ refresh: function () { var self = this; _.each(self.rows, function (row) { row.remove(); }); self.rows = self.collection.map(function (model) { var row = new self.row({ columns: self.columns, model: model }); return row; }); self.render(); Backbone.trigger("backgrid:refresh"); return self; }, /** Renders all the rows inside this body. */ render: function () { this.$el.empty(); var fragment = document.createDocumentFragment(); for (var i = 0; i < this.rows.length; i++) { var row = this.rows[i]; fragment.appendChild(row.render().el); } this.el.appendChild(fragment); return this; }, /** Clean up this body and it's rows. @chainable */ remove: function () { for (var i = 0; i < this.rows.length; i++) { var row = this.rows[i]; row.remove.apply(row, arguments); } return Backbone.View.prototype.remove.apply(this, arguments); } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** A Footer is a generic class that only defines a default tag `tfoot` and number of required parameters in the initializer. @abstract @class Backgrid.Footer @extends Backbone.View */ var Footer = Backgrid.Footer = Backbone.View.extend({ /** @property */ tagName: "tfoot", /** Initializer. @param {Object} options @param {*} options.parent The parent view class of this footer. @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Collection} options.collection @throws {TypeError} If options.columns or options.collection is undefined. */ initialize: function (options) { requireOptions(options, ["columns", "collection"]); this.parent = options.parent; this.columns = options.columns; if (!(this.columns instanceof Backbone.Collection)) { this.columns = new Backgrid.Columns(this.columns); } } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ /** Grid represents a data grid that has a header, body and an optional footer. By default, a Grid treats each model in a collection as a row, and each attribute in a model as a column. To render a grid you must provide a list of column metadata and a collection to the Grid constructor. Just like any Backbone.View class, the grid is rendered as a DOM node fragment when you call render(). var grid = Backgrid.Grid({ columns: [{ name: "id", label: "ID", type: "string" }, // ... ], collections: books }); $("#table-container").append(grid.render().el); Optionally, if you want to customize the rendering of the grid's header and footer, you may choose to extend Backgrid.Header and Backgrid.Footer, and then supply that class or an instance of that class to the Grid constructor. See the documentation for Header and Footer for further details. var grid = Backgrid.Grid({ columns: [{ name: "id", label: "ID", type: "string" }], collections: books, header: Backgrid.Header.extend({ //... }), footer: Backgrid.Paginator }); Finally, if you want to override how the rows are rendered in the table body, you can supply a Body subclass as the `body` attribute that uses a different Row class. @class Backgrid.Grid @extends Backbone.View See: - Backgrid.Column - Backgrid.Header - Backgrid.Body - Backgrid.Row - Backgrid.Footer */ var Grid = Backgrid.Grid = Backbone.View.extend({ /** @property */ tagName: "table", /** @property */ className: "backgrid", /** @property */ header: Header, /** @property */ body: Body, /** @property */ footer: null, /** Initializes a Grid instance. @param {Object} options @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Collection} options.collection The collection of tabular model data to display. @param {Backgrid.Header} [options.header=Backgrid.Header] An optional Header class to override the default. @param {Backgrid.Body} [options.body=Backgrid.Body] An optional Body class to override the default. @param {Backgrid.Row} [options.row=Backgrid.Row] An optional Row class to override the default. @param {Backgrid.Footer} [options.footer=Backgrid.Footer] An optional Footer class. */ initialize: function (options) { requireOptions(options, ["columns", "collection"]); // Convert the list of column objects here first so the subviews don't have // to. if (!(options.columns instanceof Backbone.Collection)) { options.columns = new Columns(options.columns); } this.columns = options.columns; this.header = options.header || this.header; this.header = new this.header(options); this.body = options.body || this.body; this.body = new this.body(options); this.footer = options.footer || this.footer; if (this.footer) { this.footer = new this.footer(options); } this.listenTo(this.columns, "reset", function () { this.header = new (this.header.remove().constructor)(options); this.body = new (this.body.remove().constructor)(options); if (this.footer) this.footer = new (this.footer.remove().constructor)(options); this.render(); }); }, /** Delegates to Backgrid.Body#insertRow. */ insertRow: function (model, collection, options) { return this.body.insertRow(model, collection, options); }, /** Delegates to Backgrid.Body#removeRow. */ removeRow: function (model, collection, options) { return this.body.removeRow(model, collection, options); }, /** Delegates to Backgrid.Columns#add for adding a column. Subviews can listen to the `add` event from their internal `columns` if rerendering needs to happen. @param {Object} [options] Options for `Backgrid.Columns#add`. @param {boolean} [options.render=true] Whether to render the column immediately after insertion. @chainable */ insertColumn: function (column, options) { var self = this; options = options || {render: true}; self.columns.add(column, options); return self; }, /** Delegates to Backgrid.Columns#remove for removing a column. Subviews can listen to the `remove` event from the internal `columns` if rerendering needs to happen. @param {Object} [options] Options for `Backgrid.Columns#remove`. @chainable */ removeColumn: function (column, options) { var self = this; self.columns.remove(column, options); return self; }, /** Renders the grid's header, then footer, then finally the body. */ render: function () { this.$el.empty(); this.$el.append(this.header.render().$el); if (this.footer) { this.$el.append(this.footer.render().$el); } this.$el.append(this.body.render().$el); /** Backbone event. Fired when the grid has been successfully rendered. @event rendered */ this.trigger("rendered"); return this; }, /** Clean up this grid and its subviews. @chainable */ remove: function () { this.header.remove.apply(this.header, arguments); this.body.remove.apply(this.body, arguments); this.footer && this.footer.remove.apply(this.footer, arguments); return Backbone.View.prototype.remove.apply(this, arguments); } }); }(this, $, _, Backbone));
BobbieBel/cdnjs
ajax/libs/backgrid.js/0.1.3/backgrid.js
JavaScript
mit
62,121
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["Slider"] = factory(require("react")); else root["Slider"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_4__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _innerSlider = __webpack_require__(5); var _objectAssign = __webpack_require__(23); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _json2mq = __webpack_require__(2); var _json2mq2 = _interopRequireDefault(_json2mq); var _reactResponsiveMixin = __webpack_require__(26); var _reactResponsiveMixin2 = _interopRequireDefault(_reactResponsiveMixin); var _defaultProps = __webpack_require__(9); var _defaultProps2 = _interopRequireDefault(_defaultProps); var Slider = _react2['default'].createClass({ displayName: 'Slider', mixins: [_reactResponsiveMixin2['default']], getInitialState: function getInitialState() { return { breakpoint: null }; }, componentDidMount: function componentDidMount() { var _this = this; if (this.props.responsive) { var breakpoints = this.props.responsive.map(function (breakpt) { return breakpt.breakpoint; }); breakpoints.sort(function (x, y) { return x - y; }); breakpoints.forEach(function (breakpoint, index) { var bQuery; if (index === 0) { bQuery = (0, _json2mq2['default'])({ minWidth: 0, maxWidth: breakpoint }); } else { bQuery = (0, _json2mq2['default'])({ minWidth: breakpoints[index - 1], maxWidth: breakpoint }); } _this.media(bQuery, function () { _this.setState({ breakpoint: breakpoint }); }); }); // Register media query for full screen. Need to support resize from small to large var query = (0, _json2mq2['default'])({ minWidth: breakpoints.slice(-1)[0] }); this.media(query, function () { _this.setState({ breakpoint: null }); }); } }, render: function render() { var _this2 = this; var settings; var newProps; if (this.state.breakpoint) { newProps = this.props.responsive.filter(function (resp) { return resp.breakpoint === _this2.state.breakpoint; }); settings = newProps[0].settings === 'unslick' ? 'unslick' : (0, _objectAssign2['default'])({}, this.props, newProps[0].settings); } else { settings = (0, _objectAssign2['default'])({}, _defaultProps2['default'], this.props); } if (settings === 'unslick') { // if 'unslick' responsive breakpoint setting used, just return the <Slider> tag nested HTML return _react2['default'].createElement( 'div', null, this.props.children ); } else { return _react2['default'].createElement( _innerSlider.InnerSlider, settings, this.props.children ); } } }); module.exports = Slider; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var camel2hyphen = __webpack_require__(3); var isDimension = function (feature) { var re = /[height|width]$/; return re.test(feature); }; var obj2mq = function (obj) { var mq = ''; var features = Object.keys(obj); features.forEach(function (feature, index) { var value = obj[feature]; feature = camel2hyphen(feature); // Add px to dimension features if (isDimension(feature) && typeof value === 'number') { value = value + 'px'; } if (value === true) { mq += feature; } else if (value === false) { mq += 'not ' + feature; } else { mq += '(' + feature + ': ' + value + ')'; } if (index < features.length-1) { mq += ' and ' } }); return mq; }; var json2mq = function (query) { var mq = ''; if (typeof query === 'string') { return query; } // Handling array of media queries if (query instanceof Array) { query.forEach(function (q, index) { mq += obj2mq(q); if (index < query.length-1) { mq += ', ' } }); return mq; } // Handling single media query return obj2mq(query); }; module.exports = json2mq; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var camel2hyphen = function (str) { return str .replace(/[A-Z]/g, function (match) { return '-' + match.toLowerCase(); }) .toLowerCase(); }; module.exports = camel2hyphen; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _mixinsEventHandlers = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"./mixins/event-handlers\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())); var _mixinsEventHandlers2 = _interopRequireDefault(_mixinsEventHandlers); var _mixinsHelpers = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"./mixins/helpers\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())); var _mixinsHelpers2 = _interopRequireDefault(_mixinsHelpers); var _initialState = __webpack_require__(8); var _initialState2 = _interopRequireDefault(_initialState); var _defaultProps = __webpack_require__(9); var _defaultProps2 = _interopRequireDefault(_defaultProps); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var _track = __webpack_require__(11); var _dots = __webpack_require__(24); var _arrows = __webpack_require__(25); var InnerSlider = _react2['default'].createClass({ displayName: 'InnerSlider', mixins: [_mixinsHelpers2['default'], _mixinsEventHandlers2['default']], getInitialState: function getInitialState() { return _initialState2['default']; }, getDefaultProps: function getDefaultProps() { return _defaultProps2['default']; }, componentWillMount: function componentWillMount() { if (this.props.init) { this.props.init(); } this.setState({ mounted: true }); var lazyLoadedList = []; for (var i = 0; i < this.props.children.length; i++) { if (i >= this.state.currentSlide && i < this.state.currentSlide + this.props.slidesToShow) { lazyLoadedList.push(i); } } if (this.props.lazyLoad && this.state.lazyLoadedList.length === 0) { this.setState({ lazyLoadedList: lazyLoadedList }); } }, componentDidMount: function componentDidMount() { // Hack for autoplay -- Inspect Later this.initialize(this.props); this.adaptHeight(); }, componentDidUpdate: function componentDidUpdate() { this.adaptHeight(); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { this.initialize(nextProps); }, render: function render() { var className = (0, _classnames2['default'])('slick-initialized', 'slick-slider', this.props.className); var trackProps = { fade: this.props.fade, cssEase: this.props.cssEase, speed: this.props.speed, infinite: this.props.infinite, centerMode: this.props.centerMode, currentSlide: this.state.currentSlide, lazyLoad: this.props.lazyLoad, lazyLoadedList: this.state.lazyLoadedList, rtl: this.props.rtl, slideWidth: this.state.slideWidth, slidesToShow: this.props.slidesToShow, slideCount: this.state.slideCount, trackStyle: this.state.trackStyle, variableWidth: this.props.variableWidth }; var dots; if (this.props.dots === true && this.state.slideCount > this.props.slidesToShow) { var dotProps = { dotsClass: this.props.dotsClass, slideCount: this.state.slideCount, slidesToShow: this.props.slidesToShow, currentSlide: this.state.currentSlide, slidesToScroll: this.props.slidesToScroll, clickHandler: this.changeSlide }; dots = _react2['default'].createElement(_dots.Dots, dotProps); } var prevArrow, nextArrow; var arrowProps = { infinite: this.props.infinite, centerMode: this.props.centerMode, currentSlide: this.state.currentSlide, slideCount: this.state.slideCount, slidesToShow: this.props.slidesToShow, prevArrow: this.props.prevArrow, nextArrow: this.props.nextArrow, clickHandler: this.changeSlide }; if (this.props.arrows) { prevArrow = _react2['default'].createElement(_arrows.PrevArrow, arrowProps); nextArrow = _react2['default'].createElement(_arrows.NextArrow, arrowProps); } return _react2['default'].createElement( 'div', { className: className }, _react2['default'].createElement( 'div', { ref: 'list', className: 'slick-list', onMouseDown: this.swipeStart, onMouseMove: this.state.dragging ? this.swipeMove : null, onMouseUp: this.swipeEnd, onMouseLeave: this.state.dragging ? this.swipeEnd : null, onTouchStart: this.swipeStart, onTouchMove: this.state.dragging ? this.swipeMove : null, onTouchEnd: this.swipeEnd, onTouchCancel: this.state.dragging ? this.swipeEnd : null }, _react2['default'].createElement( _track.Track, _extends({ ref: 'track' }, trackProps), this.props.children ) ), prevArrow, nextArrow, dots ); } }); exports.InnerSlider = InnerSlider; /***/ }, /* 6 */, /* 7 */, /* 8 */ /***/ function(module, exports, __webpack_require__) { var initialState = { animating: false, dragging: false, autoPlayTimer: null, currentDirection: 0, currentLeft: null, currentSlide: 0, direction: 1, // listWidth: null, // listHeight: null, // loadIndex: 0, slideCount: null, slideWidth: null, // sliding: false, // slideOffset: 0, swipeLeft: null, touchObject: { startX: 0, startY: 0, curX: 0, curY: 0 }, lazyLoadedList: [], // added for react initialized: false, edgeDragged: false, swiped: false, // used by swipeEvent. differentites between touch and swipe. trackStyle: {}, trackWidth: 0 // Removed // transformsEnabled: false, // $nextArrow: null, // $prevArrow: null, // $dots: null, // $list: null, // $slideTrack: null, // $slides: null, }; module.exports = initialState; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { var defaultProps = { className: '', // accessibility: true, adaptiveHeight: false, arrows: true, autoplay: false, autoplaySpeed: 3000, centerMode: false, centerPadding: '50px', cssEase: 'ease', dots: false, dotsClass: 'slick-dots', draggable: true, easing: 'linear', edgeFriction: 0.35, fade: false, focusOnSelect: false, infinite: true, initialSlide: 0, lazyLoad: false, responsive: null, rtl: false, slide: 'div', slidesToShow: 1, slidesToScroll: 1, speed: 500, swipe: true, swipeToSlide: false, touchMove: true, touchThreshold: 5, useCSS: true, variableWidth: false, vertical: false, // waitForAnimate: true, afterChange: null, beforeChange: null, edgeEvent: null, init: null, swipeEvent: null, // nextArrow, prevArrow are react componets nextArrow: null, prevArrow: null }; module.exports = defaultProps; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames () { 'use strict'; var classes = ''; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if ('string' === argType || 'number' === argType) { classes += ' ' + arg; } else if (Array.isArray(arg)) { classes += ' ' + classNames.apply(null, arg); } else if ('object' === argType) { for (var key in arg) { if (arg.hasOwnProperty(key) && arg[key]) { classes += ' ' + key; } } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } /* global define */ // safely export classNames for RequireJS if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactLibCloneWithProps = __webpack_require__(12); var _reactLibCloneWithProps2 = _interopRequireDefault(_reactLibCloneWithProps); var _objectAssign = __webpack_require__(23); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var getSlideClasses = function getSlideClasses(spec) { var slickActive, slickCenter, slickCloned; var centerOffset, index; if (spec.rtl) { index = spec.slideCount - 1 - spec.index; console.log(); } else { index = spec.index; } slickCloned = index < 0 || index >= spec.slideCount; if (spec.centerMode) { centerOffset = Math.floor(spec.slidesToShow / 2); slickCenter = spec.currentSlide === index; if (index > spec.currentSlide - centerOffset - 1 && index <= spec.currentSlide + centerOffset) { slickActive = true; } } else { slickActive = spec.currentSlide <= index && index < spec.currentSlide + spec.slidesToShow; } return (0, _classnames2['default'])({ 'slick-slide': true, 'slick-active': slickActive, 'slick-center': slickCenter, 'slick-cloned': slickCloned }); }; var getSlideStyle = function getSlideStyle(spec) { var style = {}; if (spec.variableWidth === undefined || spec.variableWidth === false) { style.width = spec.slideWidth; } if (spec.fade) { style.position = 'relative'; style.left = -spec.index * spec.slideWidth; style.opacity = spec.currentSlide === spec.index ? 1 : 0; style.transition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase; style.WebkitTransition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase; } return style; }; var renderSlides = function renderSlides(spec) { var key; var slides = []; var preCloneSlides = []; var postCloneSlides = []; var count = _react2['default'].Children.count(spec.children); var child; _react2['default'].Children.forEach(spec.children, function (elem, index) { if (!spec.lazyLoad | (spec.lazyLoad && spec.lazyLoadedList.indexOf(index) >= 0)) { child = elem; } else { child = _react2['default'].createElement('div', null); } var childStyle = getSlideStyle((0, _objectAssign2['default'])({}, spec, { index: index })); slides.push((0, _reactLibCloneWithProps2['default'])(child, { key: index, 'data-index': index, className: getSlideClasses((0, _objectAssign2['default'])({ index: index }, spec)), style: childStyle })); // variableWidth doesn't wrap properly. if (spec.infinite && spec.fade === false) { var infiniteCount = spec.variableWidth ? spec.slidesToShow + 1 : spec.slidesToShow; if (index >= count - infiniteCount) { key = -(count - index); preCloneSlides.push((0, _reactLibCloneWithProps2['default'])(child, { key: key, 'data-index': key, className: getSlideClasses((0, _objectAssign2['default'])({ index: key }, spec)), style: childStyle })); } if (index < infiniteCount) { key = count + index; postCloneSlides.push((0, _reactLibCloneWithProps2['default'])(child, { key: key, 'data-index': key, className: getSlideClasses((0, _objectAssign2['default'])({ index: key }, spec)), style: childStyle })); } } }); if (spec.rtl) { return preCloneSlides.concat(slides, postCloneSlides).reverse(); } else { return preCloneSlides.concat(slides, postCloneSlides); } }; var Track = _react2['default'].createClass({ displayName: 'Track', render: function render() { var slides = renderSlides(this.props); return _react2['default'].createElement( 'div', { className: 'slick-track', style: this.props.trackStyle }, slides ); } }); exports.Track = Track; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only * @providesModule cloneWithProps */ 'use strict'; var ReactElement = __webpack_require__(13); var ReactPropTransferer = __webpack_require__(20); var keyOf = __webpack_require__(22); var warning = __webpack_require__(14); var CHILDREN_PROP = keyOf({children: null}); /** * Sometimes you want to change the props of a child passed to you. Usually * this is to add a CSS class. * * @param {ReactElement} child child element you'd like to clone * @param {object} props props you'd like to modify. className and style will be * merged automatically. * @return {ReactElement} a clone of child with props merged in. */ function cloneWithProps(child, props) { if ("production" !== (undefined)) { ("production" !== (undefined) ? warning( !child.ref, 'You are calling cloneWithProps() on a child with a ref. This is ' + 'dangerous because you\'re creating a new child which will not be ' + 'added as a ref to its parent.' ) : null); } var newProps = ReactPropTransferer.mergeProps(props, child.props); // Use `child.props.children` if it is provided. if (!newProps.hasOwnProperty(CHILDREN_PROP) && child.props.hasOwnProperty(CHILDREN_PROP)) { newProps.children = child.props.children; } // The current API doesn't retain _owner and _context, which is why this // doesn't use ReactElement.cloneAndReplaceProps. return ReactElement.createElement(child.type, newProps); } module.exports = cloneWithProps; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ 'use strict'; var ReactContext = __webpack_require__(16); var ReactCurrentOwner = __webpack_require__(19); var assign = __webpack_require__(17); var warning = __webpack_require__(14); var RESERVED_PROPS = { key: true, ref: true }; /** * Warn for mutations. * * @internal * @param {object} object * @param {string} key */ function defineWarningProperty(object, key) { Object.defineProperty(object, key, { configurable: false, enumerable: true, get: function() { if (!this._store) { return null; } return this._store[key]; }, set: function(value) { ("production" !== (undefined) ? warning( false, 'Don\'t set the %s property of the React element. Instead, ' + 'specify the correct value when initially creating the element.', key ) : null); this._store[key] = value; } }); } /** * This is updated to true if the membrane is successfully created. */ var useMutationMembrane = false; /** * Warn for mutations. * * @internal * @param {object} element */ function defineMutationMembrane(prototype) { try { var pseudoFrozenProperties = { props: true }; for (var key in pseudoFrozenProperties) { defineWarningProperty(prototype, key); } useMutationMembrane = true; } catch (x) { // IE will fail on defineProperty } } /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {string|object} ref * @param {*} key * @param {*} props * @internal */ var ReactElement = function(type, key, ref, owner, context, props) { // Built-in properties that belong on the element this.type = type; this.key = key; this.ref = ref; // Record the component responsible for creating this element. this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. this._context = context; if ("production" !== (undefined)) { // The validation flag and props are currently mutative. We put them on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. this._store = {props: props, originalProps: assign({}, props)}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. try { Object.defineProperty(this._store, 'validated', { configurable: false, enumerable: false, writable: true }); } catch (x) { } this._store.validated = false; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(this); return; } } this.props = props; }; // We intentionally don't expose the function on the constructor property. // ReactElement should be indistinguishable from a plain object. ReactElement.prototype = { _isReactElement: true }; if ("production" !== (undefined)) { defineMutationMembrane(ReactElement.prototype); } ReactElement.createElement = function(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return new ReactElement( type, key, ref, ReactCurrentOwner.current, ReactContext.current, props ); }; ReactElement.createFactory = function(type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. <Foo />.type === Foo.type. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceProps = function(oldElement, newProps) { var newElement = new ReactElement( oldElement.type, oldElement.key, oldElement.ref, oldElement._owner, oldElement._context, newProps ); if ("production" !== (undefined)) { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; ReactElement.cloneElement = function(element, config, children) { var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return new ReactElement( element.type, key, ref, owner, element._context, props ); }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function(object) { // ReactTestUtils is often used outside of beforeEach where as React is // within it. This leads to two different instances of React on the same // page. To identify a element from a different React instance we use // a flag instead of an instanceof check. var isElement = !!(object && object._isReactElement); // if (isElement && !(object instanceof ReactElement)) { // This is an indicator that you're using multiple versions of React at the // same time. This will screw with ownership and stuff. Fix it, please. // TODO: We could possibly warn here. // } return isElement; }; module.exports = ReactElement; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule warning */ "use strict"; var emptyFunction = __webpack_require__(15); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("production" !== (undefined)) { warning = function(condition, format ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || /^[s\W]*$/.test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];}); console.warn(message); try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyFunction */ function makeEmptyFunction(arg) { return function() { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function() { return this; }; emptyFunction.thatReturnsArgument = function(arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactContext */ 'use strict'; var assign = __webpack_require__(17); var emptyObject = __webpack_require__(18); var warning = __webpack_require__(14); var didWarn = false; /** * Keeps track of the current context. * * The context is automatically passed down the component ownership hierarchy * and is accessible via `this.context` on ReactCompositeComponents. */ var ReactContext = { /** * @internal * @type {object} */ current: emptyObject, /** * Temporarily extends the current context while executing scopedCallback. * * A typical use case might look like * * render: function() { * var children = ReactContext.withContext({foo: 'foo'}, () => ( * * )); * return <div>{children}</div>; * } * * @param {object} newContext New context to merge into the existing context * @param {function} scopedCallback Callback to run with the new context * @return {ReactComponent|array<ReactComponent>} */ withContext: function(newContext, scopedCallback) { if ("production" !== (undefined)) { ("production" !== (undefined) ? warning( didWarn, 'withContext is deprecated and will be removed in a future version. ' + 'Use a wrapper component with getChildContext instead.' ) : null); didWarn = true; } var result; var previousContext = ReactContext.current; ReactContext.current = assign({}, previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; } module.exports = assign; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyObject */ "use strict"; var emptyObject = {}; if ("production" !== (undefined)) { Object.freeze(emptyObject); } module.exports = emptyObject; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. * * The depth indicate how many composite components are above this render level. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTransferer */ 'use strict'; var assign = __webpack_require__(17); var emptyFunction = __webpack_require__(15); var joinClasses = __webpack_require__(21); /** * Creates a transfer strategy that will merge prop values using the supplied * `mergeStrategy`. If a prop was previously unset, this just sets it. * * @param {function} mergeStrategy * @return {function} */ function createTransferStrategy(mergeStrategy) { return function(props, key, value) { if (!props.hasOwnProperty(key)) { props[key] = value; } else { props[key] = mergeStrategy(props[key], value); } }; } var transferStrategyMerge = createTransferStrategy(function(a, b) { // `merge` overrides the first object's (`props[key]` above) keys using the // second object's (`value`) keys. An object's style's existing `propA` would // get overridden. Flip the order here. return assign({}, b, a); }); /** * Transfer strategies dictate how props are transferred by `transferPropsTo`. * NOTE: if you add any more exceptions to this list you should be sure to * update `cloneWithProps()` accordingly. */ var TransferStrategies = { /** * Never transfer `children`. */ children: emptyFunction, /** * Transfer the `className` prop by merging them. */ className: createTransferStrategy(joinClasses), /** * Transfer the `style` prop (which is an object) by merging them. */ style: transferStrategyMerge }; /** * Mutates the first argument by transferring the properties from the second * argument. * * @param {object} props * @param {object} newProps * @return {object} */ function transferInto(props, newProps) { for (var thisKey in newProps) { if (!newProps.hasOwnProperty(thisKey)) { continue; } var transferStrategy = TransferStrategies[thisKey]; if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { transferStrategy(props, thisKey, newProps[thisKey]); } else if (!props.hasOwnProperty(thisKey)) { props[thisKey] = newProps[thisKey]; } } return props; } /** * ReactPropTransferer are capable of transferring props to another component * using a `transferPropsTo` method. * * @class ReactPropTransferer */ var ReactPropTransferer = { /** * Merge two props objects using TransferStrategies. * * @param {object} oldProps original props (they take precedence) * @param {object} newProps new props to merge in * @return {object} a new object containing both sets of props merged. */ mergeProps: function(oldProps, newProps) { return transferInto(assign({}, oldProps), newProps); } }; module.exports = ReactPropTransferer; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule joinClasses * @typechecks static-only */ 'use strict'; /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} classes * @return {string} */ function joinClasses(className/*, ... */) { if (!className) { className = ''; } var nextClass; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; if (nextClass) { className = (className ? className + ' ' : '') + nextClass; } } } return className; } module.exports = joinClasses; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without loosing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function ToObject(val) { if (val == null) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } module.exports = Object.assign || function (target, source) { var from; var keys; var to = ToObject(target); for (var s = 1; s < arguments.length; s++) { from = arguments[s]; keys = Object.keys(Object(from)); for (var i = 0; i < keys.length; i++) { to[keys[i]] = from[keys[i]]; } } return to; }; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var getDotCount = function getDotCount(spec) { var dots; dots = Math.ceil(spec.slideCount / spec.slidesToScroll); return dots; }; var Dots = _react2['default'].createClass({ displayName: 'Dots', clickHandler: function clickHandler(options, e) { // In Autoplay the focus stays on clicked button even after transition // to next slide. That only goes away by click somewhere outside e.preventDefault(); this.props.clickHandler(options); }, render: function render() { var _this = this; var dotCount = getDotCount({ slideCount: this.props.slideCount, slidesToScroll: this.props.slidesToScroll }); var dots = Array.apply(null, { length: dotCount }).map(function (x, i) { var className = (0, _classnames2['default'])({ 'slick-active': _this.props.currentSlide === i * _this.props.slidesToScroll }); var dotOptions = { message: 'dots', index: i, slidesToScroll: _this.props.slidesToScroll, currentSlide: _this.props.currentSlide }; return _react2['default'].createElement( 'li', { key: i, className: className }, _react2['default'].createElement( 'button', { onClick: _this.clickHandler.bind(_this, dotOptions) }, i ) ); }); return _react2['default'].createElement( 'ul', { className: this.props.dotsClass, style: { display: 'block' } }, dots ); } }); exports.Dots = Dots; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(10); var _classnames2 = _interopRequireDefault(_classnames); var PrevArrow = _react2['default'].createClass({ displayName: 'PrevArrow', clickHandler: function clickHandler(options, e) { e.preventDefault(); this.props.clickHandler(options, e); }, render: function render() { var prevClasses = { 'slick-prev': true }; var prevHandler = this.clickHandler.bind(this, { message: 'previous' }); if (!this.props.infinite && (this.props.currentSlide === 0 || this.props.slideCount <= this.props.slidesToShow)) { prevClasses['slick-disabled'] = true; prevHandler = null; } var prevArrowProps = { key: '0', ref: 'previous', 'data-role': 'none', className: (0, _classnames2['default'])(prevClasses), style: { display: 'block' }, onClick: prevHandler }; var prevArrow; if (this.props.prevArrow) { prevArrow = _react2['default'].createElement(this.props.prevArrow, prevArrowProps); } else { prevArrow = _react2['default'].createElement( 'button', _extends({ key: '0', type: 'button' }, prevArrowProps), ' Previous' ); } return prevArrow; } }); exports.PrevArrow = PrevArrow; var NextArrow = _react2['default'].createClass({ displayName: 'NextArrow', clickHandler: function clickHandler(options, e) { e.preventDefault(); this.props.clickHandler(options, e); }, render: function render() { var nextClasses = { 'slick-next': true }; var nextHandler = this.clickHandler.bind(this, { message: 'next' }); if (!this.props.infinite) { if (this.props.centerMode && this.props.currentSlide >= this.props.slideCount - 1) { nextClasses['slick-disabled'] = true; nextHandler = null; } else { if (this.props.currentSlide >= this.props.slideCount - this.props.slidesToShow) { nextClasses['slick-disabled'] = true; nextHandler = null; } } if (this.props.slideCount <= this.props.slidesToShow) { nextClasses['slick-disabled'] = true; nextHandler = null; } } var nextArrowProps = { key: '1', ref: 'next', 'data-role': 'none', className: (0, _classnames2['default'])(nextClasses), style: { display: 'block' }, onClick: nextHandler }; var nextArrow; if (this.props.nextArrow) { nextArrow = _react2['default'].createElement(this.props.nextArrow, nextArrowProps); } else { nextArrow = _react2['default'].createElement( 'button', _extends({ key: '1', type: 'button' }, nextArrowProps), ' Next' ); } return nextArrow; } }); exports.NextArrow = NextArrow; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { var canUseDOM = __webpack_require__(27); var enquire = canUseDOM && __webpack_require__(28); var json2mq = __webpack_require__(2); var ResponsiveMixin = { media: function (query, handler) { query = json2mq(query); if (typeof handler === 'function') { handler = { match: handler }; } enquire.register(query, handler); // Queue the handlers to unregister them at unmount if (! this._responsiveMediaHandlers) { this._responsiveMediaHandlers = []; } this._responsiveMediaHandlers.push({query: query, handler: handler}); }, componentWillUnmount: function () { this._responsiveMediaHandlers.forEach(function(obj) { enquire.unregister(obj.query, obj.handler); }); } }; module.exports = ResponsiveMixin; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); module.exports = canUseDOM; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! * enquire.js v2.1.1 - Awesome Media Queries in JavaScript * Copyright (c) 2014 Nick Williams - http://wicky.nillia.ms/enquire.js * License: MIT (http://www.opensource.org/licenses/mit-license.php) */ ;(function (name, context, factory) { var matchMedia = window.matchMedia; if (typeof module !== 'undefined' && module.exports) { module.exports = factory(matchMedia); } else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return (context[name] = factory(matchMedia)); }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { context[name] = factory(matchMedia); } }('enquire', this, function (matchMedia) { 'use strict'; /*jshint unused:false */ /** * Helper function for iterating over a collection * * @param collection * @param fn */ function each(collection, fn) { var i = 0, length = collection.length, cont; for(i; i < length; i++) { cont = fn(collection[i], i); if(cont === false) { break; //allow early exit } } } /** * Helper function for determining whether target object is an array * * @param target the object under test * @return {Boolean} true if array, false otherwise */ function isArray(target) { return Object.prototype.toString.apply(target) === '[object Array]'; } /** * Helper function for determining whether target object is a function * * @param target the object under test * @return {Boolean} true if function, false otherwise */ function isFunction(target) { return typeof target === 'function'; } /** * Delegate to handle a media query being matched and unmatched. * * @param {object} options * @param {function} options.match callback for when the media query is matched * @param {function} [options.unmatch] callback for when the media query is unmatched * @param {function} [options.setup] one-time callback triggered the first time a query is matched * @param {boolean} [options.deferSetup=false] should the setup callback be run immediately, rather than first time query is matched? * @constructor */ function QueryHandler(options) { this.options = options; !options.deferSetup && this.setup(); } QueryHandler.prototype = { /** * coordinates setup of the handler * * @function */ setup : function() { if(this.options.setup) { this.options.setup(); } this.initialised = true; }, /** * coordinates setup and triggering of the handler * * @function */ on : function() { !this.initialised && this.setup(); this.options.match && this.options.match(); }, /** * coordinates the unmatch event for the handler * * @function */ off : function() { this.options.unmatch && this.options.unmatch(); }, /** * called when a handler is to be destroyed. * delegates to the destroy or unmatch callbacks, depending on availability. * * @function */ destroy : function() { this.options.destroy ? this.options.destroy() : this.off(); }, /** * determines equality by reference. * if object is supplied compare options, if function, compare match callback * * @function * @param {object || function} [target] the target for comparison */ equals : function(target) { return this.options === target || this.options.match === target; } }; /** * Represents a single media query, manages it's state and registered handlers for this query * * @constructor * @param {string} query the media query string * @param {boolean} [isUnconditional=false] whether the media query should run regardless of whether the conditions are met. Primarily for helping older browsers deal with mobile-first design */ function MediaQuery(query, isUnconditional) { this.query = query; this.isUnconditional = isUnconditional; this.handlers = []; this.mql = matchMedia(query); var self = this; this.listener = function(mql) { self.mql = mql; self.assess(); }; this.mql.addListener(this.listener); } MediaQuery.prototype = { /** * add a handler for this query, triggering if already active * * @param {object} handler * @param {function} handler.match callback for when query is activated * @param {function} [handler.unmatch] callback for when query is deactivated * @param {function} [handler.setup] callback for immediate execution when a query handler is registered * @param {boolean} [handler.deferSetup=false] should the setup callback be deferred until the first time the handler is matched? */ addHandler : function(handler) { var qh = new QueryHandler(handler); this.handlers.push(qh); this.matches() && qh.on(); }, /** * removes the given handler from the collection, and calls it's destroy methods * * @param {object || function} handler the handler to remove */ removeHandler : function(handler) { var handlers = this.handlers; each(handlers, function(h, i) { if(h.equals(handler)) { h.destroy(); return !handlers.splice(i,1); //remove from array and exit each early } }); }, /** * Determine whether the media query should be considered a match * * @return {Boolean} true if media query can be considered a match, false otherwise */ matches : function() { return this.mql.matches || this.isUnconditional; }, /** * Clears all handlers and unbinds events */ clear : function() { each(this.handlers, function(handler) { handler.destroy(); }); this.mql.removeListener(this.listener); this.handlers.length = 0; //clear array }, /* * Assesses the query, turning on all handlers if it matches, turning them off if it doesn't match */ assess : function() { var action = this.matches() ? 'on' : 'off'; each(this.handlers, function(handler) { handler[action](); }); } }; /** * Allows for registration of query handlers. * Manages the query handler's state and is responsible for wiring up browser events * * @constructor */ function MediaQueryDispatch () { if(!matchMedia) { throw new Error('matchMedia not present, legacy browsers require a polyfill'); } this.queries = {}; this.browserIsIncapable = !matchMedia('only all').matches; } MediaQueryDispatch.prototype = { /** * Registers a handler for the given media query * * @param {string} q the media query * @param {object || Array || Function} options either a single query handler object, a function, or an array of query handlers * @param {function} options.match fired when query matched * @param {function} [options.unmatch] fired when a query is no longer matched * @param {function} [options.setup] fired when handler first triggered * @param {boolean} [options.deferSetup=false] whether setup should be run immediately or deferred until query is first matched * @param {boolean} [shouldDegrade=false] whether this particular media query should always run on incapable browsers */ register : function(q, options, shouldDegrade) { var queries = this.queries, isUnconditional = shouldDegrade && this.browserIsIncapable; if(!queries[q]) { queries[q] = new MediaQuery(q, isUnconditional); } //normalise to object in an array if(isFunction(options)) { options = { match : options }; } if(!isArray(options)) { options = [options]; } each(options, function(handler) { queries[q].addHandler(handler); }); return this; }, /** * unregisters a query and all it's handlers, or a specific handler for a query * * @param {string} q the media query to target * @param {object || function} [handler] specific handler to unregister */ unregister : function(q, handler) { var query = this.queries[q]; if(query) { if(handler) { query.removeHandler(handler); } else { query.clear(); delete this.queries[q]; } } return this; } }; return new MediaQueryDispatch(); })); /***/ } /******/ ]) }); ;
maruilian11/cdnjs
ajax/libs/react-slick/0.6.0/react-slick.js
JavaScript
mit
61,015
/*! * Bootstrap-select v1.6.3 (http://silviomoreto.github.io/bootstrap-select) * * Copyright 2013-2015 bootstrap-select * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) */ (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Niets geselecteerd', noneResultsText: 'Geen resultaten gevonden voor {0}', countSelectedText: '{0} van {1} geselecteerd', maxOptionsText: ['Limiet bereikt ({n} {var} max)', 'Groep limiet bereikt ({n} {var} max)', ['items', 'item']], multipleSeparator: ', ' }; })(jQuery);
jhonrsalcedo/sitio
wp-content/themes/viviendas/assets/libraries/bootstrap-select/dist/js/i18n/defaults-nl_NL.js
JavaScript
gpl-2.0
582
import {has, isArray} from "./util" import {SourceLocation} from "./locutil" // A second optional argument can be given to further configure // the parser process. These options are recognized: export const defaultOptions = { // `ecmaVersion` indicates the ECMAScript version to parse. Must // be either 3, or 5, or 6. This influences support for strict // mode, the set of reserved words, support for getters and // setters and other features. The default is 6. ecmaVersion: 6, // Source type ("script" or "module") for different semantics sourceType: "script", // `onInsertedSemicolon` can be a callback that will be called // when a semicolon is automatically inserted. It will be passed // th position of the comma as an offset, and if `locations` is // enabled, it is given the location as a `{line, column}` object // as second argument. onInsertedSemicolon: null, // `onTrailingComma` is similar to `onInsertedSemicolon`, but for // trailing commas. onTrailingComma: null, // By default, reserved words are only enforced if ecmaVersion >= 5. // Set `allowReserved` to a boolean value to explicitly turn this on // an off. When this option has the value "never", reserved words // and keywords can also not be used as property names. allowReserved: null, // When enabled, a return at the top level is not considered an // error. allowReturnOutsideFunction: false, // When enabled, import/export statements are not constrained to // appearing at the top of the program. allowImportExportEverywhere: false, // When enabled, hashbang directive in the beginning of file // is allowed and treated as a line comment. allowHashBang: false, // When `locations` is on, `loc` properties holding objects with // `start` and `end` properties in `{line, column}` form (with // line being 1-based and column 0-based) will be attached to the // nodes. locations: false, // A function can be passed as `onToken` option, which will // cause Acorn to call that function with object in the same // format as tokens returned from `tokenizer().getToken()`. Note // that you are not allowed to call the parser from the // callback—that will corrupt its internal state. onToken: null, // A function can be passed as `onComment` option, which will // cause Acorn to call that function with `(block, text, start, // end)` parameters whenever a comment is skipped. `block` is a // boolean indicating whether this is a block (`/* */`) comment, // `text` is the content of the comment, and `start` and `end` are // character offsets that denote the start and end of the comment. // When the `locations` option is on, two more parameters are // passed, the full `{line, column}` locations of the start and // end of the comments. Note that you are not allowed to call the // parser from the callback—that will corrupt its internal state. onComment: null, // Nodes have their start and end characters offsets recorded in // `start` and `end` properties (directly on the node, rather than // the `loc` object, which holds line/column data. To also add a // [semi-standardized][range] `range` property holding a `[start, // end]` array with the same numbers, set the `ranges` option to // `true`. // // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 ranges: false, // It is possible to parse multiple files into a single AST by // passing the tree produced by parsing the first file as // `program` option in subsequent parses. This will add the // toplevel forms of the parsed file to the `Program` (top) node // of an existing parse tree. program: null, // When `locations` is on, you can pass this to record the source // file in every node's `loc` object. sourceFile: null, // This value, if given, is stored in every node, whether // `locations` is on or off. directSourceFile: null, // When enabled, parenthesized expressions are represented by // (non-standard) ParenthesizedExpression nodes preserveParens: false, plugins: {} } // Interpret and default an options object export function getOptions(opts) { let options = {} for (let opt in defaultOptions) options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt] if (options.allowReserved == null) options.allowReserved = options.ecmaVersion < 5 if (isArray(options.onToken)) { let tokens = options.onToken options.onToken = (token) => tokens.push(token) } if (isArray(options.onComment)) options.onComment = pushComment(options, options.onComment) return options } function pushComment(options, array) { return function (block, text, start, end, startLoc, endLoc) { let comment = { type: block ? 'Block' : 'Line', value: text, start: start, end: end } if (options.locations) comment.loc = new SourceLocation(this, startLoc, endLoc) if (options.ranges) comment.range = [start, end] array.push(comment) } }
hellokidder/js-studying
微信小程序/wxtest/node_modules/acorn-jsx/node_modules/acorn/src/options.js
JavaScript
mit
5,026
function thisIsAFunctionWithAVeryLongNameAndWayTooManyParameters(thisIsTheFirstParameter, andThisOneIsRelatedToIt, butNotThisOne, andNeitherThis, inFactThereArentThatManyParameters) { throw null; }
lokiiart/upali-mobile
www/frontend/node_modules/babel-plugin-syntax-trailing-function-commas/test/fixtures/trailing-function-commas/declaration/expected.js
JavaScript
gpl-3.0
200
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * @providesModule ReactCSSTransitionGroupChild */ 'use strict'; var React = require('./React'); var ReactDOM = require('./ReactDOM'); var CSSCore = require('fbjs/lib/CSSCore'); var ReactTransitionEvents = require('./ReactTransitionEvents'); var onlyChild = require('./onlyChild'); // We don't remove the element from the DOM until we receive an animationend or // transitionend event. If the user screws up and forgets to add an animation // their node will be stuck in the DOM forever, so we detect if an animation // does not start and if it doesn't, we just call the end listener immediately. var TICK = 17; var ReactCSSTransitionGroupChild = React.createClass({ displayName: 'ReactCSSTransitionGroupChild', propTypes: { name: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.shape({ enter: React.PropTypes.string, leave: React.PropTypes.string, active: React.PropTypes.string }), React.PropTypes.shape({ enter: React.PropTypes.string, enterActive: React.PropTypes.string, leave: React.PropTypes.string, leaveActive: React.PropTypes.string, appear: React.PropTypes.string, appearActive: React.PropTypes.string })]).isRequired, // Once we require timeouts to be specified, we can remove the // boolean flags (appear etc.) and just accept a number // or a bool for the timeout flags (appearTimeout etc.) appear: React.PropTypes.bool, enter: React.PropTypes.bool, leave: React.PropTypes.bool, appearTimeout: React.PropTypes.number, enterTimeout: React.PropTypes.number, leaveTimeout: React.PropTypes.number }, transition: function (animationType, finishCallback, userSpecifiedDelay) { var node = ReactDOM.findDOMNode(this); if (!node) { if (finishCallback) { finishCallback(); } return; } var className = this.props.name[animationType] || this.props.name + '-' + animationType; var activeClassName = this.props.name[animationType + 'Active'] || className + '-active'; var timeout = null; var endListener = function (e) { if (e && e.target !== node) { return; } clearTimeout(timeout); CSSCore.removeClass(node, className); CSSCore.removeClass(node, activeClassName); ReactTransitionEvents.removeEndEventListener(node, endListener); // Usually this optional callback is used for informing an owner of // a leave animation and telling it to remove the child. if (finishCallback) { finishCallback(); } }; CSSCore.addClass(node, className); // Need to do this to actually trigger a transition. this.queueClass(activeClassName); // If the user specified a timeout delay. if (userSpecifiedDelay) { // Clean-up the animation after the specified delay timeout = setTimeout(endListener, userSpecifiedDelay); this.transitionTimeouts.push(timeout); } else { // DEPRECATED: this listener will be removed in a future version of react ReactTransitionEvents.addEndEventListener(node, endListener); } }, queueClass: function (className) { this.classNameQueue.push(className); if (!this.timeout) { this.timeout = setTimeout(this.flushClassNameQueue, TICK); } }, flushClassNameQueue: function () { if (this.isMounted()) { this.classNameQueue.forEach(CSSCore.addClass.bind(CSSCore, ReactDOM.findDOMNode(this))); } this.classNameQueue.length = 0; this.timeout = null; }, componentWillMount: function () { this.classNameQueue = []; this.transitionTimeouts = []; }, componentWillUnmount: function () { if (this.timeout) { clearTimeout(this.timeout); } this.transitionTimeouts.forEach(function (timeout) { clearTimeout(timeout); }); }, componentWillAppear: function (done) { if (this.props.appear) { this.transition('appear', done, this.props.appearTimeout); } else { done(); } }, componentWillEnter: function (done) { if (this.props.enter) { this.transition('enter', done, this.props.enterTimeout); } else { done(); } }, componentWillLeave: function (done) { if (this.props.leave) { this.transition('leave', done, this.props.leaveTimeout); } else { done(); } }, render: function () { return onlyChild(this.props.children); } }); module.exports = ReactCSSTransitionGroupChild;
emineKoc/WiseWit
wisewit_front_end/node_modules/react/lib/ReactCSSTransitionGroupChild.js
JavaScript
gpl-3.0
4,805
var _ = require('lodash'); /** * formats variables for handlebars in multi-post contexts. * If extraValues are available, they are merged in the final value * @return {Object} containing page variables */ function formatPageResponse(result) { var response = { posts: result.posts, pagination: result.meta.pagination }; _.each(result.data, function (data, name) { if (data.meta) { // Move pagination to be a top level key response[name] = data; response[name].pagination = data.meta.pagination; delete response[name].meta; } else { // This is a single object, don't wrap it in an array response[name] = data[0]; } }); return response; } /** * similar to formatPageResponse, but for single post pages * @return {Object} containing page variables */ function formatResponse(post) { return { post: post }; } module.exports = { channel: formatPageResponse, single: formatResponse };
norsasono/openshift-ghost-starter
node_modules/ghost/core/server/controllers/frontend/format-response.js
JavaScript
mit
1,048
'use strict'; var times = require('../times'); var moment = require('moment'); function init (ctx) { var translate = ctx.language.translate; var basal = { name: 'basal' , label: 'Basal Profile' , pluginType: 'pill-minor' }; basal.setProperties = function setProperties (sbx) { if (hasRequiredInfo(sbx)) { var profile = sbx.data.profile; var current = profile.getTempBasal(sbx.time); var tempMark = ''; tempMark += current.treatment ? 'T' : ''; tempMark += current.combobolustreatment ? 'C' : ''; tempMark += tempMark ? ': ' : ''; sbx.offerProperty('basal', function setBasal() { return { display: tempMark + current.totalbasal.toFixed(3) + 'U' , current: current }; }); } }; function hasRequiredInfo (sbx) { if (!sbx.data.profile) { return false; } if (!sbx.data.profile.hasData()) { console.warn('For the Basal plugin to function you need a treatment profile'); return false; } if (!sbx.data.profile.getBasal()) { console.warn('For the Basal plugin to function you need a basal profile'); return false; } return true; } basal.updateVisualisation = function updateVisualisation (sbx) { if (!hasRequiredInfo(sbx)) { return; } var profile = sbx.data.profile; var prop = sbx.properties.basal; var basalValue = prop && prop.current; var tzMessage = profile.getTimezone() ? profile.getTimezone() : 'Timezone not set in profile'; var info = [{label: translate('Current basal'), value: prop.display} , {label: translate('Sensitivity'), value: profile.getSensitivity(sbx.time) + ' ' + sbx.settings.units + ' / U'} , {label: translate('Current Carb Ratio'), value: '1 U / ' + profile.getCarbRatio(sbx.time) + 'g'} , {label: translate('Basal timezone'), value: tzMessage} , {label: '------------', value: ''} , {label: translate('Active profile'), value: profile.activeProfileToTime(sbx.time)} ]; var tempText, remaining; if (basalValue.treatment) { tempText = basalValue.treatment.percent ? (basalValue.treatment.percent > 0 ? '+' : '') + basalValue.treatment.percent + '%' : !isNaN(basalValue.treatment.absolute) ? basalValue.treatment.absolute + 'U/h' : ''; remaining = parseInt(basalValue.treatment.duration - times.msecs(sbx.time - basalValue.treatment.mills).mins); info.push({label: '------------', value: ''}); info.push({label: translate('Active temp basal'), value: tempText}); info.push({label: translate('Active temp basal start'), value: new Date(basalValue.treatment.mills).toLocaleString()}); info.push({label: translate('Active temp basal duration'), value: parseInt(basalValue.treatment.duration) + ' ' + translate('mins')}); info.push({label: translate('Active temp basal remaining'), value: remaining + ' ' + translate('mins')}); info.push({label: translate('Basal profile value'), value: basalValue.basal.toFixed(3) + ' U'}); } if (basalValue.combobolustreatment) { tempText = (basalValue.combobolustreatment.relative ? '+' + basalValue.combobolustreatment.relative + 'U/h' : ''); remaining = parseInt(basalValue.combobolustreatment.duration - times.msecs(sbx.time - basalValue.combobolustreatment.mills).mins); info.push({label: '------------', value: ''}); info.push({label: translate('Active combo bolus'), value: tempText}); info.push({label: translate('Active combo bolus start'), value: new Date(basalValue.combobolustreatment.mills).toLocaleString()}); info.push({label: translate('Active combo bolus duration'), value: parseInt(basalValue.combobolustreatment.duration) + ' ' + translate('mins')}); info.push({label: translate('Active combo bolus remaining'), value: remaining + ' ' + translate('mins')}); } sbx.pluginBase.updatePillText(basal, { value: prop.display , label: translate('BASAL') , info: info }); }; function basalMessage(slots, sbx) { var basalValue = sbx.data.profile.getTempBasal(sbx.time); var response = 'Unable to determine current basal'; var preamble = ''; if (basalValue.treatment) { preamble = (slots && slots.pwd && slots.pwd.value) ? translate('alexaPreamble3person', { params: [ slots.pwd.value ] }) : translate('alexaPreamble'); var minutesLeft = moment(basalValue.treatment.endmills).from(moment(sbx.time)); response = translate('alexaBasalTemp', { params: [ preamble, basalValue.totalbasal, minutesLeft ] }); } else { preamble = (slots && slots.pwd && slots.pwd.value) ? translate('alexaPreamble3person', { params: [ slots.pwd.value ] }) : translate('alexaPreamble'); response = translate('alexaBasal', { params: [ preamble, basalValue.totalbasal ] }); } return response; } function alexaRollupCurrentBasalHandler (slots, sbx, callback) { callback(null, {results: basalMessage(slots, sbx), priority: 1}); } function alexaCurrentBasalhandler (next, slots, sbx) { next('Current Basal', basalMessage(slots, sbx)); } basal.alexa = { rollupHandlers: [{ rollupGroup: 'Status' , rollupName: 'current basal' , rollupHandler: alexaRollupCurrentBasalHandler }], intentHandlers: [{ intent: 'MetricNow' , routableSlot:'metric' , slots:['basal', 'current basal'] , intentHandler: alexaCurrentBasalhandler }] }; return basal; } module.exports = init;
GarthDB/cgm-remote-monitor
lib/plugins/basalprofile.js
JavaScript
agpl-3.0
5,961
var baseIndexOf = require('./_baseIndexOf'), toInteger = require('./toInteger'); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } module.exports = indexOf;
ElvisLouis/code
work/project/Edison/elvis/work/js/node_modules/async/node_modules/lodash/indexOf.js
JavaScript
gpl-2.0
1,232
(function(){ if ( (typeof self === 'undefined' || !self.Prism) && (typeof global === 'undefined' || !global.Prism) ) { return; } var options = { classMap: {} }; Prism.plugins.customClass = { map: function map(cm) { options.classMap = cm; }, prefix: function prefix(string) { options.prefixString = string; } } Prism.hooks.add('wrap', function (env) { if (!options.classMap && !options.prefixString) { return; } env.classes = env.classes.map(function(c) { return (options.prefixString || '') + (options.classMap[c] || c); }); }); })();
ihmcrobotics/ihmc-realtime
websitedocs/website/node_modules/prismjs/plugins/custom-class/prism-custom-class.js
JavaScript
apache-2.0
559
/* YUI 3.17.1 (build 0eb5a52) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {EventHandle} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {EventHandle} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {EventHandle} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor === DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor === DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} defaults configuration object. * @class CustomEvent * @constructor */ /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ Y.CustomEvent = function(type, defaults) { this._kds = Y.CustomEvent.keepDeprecatedSubs; this.id = Y.guid(); this.type = type; this.silent = this.logSystem = (type === YUI_LOG); if (this._kds) { /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ /** * 'After' subscribers * @property afters * @type Subscriber {} * @deprecated */ this.subscribers = {}; this.afters = {}; } if (defaults) { mixConfigs(this, defaults, true); } }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ /** * This event has fired if true * * @property fired * @type boolean * @default false; */ /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ /** * Flag for the default function to execute only if the * firing event is the current target. This happens only * when using custom event delegation and setting the * flag to `true` mimics the behavior of event delegation * in the DOM. * * @property defaultTargetOnly * @type Boolean * @default false */ /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ signature : YUI3_SIGNATURE, /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ context : Y, /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ preventable : true, /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ bubbles : true, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = 0, a = 0, subs = this._subscribers, afters = this._afters, sib = this.sibling; if (subs) { s = subs.length; } if (afters) { a = afters.length; } if (sib) { subs = sib._subscribers; afters = sib._afters; if (subs) { s += subs.length; } if (afters) { a += afters.length; } } if (when) { return (when === 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var sibling = this.sibling, subs = this._subscribers, afters = this._afters, siblingSubs, siblingAfters; if (sibling) { siblingSubs = sibling._subscribers; siblingAfters = sibling._afters; } if (siblingSubs) { if (subs) { subs = subs.concat(siblingSubs); } else { subs = siblingSubs.concat(); } } else { if (subs) { subs = subs.concat(); } else { subs = []; } } if (siblingAfters) { if (afters) { afters = afters.concat(siblingAfters); } else { afters = siblingAfters.concat(); } } else { if (afters) { afters = afters.concat(); } else { afters = []; } } return [subs, afters]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when), firedWith; if (this.fireOnce && this.fired) { firedWith = this.firedWith; // It's a little ugly for this to know about facades, // but given the current breakup, not much choice without // moving a whole lot of stuff around. if (this.emitFacade && this._addFacadeToArgs) { this._addFacadeToArgs(firedWith); } if (this.async) { setTimeout(Y.bind(this._notify, this, s, firedWith), 0); } else { this._notify(s, firedWith); } } if (when === AFTER) { if (!this._afters) { this._afters = []; } this._afters.push(s); } else { if (!this._subscribers) { this._subscribers = []; } this._subscribers.push(s); } if (this._kds) { if (when === AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {Number} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; if (subs) { for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } } if (afters) { for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { // push is the fastest way to go from arguments to arrays // for most browsers currently // http://jsperf.com/push-vs-concat-vs-slice/2 var args = []; args.push.apply(args, arguments); return this._fire(args); }, /** * Private internal implementation for `fire`, which is can be used directly by * `EventTarget` and other event module classes which have already converted from * an `arguments` list to an array, to avoid the repeated overhead. * * @method _fire * @private * @param {Array} args The array of arguments passed to be passed to handlers. * @return {boolean} false if one of the subscribers returned false, true otherwise. */ _fire: function(args) { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } if (this.broadcast) { this._broadcast(args); } return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped === 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast === 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {Number} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {Number} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; } if (subs) { i = YArray.indexOf(subs, s, 0); if (s && subs[i] === s) { subs.splice(i, 1); } } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.guid(); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn === fn) && this.context === context); } else { return (this.fn === fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {Number} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = function(type, pre) { if (!pre || !type || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }, /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t === '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var etState = this._yuievt, etConfig; if (!etState) { etState = this._yuievt = { events: {}, // PERF: Not much point instantiating lazily. We're bound to have events targets: null, // PERF: Instantiate lazily, if user actually adds target, config: { host: this, context: this }, chain: Y.config.chain }; } etConfig = etState.config; if (opts) { mixConfigs(etConfig, opts, true); if (opts.chain !== undefined) { etState.chain = opts.chain; } if (opts.prefix) { etConfig.prefix = opts.prefix; } } }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre] The prefix. Defaults to this._yuievt.config.prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); // TODO: More robust regex, accounting for category if (type.indexOf("*:") !== -1) { this._hasSiblings = true; } } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var ret, etState = this._yuievt, etConfig = etState.config, pre = etConfig.prefix; if (typeof type === "string") { if (pre) { type = _getType(type, pre); } ret = this._publish(type, etConfig, opts); } else { ret = {}; Y.each(type, function(v, k) { if (pre) { k = _getType(k, pre); } ret[k] = this._publish(k, etConfig, v || opts); }, this); } return ret; }, /** * Returns the fully qualified type, given a short type string. * That is, returns "foo:bar" when given "bar" if "foo" is the configured prefix. * * NOTE: This method, unlike _getType, does no checking of the value passed in, and * is designed to be used with the low level _publish() method, for critical path * implementations which need to fast-track publish for performance reasons. * * @method _getFullType * @private * @param {String} type The short type to prefix * @return {String} The prefixed type, if a prefix is set, otherwise the type passed in */ _getFullType : function(type) { var pre = this._yuievt.config.prefix; if (pre) { return pre + PREFIX_DELIMITER + type; } else { return type; } }, /** * The low level event publish implementation. It expects all the massaging to have been done * outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast * path publish, which can be used by critical code paths to improve performance. * * @method _publish * @private * @param {String} fullType The prefixed type of the event to publish. * @param {Object} etOpts The EventTarget specific configuration to mix into the published event. * @param {Object} ceOpts The publish specific configuration to mix into the published event. * @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will * be the default `CustomEvent` instance, and can be configured independently. */ _publish : function(fullType, etOpts, ceOpts) { var ce, etState = this._yuievt, etConfig = etState.config, host = etConfig.host, context = etConfig.context, events = etState.events; ce = events[fullType]; // PERF: Hate to pull the check out of monitor, but trying to keep critical path tight. if ((etConfig.monitored && !ce) || (ce && ce.monitored)) { this._monitor('publish', fullType, { args: arguments }); } if (!ce) { // Publish event ce = events[fullType] = new Y.CustomEvent(fullType, etOpts); if (!etOpts) { ce.host = host; ce.context = context; } } if (ceOpts) { mixConfigs(ce, ceOpts, true); } return ce; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {Boolean} True if the whole lifecycle of the event went through, * false if at any point the event propagation was halted. */ fire: function(type) { var typeIncluded = (typeof type === "string"), argCount = arguments.length, t = type, yuievt = this._yuievt, etConfig = yuievt.config, pre = etConfig.prefix, ret, ce, ce2, args; if (typeIncluded && argCount <= 3) { // PERF: Try to avoid slice/iteration for the common signatures // Most common if (argCount === 2) { args = [arguments[1]]; // fire("foo", {}) } else if (argCount === 3) { args = [arguments[1], arguments[2]]; // fire("foo", {}, opts) } else { args = []; // fire("foo") } } else { args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0)); } if (!typeIncluded) { t = (type && type.type); } if (pre) { t = _getType(t, pre); } ce = yuievt.events[t]; if (this._hasSiblings) { ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } } // PERF: trying to avoid function call, since this is a critical path if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { this._monitor('fire', (ce || t), { args: args }); } // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { if (ce2) { ce.sibling = ce2; } ret = ce._fire(args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); ce2 = this.getEvent(type, true); if (ce2) { ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '3.17.1', {"requires": ["oop"]});
extend1994/cdnjs
ajax/libs/yui/3.17.1/event-custom-base/event-custom-base-debug.js
JavaScript
mit
75,885
/** * Copyright 2011 Rackspace * * 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. * */ var sprintf = require('./sprintf').sprintf; var utils = require('./utils'); var SyntaxError = require('./errors').SyntaxError; var _cache = {}; var RE = new RegExp( "(" + "'[^']*'|\"[^\"]*\"|" + "::|" + "//?|" + "\\.\\.|" + "\\(\\)|" + "[/.*:\\[\\]\\(\\)@=])|" + "((?:\\{[^}]+\\})?[^/\\[\\]\\(\\)@=\\s]+)|" + "\\s+", 'g' ); var xpath_tokenizer = utils.findall.bind(null, RE); function prepare_tag(next, token) { var tag = token[0]; function select(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; elem._children.forEach(function(e) { if (e.tag === tag) { rv.push(e); } }); } return rv; } return select; } function prepare_star(next, token) { function select(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; elem._children.forEach(function(e) { rv.push(e); }); } return rv; } return select; } function prepare_dot(next, token) { function select(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; rv.push(elem); } return rv; } return select; } function prepare_iter(next, token) { var tag; token = next(); if (token[1] === '*') { tag = '*'; } else if (!token[1]) { tag = token[0] || ''; } else { throw new SyntaxError(token); } function select(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; elem.iter(tag, function(e) { if (e !== elem) { rv.push(e); } }); } return rv; } return select; } function prepare_dot_dot(next, token) { function select(context, result) { var i, len, elem, rv = [], parent_map = context.parent_map; if (!parent_map) { context.parent_map = parent_map = {}; context.root.iter(null, function(p) { p._children.forEach(function(e) { parent_map[e] = p; }); }); } for (i = 0, len = result.length; i < len; i++) { elem = result[i]; if (parent_map.hasOwnProperty(elem)) { rv.push(parent_map[elem]); } } return rv; } return select; } function prepare_predicate(next, token) { var tag, key, value, select; token = next(); if (token[1] === '@') { // attribute token = next(); if (token[1]) { throw new SyntaxError(token, 'Invalid attribute predicate'); } key = token[0]; token = next(); if (token[1] === ']') { select = function(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; if (elem.get(key)) { rv.push(elem); } } return rv; }; } else if (token[1] === '=') { value = next()[1]; if (value[0] === '"' || value[value.length - 1] === '\'') { value = value.slice(1, value.length - 1); } else { throw new SyntaxError(token, 'Ivalid comparison target'); } token = next(); select = function(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; if (elem.get(key) === value) { rv.push(elem); } } return rv; }; } if (token[1] !== ']') { throw new SyntaxError(token, 'Invalid attribute predicate'); } } else if (!token[1]) { tag = token[0] || ''; token = next(); if (token[1] !== ']') { throw new SyntaxError(token, 'Invalid node predicate'); } select = function(context, result) { var i, len, elem, rv = []; for (i = 0, len = result.length; i < len; i++) { elem = result[i]; if (elem.find(tag)) { rv.push(elem); } } return rv; }; } else { throw new SyntaxError(null, 'Invalid predicate'); } return select; } var ops = { "": prepare_tag, "*": prepare_star, ".": prepare_dot, "..": prepare_dot_dot, "//": prepare_iter, "[": prepare_predicate, }; function _SelectorContext(root) { this.parent_map = null; this.root = root; } function findall(elem, path) { var selector, result, i, len, token, value, select, context; if (_cache.hasOwnProperty(path)) { selector = _cache[path]; } else { // TODO: Use smarter cache purging approach if (Object.keys(_cache).length > 100) { _cache = {}; } if (path.charAt(0) === '/') { throw new SyntaxError(null, 'Cannot use absolute path on element'); } result = xpath_tokenizer(path); selector = []; function getToken() { return result.shift(); } token = getToken(); while (true) { var c = token[1] || ''; value = ops[c](getToken, token); if (!value) { throw new SyntaxError(null, sprintf('Invalid path: %s', path)); } selector.push(value); token = getToken(); if (!token) { break; } else if (token[1] === '/') { token = getToken(); } if (!token) { break; } } _cache[path] = selector; } // Execute slector pattern result = [elem]; context = new _SelectorContext(elem); for (i = 0, len = selector.length; i < len; i++) { select = selector[i]; result = select(context, result); } return result || []; } function find(element, path) { var resultElements = findall(element, path); if (resultElements && resultElements.length > 0) { return resultElements[0]; } return null; } function findtext(element, path, defvalue) { var resultElements = findall(element, path); if (resultElements && resultElements.length > 0) { return resultElements[0].text; } return defvalue; } exports.find = find; exports.findall = findall; exports.findtext = findtext;
zendey/Zendey
zendey/platforms/android/cordova/node_modules/elementtree/lib/elementpath.js
JavaScript
gpl-3.0
6,742
var now = require('../time/now') var timeout = require('./timeout') var append = require('../array/append') // ensure a minimum delay for callbacks function awaitDelay (fn, delay) { var baseTime = now() + delay return function () { // ensure all browsers will execute it asynchronously (avoid hard // to catch errors) not using "0" because of old browsers and also // since new browsers increase the value to be at least "4" // http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout var ms = Math.max(baseTime - now(), 4) return timeout.apply(this, append([fn, ms, this], arguments)) } } module.exports = awaitDelay
akileez/toolz
src/function/awaitDelay.js
JavaScript
isc
694
import chai from 'chai'; import cas from 'chai-as-promised'; chai.use(cas); export default { expect: chai.expect };
romeovs/all
test/instrument.js
JavaScript
isc
121
'use strict'; var test = require('tap').test, _ = require('lodash'), parse = require('../../../lib/parsers/javascript'), inferMembership = require('../../../lib/infer/membership')(); function toComment(fn, file) { return parse({ file: file, source: fn instanceof Function ? '(' + fn.toString() + ')' : fn }); } function evaluate(fn, file) { return toComment(fn, file).map(inferMembership); } function Foo() {} function lend() {} test('inferMembership - explicit', function (t) { t.deepEqual(_.pick(evaluate(function () { /** * Test * @memberof Bar * @static */ Foo.bar = 0; })[0], ['memberof', 'scope']), { memberof: 'Bar', scope: 'static' }, 'explicit'); t.deepEqual(_.pick(evaluate(function () { /** Test */ Foo.bar = 0; })[0], ['memberof', 'scope']), { memberof: 'Foo', scope: 'static' }, 'implicit'); t.deepEqual(_.pick(evaluate(function () { /** Test */ Foo.prototype.bar = 0; })[0], ['memberof', 'scope']), { memberof: 'Foo', scope: 'instance' }, 'instance'); t.deepEqual(_.pick(evaluate(function () { /** Test */ Foo.bar.baz = 0; })[0], ['memberof', 'scope']), { memberof: 'Foo.bar', scope: 'static' }, 'compound'); t.deepEqual(_.pick(evaluate(function () { /** Test */ (0).baz = 0; })[0], ['memberof', 'scope']), { }, 'unknown'); t.deepEqual(_.pick(evaluate(function () { Foo.bar = { /** Test */ baz: 0 }; })[0], ['memberof', 'scope']), { memberof: 'Foo.bar', scope: 'static' }, 'static object assignment'); t.deepEqual(_.pick(evaluate(function () { Foo.prototype = { /** Test */ bar: 0 }; })[0], ['memberof', 'scope']), { memberof: 'Foo', scope: 'instance' }, 'instance object assignment'); t.deepEqual(_.pick(evaluate(function () { Foo.prototype = { /** * Test */ bar: function () {} }; })[0], ['memberof', 'scope']), { memberof: 'Foo', scope: 'instance' }, 'instance object assignment, function'); t.deepEqual(_.pick(evaluate(function () { var Foo = { /** Test */ baz: 0 }; return Foo; })[0], ['memberof', 'scope']), { memberof: 'Foo', scope: 'static' }, 'variable object assignment'); t.deepEqual(_.pick(evaluate(function () { var Foo = { /** Test */ baz: function () {} }; return Foo; })[0], ['memberof', 'scope']), { memberof: 'Foo', scope: 'static' }, 'variable object assignment, function'); t.deepEqual(_.pick(evaluate(function () { /** Test */ module.exports = function () {}; })[0], ['memberof', 'scope']), { memberof: 'module', scope: 'static' }, 'simple'); t.deepEqual(_.pick(evaluate(function () { lend(/** @lends Foo */{ /** Test */ bar: 0 }); })[1], ['memberof', 'scope']), { memberof: 'Foo', scope: 'static' }, 'lends, static'); t.deepEqual(_.pick(evaluate(function () { lend(/** @lends Foo */{ /** Test */ bar: function () {} }); })[1], ['memberof', 'scope']), { memberof: 'Foo', scope: 'static' }, 'inferMembership - lends, static, function'); t.deepEqual(_.pick(evaluate(function () { lend(/** @lends Foo.prototype */{ /** Test */ bar: 0 }); })[1], ['memberof', 'scope']), { memberof: 'Foo', scope: 'instance' }); t.deepEqual(_.pick(evaluate(function () { lend(/** @lends Foo.prototype */{ /** Test */ bar: function () {} }); })[1], ['memberof', 'scope']), { memberof: 'Foo', scope: 'instance' }, 'inferMembership - lends, instance, function'); t.deepEqual(_.pick(evaluate(function () { /** Foo */ function Foo() { /** Test */ function bar() {} return { bar: bar }; } })[1], ['memberof', 'scope']), { memberof: 'Foo', scope: 'static' }, 'inferMembership - revealing, static, function'); t.equal(evaluate(function () { lend(/** @lends Foo */{}); /** Test */ })[1].memberof, undefined, 'inferMembership - lends applies only to following object'); t.equal(evaluate(function () { lend(/** @lends Foo */{}); })[0], undefined, 'inferMembership - drops lends'); t.end(); }); test('inferMembership - exports', function (t) { t.equal(evaluate(function () { /** @module mod */ /** foo */ exports.foo = 1; })[1].memberof, 'mod'); t.equal(evaluate(function () { /** @module mod */ /** foo */ exports.foo = function () {}; })[1].memberof, 'mod'); t.equal(evaluate(function () { /** @module mod */ /** bar */ exports.foo.bar = 1; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ exports.foo = { /** bar */ bar: 1 }; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ exports.foo = { /** bar */ bar: function () {} }; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ /** bar */ exports.foo.prototype.bar = function () {}; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ exports.foo.prototype = { /** bar */ bar: function () {} }; })[1].memberof, 'mod.foo'); t.end(); }); test('inferMembership - module.exports', function (t) { t.equal(evaluate(function () { /** @module mod */ /** foo */ module.exports.foo = 1; })[1].memberof, 'mod'); t.equal(evaluate(function () { /** @module mod */ /** foo */ module.exports.foo = function () {}; })[1].memberof, 'mod'); t.equal(evaluate(function () { /** @module mod */ /** bar */ module.exports.foo.bar = 1; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ module.exports.foo = { /** bar */ bar: 1 }; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ module.exports.foo = { /** bar */ bar: function () {} }; })[1].memberof, 'mod.foo'); t.equal(evaluate(function () { /** @module mod */ /** bar */ module.exports.prototype.bar = function () {}; })[1].memberof, 'mod'); t.equal(evaluate(function () { /** @module mod */ module.exports.prototype = { /** bar */ bar: function () {} }; })[1].memberof, 'mod'); t.equal(evaluate(function () { /** * @module mod * @name exports */ module.exports = 1; })[0].memberof, undefined); t.equal(evaluate(function () { /** * @module mod * @name exports */ module.exports = function () {}; })[0].memberof, undefined); t.equal(evaluate(function () { /** @module mod */ module.exports = { /** foo */ foo: 1 }; })[1].memberof, 'mod'); t.end(); }); test('inferMembership - not module exports', function (t) { var result = evaluate(function () { /** * @module mod */ /** Test */ global.module.exports.foo = 1; }, '/path/mod.js'); t.equal(result.length, 2); t.notEqual(result[0].memberof, 'mod'); t.end(); }); test('inferMembership - anonymous @module', function (t) { var result = evaluate(function () { /** * @module */ /** Test */ exports.foo = 1; }, '/path/mod.js'); t.equal(result.length, 2); t.equal(result[1].memberof, 'mod'); t.end(); }); test('inferMembership - no @module', function (t) { var result = evaluate(function () { /** Test */ exports.foo = 1; }, '/path/mod.js'); t.equal(result.length, 1); t.equal(result[0].memberof, 'mod'); t.end(); });
researchgate/documentation
test/lib/infer/membership.js
JavaScript
isc
7,692
'use strict' const t = require('tap') const Parse = require('../lib/parse.js') const makeTar = require('./make-tar.js') const fs = require('fs') const path = require('path') const tardir = path.resolve(__dirname, 'fixtures/tars') const zlib = require('zlib') const MiniPass = require('minipass') const Header = require('../lib/header.js') const EE = require('events').EventEmitter t.test('fixture tests', t => { class ByteStream extends MiniPass { write (chunk) { for (let i = 0; i < chunk.length - 1; i++) super.write(chunk.slice(i, i + 1)) return super.write(chunk.slice(chunk.length - 1, chunk.length)) } } const trackEvents = (t, expect, p, slow) => { let ok = true let cursor = 0 p.on('entry', entry => { ok = ok && t.match(['entry', entry], expect[cursor++], entry.path) if (slow) setTimeout(_ => entry.resume()) else entry.resume() }) p.on('ignoredEntry', entry => { ok = ok && t.match(['ignoredEntry', entry], expect[cursor++], 'ignored: ' + entry.path) }) p.on('warn', (c, message, data) => { ok = ok && t.match(['warn', c, message], expect[cursor++], 'warn') }) p.on('nullBlock', _ => { ok = ok && t.match(['nullBlock'], expect[cursor++], 'null') }) p.on('error', er => { ok = ok && t.match(['error', er], expect[cursor++], 'error') }) p.on('meta', meta => { ok = ok && t.match(['meta', meta], expect[cursor++], 'meta') }) p.on('eof', _ => { ok = ok && t.match(['eof'], expect[cursor++], 'eof') }) p.on('end', _ => { ok = ok && t.match(['end'], expect[cursor++], 'end') t.end() }) } t.jobs = 4 const path = require('path') const parsedir = path.resolve(__dirname, 'fixtures/parse') const files = fs.readdirSync(tardir) const maxMetaOpt = [250, null] const filterOpt = [true, false] const strictOpt = [true, false] const runTest = (file, maxMeta, filter, strict) => { const tardata = fs.readFileSync(file) const base = path.basename(file, '.tar') t.test('file=' + base + '.tar' + ' maxmeta=' + maxMeta + ' filter=' + filter + ' strict=' + strict, t => { const o = (maxMeta ? '-meta-' + maxMeta : '') + (filter ? '-filter' : '') + (strict ? '-strict' : '') const tail = (o ? '-' + o : '') + '.json' const eventsFile = parsedir + '/' + base + tail const expect = require(eventsFile) t.test('one byte at a time', t => { const bs = new ByteStream() const opt = (maxMeta || filter || strict) ? { maxMetaEntrySize: maxMeta, filter: filter ? (path, entry) => entry.size % 2 !== 0 : null, strict: strict, } : null const bp = new Parse(opt) trackEvents(t, expect, bp) bs.pipe(bp) bs.end(tardata) }) t.test('all at once', t => { const p = new Parse({ maxMetaEntrySize: maxMeta, filter: filter ? (path, entry) => entry.size % 2 !== 0 : null, strict: strict, }) trackEvents(t, expect, p) p.end(tardata) }) t.test('gzipped all at once', t => { const p = new Parse({ maxMetaEntrySize: maxMeta, filter: filter ? (path, entry) => entry.size % 2 !== 0 : null, strict: strict, }) trackEvents(t, expect, p) p.end(zlib.gzipSync(tardata)) }) t.test('gzipped byte at a time', t => { const bs = new ByteStream() const bp = new Parse({ maxMetaEntrySize: maxMeta, filter: filter ? (path, entry) => entry.size % 2 !== 0 : null, strict: strict, }) trackEvents(t, expect, bp) bs.pipe(bp) bs.end(zlib.gzipSync(tardata)) }) t.test('async chunks', t => { const p = new Parse({ maxMetaEntrySize: maxMeta, filter: filter ? (path, entry) => entry.size % 2 !== 0 : null, strict: strict, }) trackEvents(t, expect, p, true) p.write(tardata.slice(0, Math.floor(tardata.length / 2))) process.nextTick(_ => p.end(tardata.slice(Math.floor(tardata.length / 2)))) }) t.end() }) } files .map(f => path.resolve(tardir, f)).forEach(file => maxMetaOpt.forEach(maxMeta => strictOpt.forEach(strict => filterOpt.forEach(filter => runTest(file, maxMeta, filter, strict))))) t.end() }) t.test('strict warn with an error emits that error', t => { t.plan(1) const p = new Parse({ strict: true, }) p.on('error', emitted => t.equal(emitted, er)) const er = new Error('yolo') p.warn('TAR_TEST', er) }) t.test('onwarn gets added to the warn event', t => { t.plan(1) const p = new Parse({ onwarn (code, message) { t.equal(message, 'this is fine') }, }) p.warn('TAR_TEST', 'this is fine') }) t.test('onentry gets added to entry event', t => { t.plan(1) const p = new Parse({ onentry: entry => t.equal(entry, 'yes hello this is dog'), }) p.emit('entry', 'yes hello this is dog') }) t.test('drain event timings', t => { let sawOndone = false const ondone = function () { sawOndone = true this.emit('prefinish') this.emit('finish') this.emit('end') this.emit('close') } // write 1 header and body, write 2 header, verify false return // wait for drain event before continuing. // write 2 body, 3 header and body, 4 header, verify false return // wait for drain event // write 4 body and null blocks const data = [ [ { path: 'one', size: 513, type: 'File', }, new Array(513).join('1'), '1', { path: 'two', size: 513, type: 'File', }, new Array(513).join('2'), '2', { path: 'three', size: 1024, type: 'File', }, ], [ new Array(513).join('3'), new Array(513).join('3'), { path: 'four', size: 513, type: 'File', }, ], [ new Array(513).join('4'), '4', { path: 'five', size: 1024, type: 'File', }, new Array(513).join('5'), new Array(513).join('5'), { path: 'six', size: 1024, type: 'File', }, new Array(513).join('6'), new Array(513).join('6'), { path: 'seven', size: 1024, type: 'File', }, new Array(513).join('7'), new Array(513).join('7'), { path: 'eight', size: 1024, type: 'File', }, new Array(513).join('8'), new Array(513).join('8'), { path: 'four', size: 513, type: 'File', }, new Array(513).join('4'), '4', { path: 'five', size: 1024, type: 'File', }, new Array(513).join('5'), new Array(513).join('5'), { path: 'six', size: 1024, type: 'File', }, new Array(513).join('6'), new Array(513).join('6'), { path: 'seven', size: 1024, type: 'File', }, new Array(513).join('7'), new Array(513).join('7'), { path: 'eight', size: 1024, type: 'File', }, new Array(513).join('8'), ], [ new Array(513).join('8'), { path: 'nine', size: 1537, type: 'File', }, new Array(513).join('9'), ], [new Array(513).join('9')], [new Array(513).join('9')], ['9'], ].map(chunks => makeTar(chunks)) const expect = [ 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'four', 'five', 'six', 'seven', 'eight', 'nine', ] class SlowStream extends EE { write () { setTimeout(_ => this.emit('drain')) return false } end () { return this.write() } } let currentEntry const autoPipe = true const p = new Parse({ ondone, onentry: entry => { t.equal(entry.path, expect.shift()) currentEntry = entry if (autoPipe) setTimeout(_ => entry.pipe(new SlowStream())) }, }) data.forEach(d => { if (!t.equal(p.write(d), false, 'write should return false')) return t.end() }) let interval const go = _ => { const d = data.shift() if (d === undefined) return p.end() let paused if (currentEntry) { currentEntry.pause() paused = true } const hunklen = Math.floor(d.length / 2) const hunks = [ d.slice(0, hunklen), d.slice(hunklen), ] p.write(hunks[0]) if (currentEntry && !paused) { console.error('has current entry') currentEntry.pause() paused = true } if (!t.equal(p.write(hunks[1]), false, 'write should return false: ' + d)) return t.end() p.once('drain', go) if (paused) currentEntry.resume() } p.once('drain', go) p.on('end', _ => { clearInterval(interval) t.ok(sawOndone) t.end() }) go() }) t.test('consume while consuming', t => { const data = makeTar([ { path: 'one', size: 0, type: 'File', }, { path: 'zero', size: 0, type: 'File', }, { path: 'two', size: 513, type: 'File', }, new Array(513).join('2'), '2', { path: 'three', size: 1024, type: 'File', }, new Array(513).join('3'), new Array(513).join('3'), { path: 'zero', size: 0, type: 'File', }, { path: 'zero', size: 0, type: 'File', }, { path: 'four', size: 1024, type: 'File', }, new Array(513).join('4'), new Array(513).join('4'), { path: 'zero', size: 0, type: 'File', }, { path: 'zero', size: 0, type: 'File', }, ]) const runTest = (t, size) => { const p = new Parse() const first = data.slice(0, size) const rest = data.slice(size) p.once('entry', entry => { for (let pos = 0; pos < rest.length; pos += size) p.write(rest.slice(pos, pos + size)) p.end() }) .on('entry', entry => entry.resume()) .on('end', _ => t.end()) .write(first) } // one that aligns, and another that doesn't, so that we // get some cases where there's leftover chunk and a buffer t.test('size=1000', t => runTest(t, 1000)) t.test('size=1024', t => runTest(t, 4096)) t.end() }) t.test('truncated input', t => { const data = makeTar([ { path: 'foo/', type: 'Directory', }, { path: 'foo/bar', type: 'File', size: 18, }, ]) t.test('truncated at block boundary', t => { const warnings = [] const p = new Parse({ onwarn: (c, message) => warnings.push(message) }) p.end(data) t.same(warnings, [ 'Truncated input (needed 512 more bytes, only 0 available)', ]) t.end() }) t.test('truncated mid-block', t => { const warnings = [] const p = new Parse({ onwarn: (c, message) => warnings.push(message) }) p.write(data) p.end(Buffer.from('not a full block')) t.same(warnings, [ 'Truncated input (needed 512 more bytes, only 16 available)', ]) t.end() }) t.end() }) t.test('truncated gzip input', t => { const raw = makeTar([ { path: 'foo/', type: 'Directory', }, { path: 'foo/bar', type: 'File', size: 18, }, new Array(19).join('x'), '', '', ]) const tgz = zlib.gzipSync(raw) const split = Math.floor(tgz.length * 2 / 3) const trunc = tgz.slice(0, split) const skipEarlyEnd = process.version.match(/^v4\./) t.test('early end', { skip: skipEarlyEnd ? 'not a zlib error on v4' : false, }, t => { const warnings = [] const p = new Parse() p.on('error', er => warnings.push(er.message)) let aborted = false p.on('abort', _ => aborted = true) p.end(trunc) t.equal(aborted, true, 'aborted writing') t.same(warnings, ['zlib: unexpected end of file']) t.end() }) t.test('just wrong', t => { const warnings = [] const p = new Parse() p.on('error', er => warnings.push(er.message)) let aborted = false p.on('abort', _ => aborted = true) p.write(trunc) p.write(trunc) p.write(tgz.slice(split)) p.end() t.equal(aborted, true, 'aborted writing') t.same(warnings, ['zlib: incorrect data check']) t.end() }) t.end() }) t.test('end while consuming', t => { // https://github.com/npm/node-tar/issues/157 const data = zlib.gzipSync(makeTar([ { path: 'package/package.json', type: 'File', size: 130, }, new Array(131).join('x'), { path: 'package/node_modules/@c/d/node_modules/e/package.json', type: 'File', size: 30, }, new Array(31).join('e'), { path: 'package/node_modules/@c/d/package.json', type: 'File', size: 33, }, new Array(34).join('d'), { path: 'package/node_modules/a/package.json', type: 'File', size: 59, }, new Array(60).join('a'), { path: 'package/node_modules/b/package.json', type: 'File', size: 30, }, new Array(31).join('b'), '', '', ])) const actual = [] const expect = [ 'package/package.json', 'package/node_modules/@c/d/node_modules/e/package.json', 'package/node_modules/@c/d/package.json', 'package/node_modules/a/package.json', 'package/node_modules/b/package.json', ] const mp = new MiniPass() const p = new Parse({ onentry: entry => { actual.push(entry.path) entry.resume() }, onwarn: (c, m, data) => t.fail(`${c}: ${m}`, data), }) p.on('end', () => { t.same(actual, expect) t.end() }) mp.end(data) mp.pipe(p) }) t.test('bad archives', t => { const p = new Parse() const warnings = [] p.on('warn', (code, msg, data) => { warnings.push([code, msg, data]) }) p.on('end', () => { // last one should be 'this archive sucks' t.match(warnings.pop(), [ 'TAR_BAD_ARCHIVE', 'Unrecognized archive format', { code: 'TAR_BAD_ARCHIVE', tarCode: 'TAR_BAD_ARCHIVE' }, ]) t.end() }) // javascript test is not a tarball. p.end(fs.readFileSync(__filename)) }) t.test('header that throws', t => { const p = new Parse() p.on('warn', (c, m, d) => { t.equal(m, 'invalid base256 encoding') t.match(d, { code: 'TAR_ENTRY_INVALID', }) t.end() }) const h = new Header({ path: 'path', mode: 0o07777, // gonna make this one invalid uid: 1234, gid: 4321, type: 'File', size: 1, }) h.encode() const buf = h.block const bad = Buffer.from([0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]) bad.copy(buf, 100) t.throws(() => new Header(buf), 'the header with that buffer throws') p.write(buf) }) t.test('warnings that are not so bad', t => { const p = new Parse() const warnings = [] p.on('warn', (code, m, d) => { warnings.push([code, m, d]) t.fail('should get no warnings') }) // the parser doesn't actually decide what's "ok" or "supported", // it just parses. So we have to set it ourselves like unpack does p.once('entry', entry => entry.invalid = true) p.on('entry', entry => entry.resume()) const data = makeTar([ { path: '/a/b/c', type: 'File', size: 1, }, 'a', { path: 'a/b/c', type: 'Directory', }, '', '', ]) p.on('end', () => { t.same(warnings, []) t.end() }) p.end(data) })
npm/node-tar
test/parse.js
JavaScript
isc
15,911
// This takes in a set of pairs and writes them to the database. /*jshint node: true */ "use strict"; var csv = require('fast-csv'); var database = require('./database'); var data = csv.fromPath('team.csv', {headers : true}). on("data", function(datum) { database.writeUser({name: datum.User, location: datum.Location, active: true}); });
tahoemph/random_pairs
import_users.js
JavaScript
isc
345
import capitalize from './util/capitalize'; const unitNames = { npc_dota_roshan_spawner: 'Roshan', dota_item_rune_spawner_powerup: 'Rune', dota_item_rune_spawner_bounty: 'Bounty Rune', ent_dota_tree: 'Tree', npc_dota_healer: 'Shrine', ent_dota_fountain: 'Fountain', npc_dota_fort: 'Ancient', ent_dota_shop: 'Shop', npc_dota_tower: 'Tower', npc_dota_barracks: 'Barracks', npc_dota_filler: 'Building', npc_dota_watch_tower: 'Outpost', trigger_multiple: 'Neutral Camp Spawn Box', npc_dota_neutral_spawner: 'Neutral Camp', observer: 'Observer Ward', sentry: 'Sentry Ward', }; const getUnitName = (unitType, unitSubType) => (unitSubType ? `${capitalize(unitSubType.replace('tower', 'Tier ').replace('range', 'Ranged'))} ` : '') + unitNames[unitType]; const pullTypes = ['Normal', 'Fast', 'Slow']; const neutralTypes = ['Easy', 'Medium', 'Hard', 'Ancient']; const getPopupContent = (stats, feature) => { const dotaProps = feature.get('dotaProps'); const unitClass = dotaProps.subType ? `${dotaProps.id}_${dotaProps.subType}` : dotaProps.id; const unitStats = stats[unitClass]; let htmlContent = `<div class="info"><span class="info-header">${getUnitName(dotaProps.id, dotaProps.subType)}</span><span class="info-body">`; if (dotaProps.pullType != null) { htmlContent += `<br><span class="info-line">Pull Type: ${pullTypes[dotaProps.pullType]}</span>`; } if (dotaProps.neutralType != null) { htmlContent += `<br><span class="info-line">Difficulty: ${neutralTypes[dotaProps.neutralType]}</span>`; } if (stats && unitStats) { if (unitStats.hasOwnProperty('damageMin') && unitStats.hasOwnProperty('damageMax')) { htmlContent += `<br><span class="info-line">Damage: ${unitStats.damageMin}&ndash;${unitStats.damageMax}</span>`; } if (unitStats.hasOwnProperty('bat')) { htmlContent += `<br><span class="info-line">BAT: ${unitStats.bat}</span>`; } if (unitStats.hasOwnProperty('attackRange')) { htmlContent += `<br><span class="info-line">Attack Range: ${unitStats.attackRange}</span>`; } if (unitStats.hasOwnProperty('health')) { htmlContent += `<br><span class="info-line">Health: ${unitStats.health}</span>`; } if (unitStats.hasOwnProperty('armor')) { htmlContent += `<br><span class="info-line">Armor: ${unitStats.armor}</span>`; } if (unitStats.hasOwnProperty('dayVision') && unitStats.hasOwnProperty('nightVision')) { htmlContent += `<br><span class="info-line">Vision: ${unitStats.dayVision}/${unitStats.nightVision}</span>`; } } htmlContent += '</span></div>'; return htmlContent; }; export default getPopupContent;
devilesk/dota-interactive-map
src/js/getPopupContent.js
JavaScript
isc
2,819
/** Markup under cursor and editing */ var Reflux=require("reflux"); var docfilestore=require("./docfile"); var markupNav=require("../markup/nav"); var markupStore=Reflux.createStore({ listenables:[require("../actions/markup")] ,markupsUnderCursor:[] ,ctrl_m_handler:null ,editing:null ,hovering:null ,onMarkupsUnderCursor:function(markupsUnderCursor) { //this.editing=null; if (this.markupsUnderCursor==markupsUnderCursor) return; this.markupsUnderCursor=markupsUnderCursor||[]; this.trigger(this.markupsUnderCursor,{cursor:true}); } ,getEditing:function() { return this.editing; } ,getNext:function() { if (!this.editing) return; return markupNav.next(this.editing.markup); } ,getPrev:function() { if (!this.editing) return; return markupNav.prev(this.editing.markup); } ,cancelEdit:function() { this.editing=null; this.ctrl_m_handler=null; } ,freeEditing:function() { if (!this.editing) return; this.editing.doc=null;//to notify markupselector shouldComponentUpdate } ,onEditMarkup:function(markup) { this.cancelEdit(); this.editing=markup; this.ctrl_m_handler=null; this.trigger([{doc:markup.handle.doc,key:markup.key,markup:markup}],{cursor:true}); } ,setEditing:function(markup,handler) { this.cancelEdit(); this.editing=markup; this.ctrl_m_handler=handler; //this.trigger([],{cursor:true}); this.trigger(markup,{editing:true}); } ,onSetHotkey:function(handler) { this.ctrl_m_handler=handler; //console.log("handler",handler,this); } ,remove:function(markup) { //console.log("remove markup",markup); this.cancelEdit(); var doc=markup.handle.doc; doc.getEditor().react.removeMarkup(markup.key); this.trigger([],{cursor:true}); } ,removeByMid:function(mid,file){ //console.log("remove mid in file",mid,file); var doc=docfilestore.docOf(file); doc.getEditor().react.removeMarkup(mid); this.trigger([],{cursor:true}); } ,onToggleMarkup:function(){ if (this.ctrl_m_handler) { this.ctrl_m_handler(); this.ctrl_m_handler=null;//fire once } } ,getHovering:function() { return this.hovering; } ,onHovering:function(m) { this.hovering=m; this.trigger(m,{hovering:true}); } ,onCreateMarkup:function(obj,cb) { if (!obj.typedef || !obj.typedef.mark) { console.log(obj); throw "cannot create markup" } this.editing=null; obj.typedef.mark(obj, docfilestore.docOf ,function(err,newmarkup){ this.markupsUnderCursor=newmarkup; this.trigger( this.markupsUnderCursor,{newly:true}); if (cb) cb(); }.bind(this)); } }) module.exports=markupStore;
ksanaforge/pannaloka
src/stores/markup.js
JavaScript
isc
2,579
/*jslint node: true*/ "use strict"; var fs = require('fs'), path = require('path'), util = require('util'), protocolHandler = {}, moment = require('moment'); protocolHandler.http = require('http'); protocolHandler.https = require('https'); function asArray(a) { if (Array.isArray(a)) { return a; } // else if (a === null || a === undefined) { return []; } // else return [a]; } function Client(settings) { var protocol = settings.protocol || "http"; this.handler = protocolHandler[protocol]; this.verbose = !!settings.verbose; // false if not set this.server = settings.server || "win-api.westtoer.be"; this.version = settings.version || "v1"; this.clientid = settings.clientid || "westtoer"; this.secret = settings.secret || "no-secret"; this.baseURI = protocol + "://" + this.server + "/api/" + this.version + "/"; this.authURI = protocol + "://" + this.server + "/oauth/v2/token?grant_type=client_credentials&client_id=" + encodeURIComponent(this.clientid) + "&client_secret=" + encodeURIComponent(this.secret); // we initialize in a stopped modus this.stop(); } Client.DEFAULT_PAGE = 1; Client.DEFAULT_SIZE = 10; function GenericQuery(tpl) { if (tpl !== undefined && tpl.constructor === GenericQuery) { // clone - constructor this.format = tpl.format; this.resources = tpl.resources.slice(0); this.touristictypes = tpl.touristictypes.slice(0); this.sizeVal = tpl.sizeVal; this.pageNum = tpl.pageNum; this.channels = tpl.channels.slice(0); this.lastmodRange = tpl.lastmodRange; this.softDelState = tpl.softDelState; this.pubState = tpl.pubState; this.bulkMode = tpl.bulkMode; this.partnerId = tpl.partnerId; this.keyvalset = tpl.keyvalset.slice(0); this.ownerEmail = tpl.ownerEmail; this.requiredFields = tpl.requiredFields.slice(0); this.selectId = tpl.selectId; this.selectMunicipal = tpl.selectMunicipal; this.machineName = tpl.machineName; this.anyTerm = tpl.anyTerm; } else { // nothing to clone, use defaults this.format = 'xml'; this.resources = ['accommodation']; //default zou alle types moeten kunnen bevatten this.touristictypes = []; this.sizeVal = Client.DEFAULT_SIZE; this.pageNum = Client.DEFAULT_PAGE; this.channels = []; this.requiredFields = []; this.keyvalset = []; this.bulkMode = false; } } GenericQuery.prototype.clone = function () { return new GenericQuery(this); }; // paging GenericQuery.prototype.page = function (page) { this.pageNum = Number(page) || Client.DEFAULT_PAGE; return this; }; GenericQuery.prototype.size = function (size) { this.sizeVal = Number(size) || 10; return this; }; // qrybuilder formats GenericQuery.prototype.asJSON_HAL = function () { this.format = 'json+hal'; return this; }; GenericQuery.prototype.asJSON = function () { this.format = 'json'; return this; }; GenericQuery.prototype.asXML = function () { this.format = 'xml'; return this; }; GenericQuery.prototype.bulk = function () { this.bulkMode = true; return this; }; //qrybuilder resource filter GenericQuery.prototype.forResources = function (newRsrc) { this.resources = asArray(newRsrc); return this; }; GenericQuery.prototype.andResource = function (singleRsrc) { this.resources.push(singleRsrc); return this; }; //qrybuilder type filter -- product queries GenericQuery.prototype.forTypes = function (newtypes) { return this.forResources(newtypes); }; GenericQuery.prototype.andType = function (singletype) { return this.andResource(singletype); }; //qrybuilder type filter -- vocabularies queries GenericQuery.prototype.forVocs = function () { return this.forResources(['vocabulary']); }; //qrybuilder type filter -- claims queries GenericQuery.prototype.forClaims = function () { return this.forResources(['product_claim']); }; //qrybuilder type filter -- statistical queries GenericQuery.prototype.forStats = function () { return this.forResources(['product_statistical_data']); }; //qrybuilder touristic_type filter GenericQuery.prototype.forTouristicTypes = function (newtypes) { this.touristictypes = asArray(newtypes); return this; }; GenericQuery.prototype.andTouristicType = function (singletype) { this.touristictypes.push(singletype); return this; }; //qrybuilder generic keyvals filter GenericQuery.prototype.andKeyVal = function (key, val) { this.keyvalset.push({"key": key, "val": val}); return this; }; //qrybuilder lastmod filter GenericQuery.prototype.lastmod = function (range) { this.lastmodRange = range; return this; }; function dateFormat(s) { if (s === undefined || s === null) { return "*"; } return moment(s).format('YYYY-MM-DD'); } GenericQuery.prototype.lastmodBetween = function (from, to) { var range = {}; if (from !== undefined && from !== null) { range.gte = dateFormat(from); } if (to !== undefined && to !== null) { range.lt = dateFormat(to); } return this.lastmod(range); // start boundary is inclusive, end-boundary is exclusive }; //qrybuilder delete filter GenericQuery.prototype.removed = function () { this.softDelState = true; return this; }; GenericQuery.prototype.active = function () { this.softDelState = false; return this; }; GenericQuery.prototype.ignoreRemoved = function () { this.softDelState = undefined; return this; }; //qrybuilder pubchannel filter GenericQuery.prototype.forChannels = function (chs) { this.channels = asArray(chs); return this; }; GenericQuery.prototype.andChannel = function (ch) { this.channels.push(ch); return this; }; GenericQuery.prototype.requirePubChannel = function () { return this.andChannel(".*"); }; //qrybuilder published filter GenericQuery.prototype.published = function () { this.pubState = true; return this; }; GenericQuery.prototype.hidden = function () { this.pubState = false; return this; }; GenericQuery.prototype.ignorePublished = function () { this.pubState = undefined; return this; }; //qrybuilder owner-email filtering GenericQuery.prototype.owner = function (email) { this.ownerEmail = email; return this; }; //qrybuilder partner-id filtering GenericQuery.prototype.partner = function (id) { this.partnerId = id; return this; }; //qrybuilder id filtering GenericQuery.prototype.id = function (id) { this.selectId = id; return this; }; //qrybuilder municipality filtering GenericQuery.prototype.municipality = function (muni) { this.selectMunicipal = muni; return this; }; //qrybuilder existingfields filter GenericQuery.prototype.requireFields = function (flds) { this.requiredFields = asArray(flds); return this; }; GenericQuery.prototype.andField = function (fld) { this.requiredFields.push(fld); return this; }; //qrybuilder vocname filtering GenericQuery.prototype.vocname = function (name) { this.machineName = name; return this; }; //qrybuilder stats-year filtering GenericQuery.prototype.statsyear = function (year) { this.statsYear = Number(year); return this; }; //qrybuilder any field matching GenericQuery.prototype.match = function (term) { this.anyTerm = term; return this; }; GenericQuery.addURI = function (key, value, unsetVal) { if (value === unsetVal) { return ""; } // else return "&" + key + "=" + encodeURIComponent(value); }; GenericQuery.addQuery = function (set, type, key, value) { if (Array.isArray(value)) { value = value.join(" "); } if (value === undefined || value === null || value === "") { return; } // else var rule = {}, qry = {}; rule[key] = value; qry[type] = rule; set.push(qry); }; GenericQuery.addMatchQuery = function (set, key, value) { GenericQuery.addQuery(set, "match", key, value); }; GenericQuery.addFuzzyQuery = function (set, key, value) { GenericQuery.addQuery(set, "fuzzy", key, value); }; GenericQuery.addTermsQuery = function (set, key, value) { GenericQuery.addQuery(set, "terms", key, value.split(/\s/)); }; GenericQuery.addRegExpQuery = function (set, key, value) { GenericQuery.addQuery(set, "regexp", key, value); }; GenericQuery.addRangeQuery = function (set, key, range) { GenericQuery.addQuery(set, "range", key, range); }; GenericQuery.addNestedQuery = function (set, path, subfn) { if (path === undefined) { return; } // else var subset = [], qry = {"bool": {"must": subset}}; subfn(subset); set.push({"nested": {"path": path, "query": qry}}); }; GenericQuery.addExistsFilters = function (set, fields) { fields.forEach(function (field) { if (field === undefined || field === null || field === "") { return; } set.push({"exists": {"field": field}}); }); }; GenericQuery.prototype.getURI = function (client, notoken) { notoken = notoken || false; var me = this, uri, esq = [], esf = [], query, queryNeeded = false, expired = client.token_expires < Date.now(); if (!notoken && (client.token === null || expired)) { throw new Error("client has no active (" + !expired + ") token (" + client.token + ")"); } if (this.resources === undefined || this.resources === null || this.resources.length === 0) { throw new Error("no types specified for fetch"); } uri = client.baseURI + (this.bulkMode ? "bulk/" : "") + this.resources.join(',') + "?format=" + this.format + "&access_token=" + (notoken ? "***" : encodeURIComponent(client.token)); if (!this.bulkMode) { // paging is meaningless in bulk mode uri += GenericQuery.addURI("size", this.sizeVal, Client.DEFAULT_SIZE); uri += GenericQuery.addURI("page", this.pageNum, Client.DEFAULT_PAGE); } GenericQuery.addRangeQuery(esq, "metadata.update_date", this.lastmodRange); GenericQuery.addMatchQuery(esq, "metadata.deleted", this.softDelState); GenericQuery.addMatchQuery(esq, "publishing_channels.published", this.pubState); GenericQuery.addMatchQuery(esq, "metadata.id", this.selectId); GenericQuery.addMatchQuery(esq, "location_info.address.municipality", this.selectMunicipal); this.keyvalset.forEach( function(kv) { GenericQuery.addMatchQuery(esq, kv.key, kv.val); }); GenericQuery.addFuzzyQuery(esq, "_all", this.anyTerm); GenericQuery.addExistsFilters(esf, this.requiredFields); if (this.channels.length > 0) { GenericQuery.addNestedQuery( esq, "publishing_channels.publishing_channel", function (subset) { GenericQuery.addRegExpQuery(subset, "publishing_channels.publishing_channel.code", me.channels); GenericQuery.addMatchQuery(subset, "publishing_channels.publishing_channel.published", true); } ); } GenericQuery.addMatchQuery(esq, "metadata.touristic_product_type.code", this.touristictypes); // specific for claims GenericQuery.addRegExpQuery(esq, "claims.claim.owner.email_address", this.ownerEmail); GenericQuery.addMatchQuery(esq, "metadata.partner_id", this.partnerId); // specific for vocabs GenericQuery.addMatchQuery(esq, "machine_name", this.machineName); // specific for stats GenericQuery.addMatchQuery(esq, "statistical_data_collection.year", this.statsYear); query = {"query" : {"filtered": {}}}; if (esq.length > 0) { queryNeeded = true; query.query.filtered.query = {"bool" : {"must": esq}}; } if (esf.length > 0) { queryNeeded = true; query.query.filtered.filter = {"bool" : {"must": esf}}; } if (queryNeeded) { uri += "&_query=" + encodeURIComponent(JSON.stringify(query)); } return uri; }; function getResponse(client, uri, cb, verbose) { verbose = verbose || false; if (verbose) { console.log("call uri [%s]", uri); } client.get(uri, function (res) { cb(null, res); }).on('error', function (e) { cb(e); }); } function streamData(client, uri, sink, cb, verbose) { getResponse(client, uri, function (e, res) { var stream; if (e) { sink.emit('error', e); } else if (res === undefined || res === null) { sink.emit('error', new Error("error reading uri [" + uri + "] - no response object.")); } else if (res.statusCode !== 200) { sink.emit('error', new Error("error reading uri [" + uri + "] to stream - response.status == " + res.statusCode)); } else { // all is well, so try sinking this data stream = res.pipe(sink); } cb(e, res, stream); }, verbose); } function getData(client, uri, cb, verbose) { getResponse(client, uri, function (e, res) { var data = ""; if (e) { return cb(e); } //else if (res === undefined || res === null) { return cb(new Error("error reading uri [" + uri + "] - no response object.")); } if (res.statusCode !== 200) { return cb(new Error("error reading uri [" + uri + "] - status == " + res.statusCode)); } // else res .on('data', function (chunk) { data += chunk; }) .on('end', function () { cb(null, data); }) .on('error', cb); }, verbose); } function getJSON(client, uri, cb, verbose) { getData(client, uri, function (e, data) { if (e) { return cb(e); } //else cb(null, JSON.parse(data)); }, verbose); } function getXML(client, uri, cb, verbose) { //TODO parse XML to DOM ? getData(client, uri, cb, verbose); } Client.prototype.stop = function () { clearTimeout(this.token_refresh); this.token = null; this.token_expires = Date.now(); this.token_refresh = null; }; Client.prototype.start = function (cb) { cb = cb || function () {return; }; var me = this, SLACK_MILLIS = 1000, exp_in_millis; if (me.token_refresh !== null) { // already started... if (cb) { return cb(null); // no errors, but no token object either } return; } // else getJSON(this.handler, this.authURI, function (e, resp) { if (e) { console.error("getjson ERROR: %j", e); return cb(e); } me.token = resp.access_token; exp_in_millis = resp.expires_in * 1000; me.token_expires = Date.now() + exp_in_millis; if (exp_in_millis > SLACK_MILLIS) { // we assume at least 1s slack to operate me.token_refresh = setTimeout(function () { me.start(); }, exp_in_millis - SLACK_MILLIS); } else { console.warn("token validity too short to organize self-refresh"); } if (me.verbose) { console.log("got token %s - valid for %d - till %s", me.token, resp.expires_in, moment(me.token_expires)); } cb(e, resp); }, this.verbose); }; Client.prototype.fetch = function (qry, cb) { if (arguments.length < 2) { cb = qry; qry = new GenericQuery(); } try { if (qry.format === 'json') { getJSON(this.handler, qry.getURI(this), function (e, resp) { cb(e, resp); }, this.verbose); } else if (qry.format === 'json+hal') { getJSON(this.handler, qry.getURI(this), function (e, resp) { if (e) { return cb(e); } // else var meta = resp, EMB = "_embedded", emb = meta[EMB]; resp = emb.items; delete emb.items; cb(e, resp, meta); }, this.verbose); } else if (qry.format === 'xml') { getXML(this.handler, qry.getURI(this), function (e, resp) { cb(e, resp); }, this.verbose); } } catch (e) { cb(e); } }; Client.prototype.stream = function (qry, sink, cb) { if (arguments.length < 2) { sink = qry; qry = new GenericQuery(); } cb = cb || function () { return; }; // do nothing callback try { streamData(this.handler, qry.getURI(this), sink, cb, this.verbose); } catch (e) { cb(e, null); } }; Client.prototype.parseVocabularyCodes = function (vocabs, onlyNames) { return vocabs.reduce(function (byName, voc) { var name = voc.machine_name; if (onlyNames === undefined || onlyNames.indexOf(name) !== -1) { if (byName.hasOwnProperty(name)) { throw new Error("duplicate key machine_name : " + name); } if (voc && voc.terms && voc.terms.term) { byName[name] = Object.keys(voc.terms.term.reduce(function (res, term) { var code = term.code || ""; if (code.length === 0) { throw new Error("invalid empty code '' for vocabulary: " + name); } if (res.hasOwnProperty(code)) { throw new Error("duplicate code '" + code + "' for vocabulary: " + name); } res[code] = term; return res; }, {})); // byName[name] = voc.terms.term.map(function (term) { // var code = term.code || ""; // if (code.length === 0) { // throw new Error("invalid empty code '' for vocabulary: " + name); // } // return code; // }); } else { byName[name] = []; } } return byName; }, {}); }; Client.prototype.parseVocabularyTrees = function (vocabs, onlyNames) { return vocabs.reduce(function (byName, voc) { var name = voc.machine_name, termRoot = {children: []}, termNodes; if (onlyNames === undefined || onlyNames.indexOf(name) !== -1) { if (byName.hasOwnProperty(name)) { throw new Error("duplicate key machine_name : " + name); } if (voc && voc.terms && voc.terms.term && voc.hierarchy) { // list all linkable nodes termNodes = voc.terms.term.reduce(function (tns, term) { var code = term.code || "", pcode = term.parent_code || ""; if (code.length === 0) { throw new Error("invalid empty code '' for vocabulary: " + name); } if (tns.hasOwnProperty(code)) { throw new Error("duplicate code '" + code + "' for vocabulary: " + name); } tns[code] = { code: code, parent: pcode, children: [] }; return tns; }, {}); // link parents and children Object.keys(termNodes).forEach(function (code) { var tn = termNodes[code], pn = tn.parent === "" ? termRoot : termNodes[tn.parent]; if (pn === null || pn === undefined) { throw new Error("not found node for parent_code '" + tn.parent + "' in voc named: " + name); } tn.parent = pn; pn.children.push(tn); }); byName[name] = termRoot.children; } else { byName[name] = null; } } return byName; }, {}); }; module.exports.client = function (settings) { return new Client(settings); }; module.exports.query = function (service) { service = service || 'product'; if (service === 'product') { return new GenericQuery(); } if (service === 'vocabulary') { return new GenericQuery().forVocs(); } if (service === 'claim') { return new GenericQuery().forClaims(); } if (service === 'statistics') { return new GenericQuery().forStats(); } throw "unknown service request"; };
westtoer/node-winapi
lib/winapi.js
JavaScript
isc
20,578
var sendError = require('../../util/send-error'); // Create a new todo module.exports = function (options) { // Shorter reference to data store var store = options.store; return function (req, res) { var todo = store.todos.filter(function (t) { return t.id === req.params.id; })[0]; // No todo with that id if (!todo) { return sendError(res, 404, 'Todo not found'); } // Verify that user exists var user = store.users.filter(function (u) { return u.id === req.params.userId; })[0]; if (!user) { return sendError(res, 400, 'User not found: ' + req.params.userId); } // Set values todo.assignedTo = user.id; // Save data to store store.users.splice(store.users.indexOf(user), 1, user); // Respond res.status(200).json(todo); }; };
wesleytodd/express-todo-api
handlers/todos/assign.js
JavaScript
isc
784
var pi = require('./src/pi'); function run() { pi.send(parseInt(process.argv[2], 10)); setTimeout(run(), 2000); } run();
LucioFranco/bota2015
single.js
JavaScript
isc
128
'use strict' const net = require('net') const assert = require('assert') const eventList = require('../src/event-list') const tcpEmitterServer = require('../src/index') const { net: netUtils, payload: payloadUtils } = require('./utils') describe('TCP Emitter Server Tests:', function () { describe('Scenario: Creating a new TCP Emitter server:', function () { describe('When creating a new TCP Emitter server:', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { serverInst = tcpEmitterServer() }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) it('should return new instance of `net.Server`', function () { assert.ok(serverInst instanceof net.Server) }) }) }) describe('Scenario: Subscribing to an event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter server which the TCP Emitter client will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with a connected TCP Emitter client,', function () { /** * TCP Emitter client that will be subscribing to an event. * @type {net.Socket} */ let clientInst = null beforeEach(function () { // Create the TCP Emitter client and connect it with the TCP Emitter // server for this test. return netUtils.createTCPEmitterClient(serverInst.address()) .then(client => { clientInst = client }) }) afterEach(function () { return netUtils.closeTCPEmitterClient(clientInst) }) describe('when the TCP Emitter client subscribes to an event:', function () { /** * Event which the TCP Emitter client will be subscribing to. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' }) it('should emit TCP Emitter Subscribe Event with the TCP Emitter client & Event name', function (done) { serverInst.on(eventList.subscribe, (socket, eventName) => { // Assert that the emitted event name is the same as the event // name which the TCP Emitter client subscribed to. assert.strictEqual(event, eventName) // Assert that socket is of type 'net.Socket'. assert.ok(socket instanceof net.Socket) done() }) // Subscribe to an event. clientInst.write(payloadUtils.createSubscribe({ event })) }) }) }) }) }) describe('Scenario: Subscribing to an already subscribed event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter server which the TCP Emitter client will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with a connected TCP Emitter client,', function () { /** * TCP Emitter client that will be subscribing to an event. * @type {net.Socket} */ let clientInst = null beforeEach(function () { // Create the TCP Emitter client and connect it with the TCP Emitter // server for this test. return netUtils.createTCPEmitterClient(serverInst.address()) .then(client => { clientInst = client }) }) afterEach(function () { return netUtils.closeTCPEmitterClient(clientInst) }) describe('that is subscribed to an event,', function () { /** * Event which the TCP Emitter client will be subscribing to. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' return clientInst.write(payloadUtils.createSubscribe({ event })) }) describe('when re-subscribing to the same event:', function () { it('should not emit TCP Emitter Subscribe Event', function (done) { global.setTimeout(done, 500) serverInst.on(eventList.subscribe, data => { assert.fail('TCP Emitter server should not emit TCP Emitter ' + 'Subscribe Event if the TCP Emitter client requests to ' + 'subscribe to an event that it is already subscribed to') done() }) // Subscribe to an event which the TCP Emitter client is already // subscribed to. clientInst.write(payloadUtils.createSubscribe({ event })) }) }) }) }) }) }) describe('Scenario: Unsubscribing from an event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter server which the TCP Emitter client will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with a connected TCP Emitter client,', function () { /** * TCP Emitter client that will be unsubscribing from an event. * @type {net.Socket} */ let clientInst = null beforeEach(function () { // Create the TCP Emitter client and connect it with the TCP Emitter // server for this test. return netUtils.createTCPEmitterClient(serverInst.address()) .then(client => { clientInst = client }) }) afterEach(function () { return netUtils.closeTCPEmitterClient(clientInst) }) describe('that is subscribed to an event,', function () { /** * Event which the TCP Emitter client will be unsubscribing from. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' return clientInst.write(payloadUtils.createSubscribe({ event })) }) describe('when the TCP Emitter client unsubscribes from an event:', function () { it('should emit TCP Emitter Unsubscribe Event with the TCP Emitter client & Event name', function (done) { serverInst.on(eventList.unsubscribe, (socket, eventName) => { // Assert that the emitted event name is the same as the event // name which the TCP Emitter client subscribed to. assert.strictEqual(event, eventName) // Assert that socket is of type 'net.Socket'. assert.ok(socket instanceof net.Socket) done() }) // Subscribe to an event. return clientInst.write(payloadUtils.createUnsubscribe({ event })) }) }) }) }) }) }) describe('Scenario: Unsubscribing from an unsubscribed event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter server which the TCP Emitter client will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with a connected TCP Emitter client,', function () { /** * TCP Emitter client that will be subscribing to an event. * @type {net.Socket} */ let clientInst = null beforeEach(function () { // Create the TCP Emitter client and connect it with the TCP Emitter // server for this test. return netUtils.createTCPEmitterClient(serverInst.address()) .then(client => { clientInst = client }) }) afterEach(function () { return netUtils.closeTCPEmitterClient(clientInst) }) describe('when the TCP Emitter client request to unsubscribes from an event that it is not subscribed to:', function () { /** * Event which the TCP Emitter client will be unsubscribing from. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' }) it('should not emit TCP Emitter Unsubscribe Event', function (done) { global.setTimeout(done, 500) serverInst.on(eventList.unsubscribe, data => { assert.fail('TCP Emitter server should not emit TCP Emitter ' + 'Unsubscribe Event if the TCP Emitter client requests to ' + 'unsubscribe from an event that it is not subscribed to') done() }) // Unsubscribe from an event that the TCP Emitter client is not // subscribed to. clientInst.write(payloadUtils.createUnsubscribe({ event })) }) }) }) }) }) describe('Scenario: Broadcasting to an event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter server which the TCP Emitter client will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with a connected TCP Emitter client,', function () { /** * TCP Emitter client that will be broadcasting to an event. * @type {net.Socket} */ let clientInst = null beforeEach(function () { // Create the TCP Emitter client and connect it with the TCP Emitter // server for this test. return netUtils.createTCPEmitterClient(serverInst.address()) .then(client => { clientInst = client }) }) afterEach(function () { return netUtils.closeTCPEmitterClient(clientInst) }) describe('when the TCP Emitter client broadcasts to an event:', function () { /** * Event which the TCP Emitter client will be broadcasting to. * @type {string} */ let event = null /** * Arguments that will be broadcasted. * @type {Array.<*>} */ let args = null beforeEach(function () { event = 'event-name' args = [ 1, '2', true, { name: 'luca' } ] }) it('should emit TCP Emitter Broadcast Event with the TCP Emitter client, Event name & Arguments', function (done) { // When an assertion fails in a EventEmitter, it will by default // emit the 'error' event with the error object. If there are no // listeners to the 'error' event it will throw the Error to the // process. // // Such implementation is expected when dealing with syncrhonous // processes, however since the Broadcast process uses Promises so // that it emits the TCP Emitter Broadcast Event once all the event // listeners (TCP Emitter clients) have been notified, when the // 'error' event is emitted, apart from the assertion error it will // also show the UnhandledPromiseRejectionWarning warning. // // This is why we are listening for the error event in this test // case. serverInst.on('error', done) serverInst.on(eventList.broadcast, (socket, eventName, broadcastedArgs) => { // Assert that the emitted event name is the same as the event // name which the TCP Emitter client broadcasted to. assert.strictEqual(event, eventName) // Assert that socket is of type 'net.Socket'. assert.ok(socket instanceof net.Socket) // Assert that the emitted arguments are the same as the // broadcasted arguments. assert.deepStrictEqual(args, broadcastedArgs) done() }) // Broadcast to an event. clientInst.write(payloadUtils.createBroadcast({ event, args })) }) }) }) }) }) describe('Scenario: Subscribing & broadcasting to an event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter Server which the TCP Emitter clients will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with multiple connected TCP Emitter clients,', function () { /** * TCP Emitter client that will be receiving the payload. * @type {net.Socket} */ let receiverOne = null /** * TCP Emitter client that will be receiving the payload. * @type {net.Socket} */ let receiverTwo = null /** * TCP Emitter client that will be subscribed to another event. * @type {net.Socket} */ let otherClient = null /** * TCP Emitter client that will be broadcasting the payload. * @type {net.Socket} */ let broadcaster = null beforeEach(function () { // Create the TCP Emitter clients and connect them with the TCP // Emitter server for this test. return Promise.all([ netUtils.createTCPEmitterClient(serverInst.address()), netUtils.createTCPEmitterClient(serverInst.address()), netUtils.createTCPEmitterClient(serverInst.address()), netUtils.createTCPEmitterClient(serverInst.address()) ]).then(clients => { receiverOne = clients[0] receiverTwo = clients[1] otherClient = clients[2] broadcaster = clients[3] }) }) afterEach(function () { return Promise.all([ netUtils.closeTCPEmitterClient(receiverOne), netUtils.closeTCPEmitterClient(receiverTwo), netUtils.closeTCPEmitterClient(otherClient), netUtils.closeTCPEmitterClient(broadcaster) ]) }) describe('that are subscribed to an event,', function () { /** * Name of the event which the TCP Emitter clients will be subscribing * & broadcasting to. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' // Subscribe the TCP Emitter clients. return Promise.all([ netUtils.write(receiverOne, payloadUtils.createSubscribe({ event })), netUtils.write(receiverTwo, payloadUtils.createSubscribe({ event })), netUtils.write(broadcaster, payloadUtils.createSubscribe({ event })), netUtils.write(otherClient, payloadUtils.createSubscribe({ event: 'other' })) ]) }) describe('when a TCP Emitter client broadcasts to an event:', function () { /** * Arguments that will be broadcasted. * @type {Array.<*>} */ let args = null beforeEach(function () { args = [ 1, '2', true, { name: 'luca' } ] }) it('should broadcast the payload to the listeners of the event', function (done) { // Wait for any data sent by the TCP Emitter server. Promise.all([ netUtils.waitForData(receiverOne), netUtils.waitForData(receiverTwo) ]).then(dataArray => { dataArray.forEach(data => { // Parse the data retrieved from TCP Emitter server. const payloads = payloadUtils.parsePayload({ data }) // Assert that only one payload was received. assert.strictEqual(payloads.length, 1) // Assert 'event' attribute. assert.strictEqual(event, payloads[0].event) // Assert 'args' attribute assert.deepStrictEqual(args, payloads[0].args) }) // Finalize test. done() }).catch(done) // Broadcast payload to the event which the receiver TCP Emitter // client is subscriibed to. broadcaster.write(payloadUtils.createBroadcast({ event, args })) }) it('should not broadcast the payload to the TCP Emitter client from where the broadcast originated from', function (done) { // Wait 500ms for any data sent by TCP Emitter Server before // assuming the test case is successful. global.setTimeout(done, 500) // Wait for any data sent by the TCP Emitter server. netUtils.waitForData(broadcaster).then(() => { // TCP Emitter clients that broadcasted to the event should not // be notified by the TCP Emitter server. assert.fail('TCP Emitter clients that broadcasted to the ' + 'should not be notified') }).catch(done) // Broadcast payload to the event which the receiver TCP Emitter // client is subscriibed to. broadcaster.write(payloadUtils.createBroadcast({ event, args })) }) it('should not broadcast the payload to the TCP Emitter clients that are not subscribed to the event the broadcast was made for', function (done) { // Wait 500ms for any data sent by TCP Emitter Server before // assuming the test case is successful. global.setTimeout(done, 500) // Wait for any data sent by the TCP Emitter server. netUtils.waitForData(otherClient).then(() => { // TCP Emitter clients which are not subscribed to the event // which the broadcast was made to, should not be notified. assert.fail('TCP Emitter client which is not subscribed to ' + 'the event the broadcast was made to, should not be notified') }).catch(done) // Broadcast payload to the event which the receiver TCP Emitter // client is subscriibed to. broadcaster.write(payloadUtils.createBroadcast({ event, args })) }) }) }) }) }) }) describe('Scenario: Unsubscribing from & broadcasting to an event:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter server which the TCP Emitter clients whill be // connecting return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with multiple connected TCP Emitter clients,', function () { /** * TCP Emitter client that will be receiving the payload. * @type {net.Socket} */ let receiver = null /** * TCP Emitter client that will be broadcasting the payload. * @type {net.Socket} */ let broadcaster = null /** * TCP Emitter client that will be unsubscribing from an event. * @type {net.Socket} */ let unsubscriber = null beforeEach(function () { // Create the TCP Emitter clients and connect them with the TCP // Emitter server for this test. return Promise.all([ netUtils.createTCPEmitterClient(serverInst.address()), netUtils.createTCPEmitterClient(serverInst.address()), netUtils.createTCPEmitterClient(serverInst.address()) ]).then(clients => { receiver = clients[0] broadcaster = clients[1] unsubscriber = clients[2] }) }) afterEach(function () { return Promise.all([ netUtils.closeTCPEmitterClient(receiver), netUtils.closeTCPEmitterClient(broadcaster), netUtils.closeTCPEmitterClient(unsubscriber) ]) }) describe('that are subscribed to an event,', function () { /** * Name of the event which the TCP Emitter clients will be subscribing * & broadcasting to. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' // Subscribe the TCP Emitter clients return Promise.all([ netUtils.write(receiver, payloadUtils.createSubscribe({ event })), netUtils.write(unsubscriber, payloadUtils.createSubscribe({ event })) ]) }) describe('and a TCP Emitter client unsubscribes from an event,', function () { beforeEach(function () { return netUtils.write(unsubscriber, payloadUtils.createUnsubscribe({ event })) }) describe('when a TCP Emitter client broadcasts to an event:', function () { /** * Arguments that will be broadcasted. * @type {Array.<*>} */ let args = null beforeEach(function () { args = [ 1, '2', true, { name: 'luca' } ] }) it('should broadcast the payload to the listeners of the event', function (done) { // Wait for any data sent by the TCP Emitter server. netUtils.waitForData(receiver).then((data) => { // Parse the data retrieved from TCP Emitter server. const payloads = payloadUtils.parsePayload({ data }) // Assert that only one payload was received. assert.strictEqual(payloads.length, 1) // Assert 'event' attribute. assert.strictEqual(event, payloads[0].event) // Assert 'args' attribute assert.deepStrictEqual(args, payloads[0].args) // Finalize test. done() }).catch(done) // Broadcast payload to the event which the TCP Emitter clients // have subscribed to. broadcaster.write(payloadUtils.createBroadcast({ event, args })) }) it('should not broadcast the payload to the TCP Emitter client that unsubscribed from the event', function (done) { // Wait 500ms for any data sent by TCP Emitter Server before // assuming the test case is successful. global.setTimeout(done, 500) // Wait for any data sent by the TCP Emitter server. netUtils.waitForData(unsubscriber).then(() => { // The TCP Emitter client which broadcasted the event should not // be notified by the TCP Emitter server. assert.fail('TCP Emitter client that unsubscribed from an ' + 'event should not be notified') }).catch(done) // Broadcast payload to the event which the TCP Emitter clients // have subscribed to. broadcaster.write(payloadUtils.createBroadcast({ event })) }) }) }) }) }) }) }) describe('Scenario: Broadcasting multiple payloads with a single TCP request:', function () { describe('Given a TCP Emitter server,', function () { /** * TCP Emitter server. * @type {Object} */ let serverInst = null beforeEach(function () { // Create the TCP Emitter Server which the TCP Emitter clients will be // connecting to. return netUtils.createTCPEmitterServer().then(server => { serverInst = server }) }) afterEach(function () { return netUtils.closeTCPEmitterServer(serverInst) }) describe('with multiple connected TCP Emitter clients', function () { /** * TCP Emitter client that will be receiving the payload. * @type {net.Socket} */ let receiver = null /** * TCP Emitter client that will be broadcasting the payload. * @type {net.Socket} */ let broadcaster = null beforeEach(function () { // Create the TCP Emitter clients and connect them with the TCP // Emitter server for this test. return Promise.all([ netUtils.createTCPEmitterClient(serverInst.address()), netUtils.createTCPEmitterClient(serverInst.address()) ]).then(clients => { receiver = clients[0] broadcaster = clients[1] }) }) afterEach(function () { return Promise.all([ netUtils.closeTCPEmitterClient(receiver), netUtils.closeTCPEmitterClient(broadcaster) ]) }) describe('and one of which is subscribed to an event,', function () { /** * Name of the event which the TCP Emitter clients will be subscribing * & broadcasting to. * @type {string} */ let event = null beforeEach(function () { event = 'event-name' // Subscribe the TCP Emitter client which will serve as the // receiver. return netUtils.write(receiver, payloadUtils.createSubscribe({ event })) }) describe('when broadcasting multiple payloads with a single TCP request:', function () { /** * Arguments that will be broadcasted in the first payload. * @type {Array.<*>} */ let argsOne = null /** * Arguments that will be broadcasted in the second payload. * @type {Array.<*>} */ let argsTwo = null beforeEach(function () { argsOne = [ 1, '2', true, { name: 'luca' } ] argsTwo = [ 2, '3', false, { surname: 'tabone' } ] }) it('should broadcast all the payloads to the listeners of the event accordingly', function (done) { // Wait for any data sent by the TCP Emitter server. netUtils.waitForData(receiver).then(data => { // Parse the data retrieved from TCP Emitter server. const payloads = payloadUtils.parsePayload({ data }) // Assert that two payload was received. assert.strictEqual(payloads.length, 2) assert.deepStrictEqual(event, payloads[0].event) assert.deepStrictEqual(event, payloads[1].event) assert.deepStrictEqual(argsOne, payloads[0].args) assert.deepStrictEqual(argsTwo, payloads[1].args) done() }).catch(done) // Broadcast the first payload at the event which the receiver // TCP Emitter client is subscriibed to. broadcaster.write(payloadUtils .createBroadcast({ event, args: argsOne })) // Broadcast the second payload at the event which the receiver // TCP Emitter client is subscriibed to. broadcaster.write(payloadUtils .createBroadcast({ event, args: argsTwo })) }) }) }) }) }) }) })
tcp-emitter/server
test/tcp-emitter-server-test.js
JavaScript
isc
29,571
export default { isMobile(window) { return window.innerWidth <= 420 }, generateTranslation(current, columnCount, elWidth, increment) { var position = current.position var value = current.value if (increment) { if (position < columnCount-1) { position = position + 1 } } else if (position > 0) { position = position - 1 } value = position ? `-${elWidth * position}px`: '0px' return { position: position, value: value } }, browserPrefix(attr, value) { var object = {} object[`-webkit-${attr}`] = value object[`-moz-${attr}`] = value object[`-o-${attr}`] = value return object }, stripeHeight() { const PRODUCT_HEADER_CLASS = 'product__header-menu' let bodyHeight = document.body.getBoundingClientRect().height let headerHeight = document.getElementsByClassName(PRODUCT_HEADER_CLASS)[0].getBoundingClientRect().height return bodyHeight - headerHeight } }
sprintly/sprintly-kanban
app/views/pages/helpers.js
JavaScript
isc
987
import React from 'react'; import { render } from 'react-dom'; import $ from 'jquery'; import IconAuthorAttrib from './subComponents/iconAuthorAttrib' import site_footer_switch from './helpers/site_footer_switch' export default class Foot extends React.Component { render(){ // console.log(this.props, 'was this.props in foot'); let resumeIconSrc = "./assets/icons/interface.svg" let portraitIconSrc = "./assets/icons/circle.svg" // let footStyle = let localListStyle = { listStyle: "none", // border: "1px solid black", paddingLeft: "0" } let localTextSize = { fontSize: "calc(5px + .3vh)", paddingLeft: "1px" } let iconAttrib; if(this.props.selectedLayout==="twitterMimic"){ iconAttrib = <div id="attribCollection" style={localTextSize} > <ul style={localListStyle}> <li><IconAuthorAttrib {...this.props} iconImg={resumeIconSrc} iconAuthorLink={"https://smashicons.com/"} /></li> <li><IconAuthorAttrib {...this.props} iconImg={portraitIconSrc} iconAuthorLink={"http://www.freepik.com/"} /></li> </ul> both authors found at <a href="https://www.flaticon.com">www.flaticon.com</a> </div> } else { iconAttrib = <div id="iconAttribNotNeeded"></div> } return( <div id="footContainer" style={site_footer_switch(this.props)} > {/*<div><a>webform to send me e-mails without giving out my email address?</a></div>*/} {iconAttrib} </div> ) } }
MelanistOnca/Pers
public/js/foot.js
JavaScript
isc
1,660
import React, { Component } from "react"; import { autobind } from "core-decorators"; import { DiscoverAddressesFormHeader as DiscoverAddressesHeader, DiscoverAddressesFormBody } from "./Form"; @autobind class DiscoverAddressesBody extends Component { constructor(props) { super(props); this.state = this.getInitialState(); } componentWillUnmount() { this.resetState(); } getInitialState() { return { passPhrase: "", hasAttemptedDiscover: false }; } render() { const { passPhrase, hasAttemptedDiscover } = this.state; const { onSetPassPhrase, onDiscoverAddresses, onKeyDown } = this; return ( <DiscoverAddressesFormBody {...{ ...this.props, passPhrase, hasAttemptedDiscover, onSetPassPhrase, onDiscoverAddresses, onKeyDown }} /> ); } resetState() { this.setState(this.getInitialState()); } onSetPassPhrase(passPhrase) { this.setState({ passPhrase }); } onDiscoverAddresses() { if (!this.state.passPhrase) { return this.setState({ hasAttemptedDiscover: true }); } this.props.onDiscoverAddresses(this.state.passPhrase); this.resetState(); } onKeyDown(e) { if(e.keyCode == 13) { // Enter key e.preventDefault(); this.onDiscoverAddresses(); } } } export { DiscoverAddressesHeader, DiscoverAddressesBody };
oktapodia/decrediton-appveyor-test
app/components/views/GetStartedPage/DiscoverAddresses/index.js
JavaScript
isc
1,439
'use strict'; module.exports = function(err, req, res, next) { let statusCode = err.statusCode || 500; let message = err.message || 'doh!'; let stack = err.stack || ''; res.status(statusCode).json({ message: message, stack: stack }); }
joerx/proto-ci
app/modules/api/error-handler.js
JavaScript
isc
256
// adopted from: https://github.com/fshost/node-dir // Copyright (c) 2012 Nathan Cartwright <[email protected]> (MIT) var fs = require('fs') var path = require('path') var mm = require('../glob/minimatch') /** * merge two objects by extending target object with source object * @param target object to merge * @param source object to merge * @param {Boolean} [modify] whether to modify the target * @returns {Object} extended object */ function extend(target, source, modify) { var result = target ? modify ? target : extend({}, target, true) : {}; if (!source) return result; for (var key in source) { if (source.hasOwnProperty(key) && source[key] !== undefined) { result[key] = source[key]; } } return result; } /** * determine if a string is contained within an array or matches a regular expression * @param {String} str string to match * @param {Array|Regex} match array or regular expression to match against * @returns {Boolean} whether there is a match */ function matches(str, match) { if (Array.isArray(match)) { var l = match.length; for (var s = 0; s < l; s++) { if (mm(str, match[s])) { return true; } } return false; } return match.test(str); } /** * read files and call a function with the contents of each file * @param {String} dir path of dir containing the files to be read * @param {String} encoding file encoding (default is 'utf8') * @param {Object} options options hash for encoding, recursive, and match/exclude * @param {Function(error, string)} callback callback for each files content * @param {Function(error)} complete fn to call when finished */ function readFilesStream(dir, options, callback, complete) { if (typeof options === 'function') { complete = callback; callback = options; options = {}; } if (typeof options === 'string') options = { encoding: options }; options = extend({ recursive: true, encoding: 'utf8', doneOnErr: true }, options); var files = []; var done = function (err) { if (typeof complete === 'function') { if (err) return complete(err); complete(null, files); } }; fs.readdir(dir, function (err, list) { if (err) { if (options.doneOnErr === true) { if (err.code === 'EACCES') return done(); return done(err); } } var i = 0; if (options.reverse === true || (typeof options.sort == 'string' && (/reverse|desc/i).test(options.sort))) { list = list.reverse(); } else if (options.sort !== false) list = list.sort(); (function next() { var filename = list[i++]; if (!filename) return done(null, files); var file = path.join(dir, filename); fs.stat(file, function (err, stat) { if (err && options.doneOnErr === true) return done(err); if (stat && stat.isDirectory()) { if (options.recursive) { if (options.matchDir && !matches(filename, options.matchDir)) return next(); if (options.excludeDir && matches(filename, options.excludeDir)) return next(); readFilesStream(file, options, callback, function (err, sfiles) { if (err && options.doneOnErr === true) return done(err); files = files.concat(sfiles); next(); }); } else next(); } else if (stat && stat.isFile()) { if (options.match && !matches(filename, options.match)) return next(); if (options.exclude && matches(filename, options.exclude)) return next(); if (options.filter && !options.filter(filename)) return next(); if (options.shortName) files.push(filename); else files.push(file); var stream = fs.createReadStream(file); stream.setEncoding(options.encoding); stream.on('error', function (err) { if (options.doneOnErr === true) return done(err); next(); }); if (callback.length > 3) if (options.shortName) callback(null, stream, filename, next); else callback(null, stream, file, next); else callback(null, stream, next); } else { next(); } }); })(); }); } module.exports = readFilesStream;
akileez/toolz
src/stream/read-file-stream.js
JavaScript
isc
4,333
var http = require('http'); var util = require('util'); module.exports.createServer = createServer; module.exports.Server = Server; module.exports.install = install; function createServer(listener) { var server = http.createServer.apply(http, arguments); return install(server); } function Server() { http.Server.apply(this, arguments); install(this); } util.inherits(Server, http.Server); function install(server) { var conns = new Map([]); server.on('connection', function (conn) { conns.set(conn, null); conn.on('close', function () { conns.delete(conn); }); }); server.on('request', function (req, res) { var conn = req.connection; conns.set(conn, res); res.on('finish', function () { conns.set(conn, null); }); }); server.gracefulClose = function (done) { conns.forEach(function (res, conn) { if (res !== null && !res.headersSent) { debug('sending response with "Connection: close"'); res.setHeader('Connection', 'close'); } else if (res !== null) { res.on('finish', function () { setIdleTimeout(server, conn); }); } else { setIdleTimeout(server, conn); } }); return server.close.apply(server, arguments); }; debug('graceful-http-server installed'); return server; } function setIdleTimeout(server, conn) { var onTimeout = function () { debug('closing connection'); conn.destroy(); server.removeListener('request', onRequest); }; conn.setTimeout(400, onTimeout); var onRequest = function (req, res) { if (conn === req.connection) { debug('sending response with "Connection: close"'); res.setHeader('Connection', 'close'); conn.removeListener('timeout', onTimeout); server.removeListener('request', onRequest); } }; server.on('request', onRequest); } function debug(message) { // console.log.apply(console, arguments); }
AtsushiSuzuki/http-graceful-close
index.js
JavaScript
isc
2,024
const {createServer} = require('http') const {readFileSync} = require('fs') const template = readFileSync(__dirname + '/index.html') createServer((req, res) => { if (req.url === '/favicon.ico') { res.writeHead(404) res.end() } else if (req.headers.referer && req.url !== '/') { res.writeHead(302, { 'Location': 'ob:/' + req.url.replace('ob://', '') }) res.end() } else { res.end(template) } }).listen(8888)
overra/oblink
index.js
JavaScript
isc
447
'use strict'; const XmlNode = require('./XmlNode'); /** A processing instruction within an XML document. @public */ class XmlProcessingInstruction extends XmlNode { /** @param {string} name @param {string} [content] */ constructor(name, content = '') { super(); /** Name of this processing instruction. Also sometimes referred to as the processing instruction "target". @type {string} @public */ this.name = name; /** Content of this processing instruction. @type {string} @public */ this.content = content; } get type() { return XmlNode.TYPE_PROCESSING_INSTRUCTION; } toJSON() { return Object.assign(XmlNode.prototype.toJSON.call(this), { name: this.name, content: this.content, }); } } module.exports = XmlProcessingInstruction;
rgrove/parse-xml
src/lib/XmlProcessingInstruction.js
JavaScript
isc
841
import auth from './authReducer' export { auth }
nattatorn-dev/expo-with-realworld
modules/Auth/reducers/index.js
JavaScript
mit
50
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M2 6.67V22h20V6H8.3l8.26-3.34L15.88 1 2 6.67zM7 20c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm13-8h-2v-2h-2v2H4V8h16v4z" }), 'RadioSharp');
AlloyTeam/Nuclear
components/icon/esm/radio-sharp.js
JavaScript
mit
272
/** * @author: @NikhilS */ require('ts-node/register'); var helpers = require('./helpers'); exports.config = { baseUrl: 'http://localhost:3000/', // use `npm run e2e` specs: [ helpers.root('src/**/**.e2e.ts'), helpers.root('src/**/*.e2e.ts') ], exclude: [], framework: 'jasmine2', allScriptsTimeout: 110000, jasmineNodeOpts: { showTiming: true, showColors: true, isVerbose: false, includeStackTrace: false, defaultTimeoutInterval: 400000 }, directConnect: true, capabilities: { 'browserName': 'chrome', 'chromeOptions': { 'args': ['show-fps-counter=true'] } }, onPrepare: function() { browser.ignoreSynchronization = true; }, /** * Angular 2 configuration * * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching * `rootEl` */ useAllAngular2AppRoots: true };
nikhilsarvaiye/PeopleManager
config/protractor.conf.js
JavaScript
mit
931
// Include assertion library "Should" var should = require('should'); // jshint ignore:line var PowerupElection = require('polyball/shared/powerups/PowerupElection.js'); var Vote = require('polyball/shared/model/Vote.js'); // An example test that runs using Mocha and uses "Should" for assertion testing describe('Powerup Election', function() { "use strict"; describe('#addVote()', function() { it('should increase the size of the votes array by 1', function() { var pe = new PowerupElection({powerups: [1,2,3]}); pe.addVote(new Vote({spectatorID: 1, powerup:1})); pe.votes.length.should.equal(1); }); it('should increase the size of the votes array by 1 for each added vote', function() { var pe = new PowerupElection({powerups: [1,2,3]}); var n = 10; for (var i = 0; i < n; i++){ pe.addVote(new Vote({spectatorID: i, powerup:1})); } pe.votes.length.should.equal(n); }); it('should replace the current vote with new vote', function() { var pe = new PowerupElection({powerups: [1,2,3]}); pe.addVote(new Vote({spectatorID: 1, powerup:1})); pe.addVote(new Vote({spectatorID: 1, powerup:2})); pe.votes.length.should.equal(1); (pe.votes[0]).powerup.should.equal(2); }); it('should replace the current vote with new vote for each additional ' + 'vote from same spectator', function() { var pe = new PowerupElection({powerups: [1,2,3]}); var n = 10; var firstVote = 1; var secondVote = 2; for (var i = 0; i < n; i++){ pe.addVote(new Vote({spectatorID: i, powerup: firstVote})); pe.addVote(new Vote({spectatorID: i, powerup: secondVote})); } pe.votes.length.should.equal(n); pe.votes.forEach(function(elm){ elm.powerup.should.equal(secondVote); }); }); }); describe('#removeVote()', function() { it('should decrease the size of the votes array by 1', function() { var pe = new PowerupElection({powerups: [1,2,3]}); pe.addVote(new Vote({spectatorID: 1, powerup:1})); pe.removeVote(1); pe.votes.length.should.equal(0); }); it('should decrease the size of the votes array by 1 for each additional call', function() { var pe = new PowerupElection({powerups: [1,2,3]}); var n = 10; for (var i = 0; i < n; i++){ pe.addVote(new Vote({spectatorID: i, powerup:1})); } for (i = 0; i < n; i++){ pe.removeVote(i); } pe.votes.length.should.equal(0); }); }); describe('#getWinner()', function() { it('should return the powerup with the most votes ', function() { var pe = new PowerupElection({powerups: [1,2,3]}); pe.addVote(new Vote({spectatorID: 1, powerup:1})); pe.addVote(new Vote({spectatorID: 2, powerup:2})); pe.addVote(new Vote({spectatorID: 3, powerup:2})); pe.getWinner().should.equal(2); }); it('should decrease the size of the votes array by 1 for each additional call', function() { var pe = new PowerupElection({powerups: [1,2,3]}); var winner = pe.getWinner(); (winner != null).should.be.ok; //jshint ignore:line [1,2,3].should.containEql(winner); }); }); });
polyball/polyball
polyball/tests/shared/model/PowerupElectionTests.js
JavaScript
mit
3,626
version https://git-lfs.github.com/spec/v1 oid sha256:92a4f24d3a4ad4de3bbed1013b330d5ca23f4d0cbeed4a7536dcd6b3cd3e492d size 4461
yogeshsaroya/new-cdnjs
ajax/libs/dojo/1.7.2/nls/nb/colors.js
JavaScript
mit
129
version https://git-lfs.github.com/spec/v1 oid sha256:50ef15b4c4f47fb98410127b48f1db6e32dc7f759cab685bd27afbfcfd7fdd38 size 23119
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.17.1/jsonp/jsonp-coverage.js
JavaScript
mit
130
/* transparency component */ define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/_base/array', 'dojo/query', 'dojo/dom-style', 'dijit/PopupMenuItem', 'dijit/TooltipDialog', 'dijit/form/HorizontalSlider', 'dijit/form/HorizontalRuleLabels' ], function ( declare, lang, array, query, domStyle, PopupMenuItem, TooltipDialog, HorizontalSlider, HorizontalRuleLabels ) { return declare(PopupMenuItem, { layer: null, constructor: function (options) { options = options || {}; lang.mixin(this, options); }, postCreate: function () { this.inherited(arguments); var transparencySlider = new HorizontalSlider({ value: this.layer.layer.getOpacity(), minimum: 0, maximum: 1, discreteValues: 21, intermediateChanges: true, showButtons: false, onChange: lang.hitch(this, function (value) { this.layer.layer.setOpacity(value); array.forEach(query('.' + this.layer.id + '-layerLegendImage'), function (img) { domStyle.set(img, 'opacity', value); }); }) }); var rule = new HorizontalRuleLabels({ labels: ['100%', '50%', '0%'], style: 'height:1em;font-size:75%;' }, transparencySlider.bottomDecoration); rule.startup(); transparencySlider.startup(); this.popup = new TooltipDialog({ style: 'width:200px;', content: transparencySlider }); domStyle.set(this.popup.connectorNode, 'display', 'none'); this.popup.startup(); } }); });
pri0ri7y/OpenMap
js/widgets/templates/layercontrol/plugins/Transparency.js
JavaScript
mit
1,864
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // Version 2, December 2004 // // Copyright (C) 2004 Sam Hocevar <[email protected]> // // Everyone is permitted to copy and distribute verbatim or modified // copies of this license document, and changing it is allowed as long // as the name is changed. // // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION // // 0. You just DO WHAT THE FUCK YOU WANT TO. function Map3DGeometry (data, innerRadius) { if ((arguments.length < 2) || isNaN(parseFloat(innerRadius)) || !isFinite(innerRadius) || (innerRadius < 0)) { // if no valid inner radius is given, do not extrude innerRadius = 42; } THREE.Geometry.call (this); // data.vertices = [lat, lon, ...] // data.polygons = [[poly indices, hole i-s, ...], ...] // data.triangles = [tri i-s, ...] var i, uvs = []; for (i = 0; i < data.vertices.length; i += 2) { var lon = data.vertices[i]; var lat = data.vertices[i + 1]; // colatitude var phi = +(90 - lat) * 0.01745329252; // azimuthal angle var the = +(180 - lon) * 0.01745329252; // translate into XYZ coordinates var wx = Math.sin (the) * Math.sin (phi) * -1; var wz = Math.cos (the) * Math.sin (phi); var wy = Math.cos (phi); // equirectangular projection var wu = 0.25 + lon / 360.0; var wv = 0.5 + lat / 180.0; this.vertices.push (new THREE.Vector3 (wx, wy, wz)); uvs.push (new THREE.Vector2 (wu, wv)); } var n = this.vertices.length; if (innerRadius <= 1) { for (i = 0; i < n; i++) { var v = this.vertices[i]; this.vertices.push (v.clone ().multiplyScalar (innerRadius)); } } for (i = 0; i < data.triangles.length; i += 3) { var a = data.triangles[i]; var b = data.triangles[i + 1]; var c = data.triangles[i + 2]; this.faces.push( new THREE.Face3( a, b, c, [ this.vertices[a], this.vertices[b], this.vertices[c] ] ) ); this.faceVertexUvs[ 0 ].push( [ uvs[ a ], uvs[ b ], uvs[ c ] ]); if ((0 < innerRadius) && (innerRadius <= 1)) { this.faces.push( new THREE.Face3( n + b, n + a, n + c, [ this.vertices[b].clone ().multiplyScalar (-1), this.vertices[a].clone ().multiplyScalar (-1), this.vertices[c].clone ().multiplyScalar (-1) ] ) ); this.faceVertexUvs[ 0 ].push( [ uvs[ b ], uvs[ a ], uvs[ c ] ]); // shitty uvs to make 3js exporter happy } } // extrude if (innerRadius < 1) { for (i = 0; i < data.polygons.length; i++) { var polyWithHoles = data.polygons[i]; for (var j = 0; j < polyWithHoles.length; j++) { var polygonOrHole = polyWithHoles[j]; for (var k = 0; k < polygonOrHole.length; k++) { var a = polygonOrHole[k], b = polygonOrHole[(k + 1) % polygonOrHole.length]; var va1 = this.vertices[a], vb1 = this.vertices[b]; var va2 = this.vertices[n + a], vb2 = this.vertices[n + b]; var normal; if (j < 1) { // polygon normal = vb1.clone ().sub (va1).cross ( va2.clone ().sub (va1) ).normalize (); this.faces.push ( new THREE.Face3( a, b, n + a, [ normal, normal, normal ] ) ); this.faceVertexUvs[ 0 ].push( [ uvs[ a ], uvs[ b ], uvs[ a ] ]); // shitty uvs to make 3js exporter happy if (innerRadius > 0) { this.faces.push ( new THREE.Face3( b, n + b, n + a, [ normal, normal, normal ] ) ); this.faceVertexUvs[ 0 ].push( [ uvs[ b ], uvs[ b ], uvs[ a ] ]); // shitty uvs to make 3js exporter happy } } else { // hole normal = va2.clone ().sub (va1).cross ( vb1.clone ().sub (va1) ).normalize (); this.faces.push ( new THREE.Face3( b, a, n + a, [ normal, normal, normal ] ) ); this.faceVertexUvs[ 0 ].push( [ uvs[ b ], uvs[ a ], uvs[ a ] ]); // shitty uvs to make 3js exporter happy if (innerRadius > 0) { this.faces.push ( new THREE.Face3( b, n + a, n + b, [ normal, normal, normal ] ) ); this.faceVertexUvs[ 0 ].push( [ uvs[ b ], uvs[ a ], uvs[ b ] ]); // shitty uvs to make 3js exporter happy } } } } } } this.computeFaceNormals (); this.boundingSphere = new THREE.Sphere (new THREE.Vector3 (), 1); } Map3DGeometry.prototype = Object.create (THREE.Geometry.prototype);
beeva-hodeilopez/beeva-data-visualization-hackathon
three-js/map3d.js
JavaScript
mit
4,972
'use strict'; angular.module('ucllApp') .controller('LogoutController', function (Auth) { Auth.logout(); });
craftworkz/ucll-workshop-jhipster
jhipster-demo/src/main/webapp/scripts/app/account/logout/logout.controller.js
JavaScript
mit
126
/* * Copyright (C) 2012 David Geary. This code is from the book * Core HTML5 Canvas, published by Prentice-Hall in 2012. * * License: * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * The Software may not be used to create training material of any sort, * including courses, books, instructional videos, presentations, etc. * without the express written consent of David Geary. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), CENTROID_RADIUS = 10, CENTROID_STROKE_STYLE = 'rgba(0, 0, 0, 0.5)', CENTROID_FILL_STYLE ='rgba(80, 190, 240, 0.6)', GUIDEWIRE_STROKE_STYLE = 'goldenrod', GUIDEWIRE_FILL_STYLE = 'rgba(85, 190, 240, 0.6)', TEXT_FILL_STYLE = 'rgba(100, 130, 240, 0.5)', TEXT_STROKE_STYLE = 'rgba(200, 0, 0, 0.7)', TEXT_SIZE = 64, GUIDEWIRE_STROKE_STYLE = 'goldenrod', GUIDEWIRE_FILL_STYLE = 'rgba(85, 190, 240, 0.6)', circle = { x: canvas.width/2, y: canvas.height/2, radius: 200 }; // Functions..................................................... function drawGrid(color, stepx, stepy) { context.save() context.shadowColor = undefined; context.shadowOffsetX = 0; context.shadowOffsetY = 0; context.strokeStyle = color; context.fillStyle = '#ffffff'; context.lineWidth = 0.5; context.fillRect(0, 0, context.canvas.width, context.canvas.height); for (var i = stepx + 0.5; i < context.canvas.width; i += stepx) { context.beginPath(); context.moveTo(i, 0); context.lineTo(i, context.canvas.height); context.stroke(); } for (var i = stepy + 0.5; i < context.canvas.height; i += stepy) { context.beginPath(); context.moveTo(0, i); context.lineTo(context.canvas.width, i); context.stroke(); } context.restore(); } // Drawing functions............................................. function drawCentroid() { context.beginPath(); context.save(); context.strokeStyle = CENTROID_STROKE_STYLE; context.fillStyle = CENTROID_FILL_STYLE; context.arc(circle.x, circle.y, CENTROID_RADIUS, 0, Math.PI*2, false); context.stroke(); context.fill(); context.restore(); } function drawCircularText(string, startAngle, endAngle) { var radius = circle.radius, angleDecrement = (startAngle - endAngle)/(string.length-1), angle = parseFloat(startAngle), index = 0, character; context.save(); context.fillStyle = TEXT_FILL_STYLE; context.strokeStyle = TEXT_STROKE_STYLE; context.font = TEXT_SIZE + 'px Lucida Sans'; while (index < string.length) { character = string.charAt(index); context.save(); context.beginPath(); context.translate( circle.x + Math.cos(angle) * radius, circle.y - Math.sin(angle) * radius); context.rotate(Math.PI/2 - angle); context.fillText(character, 0, 0); context.strokeText(character, 0, 0); angle -= angleDecrement; index++; context.restore(); } context.restore(); } // Initialization................................................ if (navigator.userAgent.indexOf('Opera') === -1) context.shadowColor = 'rgba(0, 0, 0, 0.4)'; context.shadowOffsetX = 2; context.shadowOffsetY = 2; context.shadowBlur = 5; context.textAlign = 'center'; context.textBaseline = 'middle'; drawGrid('lightgray', 10, 10); drawCentroid(); drawCircularText("Clockwise around the circle", Math.PI*2, Math.PI/8);
yuesir/HTML5-Canvas
ch03/example-3.9/example.js
JavaScript
mit
4,545
// @flow import React, { type Node } from 'react'; import classnames from 'classnames'; import { Tooltip as ReactAccessibleTooltip } from 'react-accessible-tooltip'; import './tooltip.scss'; function Tooltip({ label, overlay }: { label: Node, overlay: Node }) { return ( <ReactAccessibleTooltip className="tooltip" label={({ labelAttributes }: { labelAttributes: Object }) => ( <span className="tooltip__label" {...labelAttributes}> <strong>{label}</strong> </span> )} overlay={({ overlayAttributes, isHidden, }: { overlayAttributes: Object, isHidden: boolean, }) => ( <span className={classnames('tooltip__overlay', { 'tooltip__overlay--hidden': isHidden, })} {...overlayAttributes} > <span className="tooltip__overlay-inner">{overlay}</span> </span> )} /> ); } export default Tooltip;
ryami333/react-accessible-tooltip
packages/docs/src/components/Tooltip/Tooltip.js
JavaScript
mit
1,166
var router = new AiRouter(); router.route('/',{ name:'HOME', action:function(params, query) { document.getElementById("switch").innerHTML = "Changed to Home page!"; console.log('Home Page'); }, }); router.route('/projects/:projectId/tests/:testId',{ name:'HOME', action:function(params, query) { document.getElementById("switch").innerHTML = "Changed to Projects page!"; console.log(params); console.log(query); }, }); router.route('/posts/:postId/comments/:commentId',{ name:'HOME', beforeAction:function(params, query) { console.log('This function trigger before Action'); console.log(params); console.log(query); }, action:function(params, query) { document.getElementById("switch").innerHTML = "Changed to Blog page!"; console.log('This function trigger Action'); console.log(params); console.log(query); }, afterAction:function(params, query) { console.log('This function triggers after Action'); console.log(params); console.log(query); } }); router.notFound({ action:function() { document.getElementById("switch").innerHTML = "No Route Found page!"; console.log('No Route Found page'); } }); function go1() { router.go('/demo/#/'); } function go2() { router.go('/demo/#/projects/123/tests/321'); } function go3() { router.go('/demo/#/posts/123/comments/A2516BC'); } function go4() { var things = ['Rock', 'Paper', 'Scissor']; var thing = things[Math.floor(Math.random()*things.length)]; router.go('/demo/#/'+thing); }
nedyalkovV/AiRouter
demo/demo/demo.js
JavaScript
mit
1,653
User.inject({ statics: { log: function() { var str = Array.create(arguments).join(' '); if (session && session.user) str = '[' + session.user.name + '] ' + str; app.log(str); }, logError: function(title, e) { var shortDesc = (e.fileName ? 'Error in ' + e.fileName + ', Line ' + e.lineNumber : 'Error') + ' (' + title + '): ' + e; // In some situations, the global req object might not be available, // so make sure we check to not produce another error. if (global.req && req.path) shortDesc += '\n(' + req.path + ')'; // Generate the stacktrace: var longDesc = shortDesc; if (e.javaException) { var sw = new java.io.StringWriter(); e.javaException.printStackTrace(new java.io.PrintWriter(sw)); longDesc += '\nStacktrace:\n' + sw.toString(); } User.log(longDesc); var from = app.properties.errorFromAddress || app.properties.serverAddress; var to = app.properties.errorToAddress; if (from && to) { try { // Send an error mail: var mail = new Mail(); mail.setFrom(from); mail.setTo(to); mail.setSubject('[' + new Date().format( 'yyyy/MM/dd HH:mm:ss') + '] ' + title); if (session.user != null) longDesc = '[' + session.user.name + '] ' + longDesc; mail.addText(longDesc); mail.send(); } catch (e) { } } return shortDesc; }, getHost: function() { var host = req.data.http_remotehost; var address = java.net.InetAddress.getByName(host); var name = address && address.getCanonicalHostName(); return name || host; } } });
lehni/boots
base/helma/User/functions.js
JavaScript
mit
1,599
/** * @since 2019-07-19 14:13 * @author vivaxy * * Call simple function. 7.964s * Call function await promise. 16.687s * Call function with if logic. 9.612s */ let resolved = false; function request() { return new Promise(function(resolve) { setTimeout(function() { resolve(true); }, 1000); }); } const promise = request(); async function callSimpleFunction() { return 0; } async function callFunctionWithAwaitPromise() { await promise; return 0; } async function callFunctionWithIfLogic() { if (resolved) { return 0; } await promise; return 0; } function getTime(s) { return (Date.now() - s) / 1000 + 's'; } (async function() { await promise; resolved = true; const loopCount = 1e8; let s = Date.now(); for (let i = 0; i < loopCount; i++) { await callSimpleFunction(); } console.log('Call simple function.', getTime(s)); s = Date.now(); for (let i = 0; i < loopCount; i++) { await callFunctionWithAwaitPromise(); } console.log('Call function await promise.', getTime(s)); s = Date.now(); for (let i = 0; i < loopCount; i++) { await callFunctionWithIfLogic(); } console.log('Call function with if logic.', getTime(s)); })();
vivaxy/course
benchmark/await-resolved-promise/index.js
JavaScript
mit
1,223
'use strict'; FbFriends.StatsView = Backbone.View.extend({ events: { }, initialize: function(options) { _.extend(this, options); this.friends.on('reset', this.render, this); }, render: function(event) { this.showSexRepartition(); // this.showTopVille(); this.showRelationRepartition(); }, showSexRepartition: function() { var repartition = this.friends.getRepartitionSexe(); this.$el.find(".pie-sexes").highcharts({ chart: { plotBackgroundColor: null, plotBorderWidth: 0, plotShadow: false }, title: { text: 'Sexes', align: 'center', verticalAlign: 'middle', y: 50 }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions: { pie: { dataLabels: { enabled: true, distance: -50, style: { fontWeight: 'bold', color: 'white', textShadow: '0px 1px 2px black' } }, startAngle: -90, endAngle: 90, center: ['50%', '75%'] } }, series: [{ type: 'pie', name: 'Sexes', innerSize: '50%', data: [ ['Homme', repartition["male"] || 0.0], ['Femme', repartition["female"] || 0.0], ['Non défini', repartition[""] || 0.0] ] }] }); }, showRelationRepartition: function() { var repartition = this.friends.getRelationShipPercent(); this.$el.find(".pie-relation").highcharts({ chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false }, title: { text: 'Relations' }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {point.percentage:.1f} %', style: { color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black' } } } }, series: [{ type: 'pie', data: _.pairs(repartition) }] }); }, // not yet implemented showTopVille: function() { // var data = this.friends.getTopVillesData(); // // this.$el.find('.pie-top-villes').highcharts({ // chart: { // type: 'column' // }, // title: { // text: 'Top 10 des villes' // }, // xAxis: { // categories: [] // }, // yAxis: { // min: 0 // }, // tooltip: { // headerFormat: '<span style="font-size:10px">{point.key}</span><table>', // pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' + // '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>', // footerFormat: '</table>', // shared: true, // useHTML: true // }, // plotOptions: { // column: { // pointPadding: 0.2, // borderWidth: 0 // } // }, // series: [{ // name: 'Tokyo', // data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] // // }, { // name: 'New York', // data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3] // // }, { // name: 'London', // data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2] // // }, { // name: 'Berlin', // data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1] // // }] // }); } });
FXHibon/facebook-fun
frontend/app/friends/statistics/StatsView.js
JavaScript
mit
4,807
'use strict'; const Perceptron = require('./perceptron'); const PerceptronTrainer = require('./perceptron.trainer'); const trainer = new PerceptronTrainer(); trainer.setLearningRate(2.0); // and-perceptron: weights: [1,4], bias: -5 const perceptron = new Perceptron(); perceptron.setWeights([-20,-30]); perceptron.setBias(1); trainer.train(perceptron, [ { inputs: [0 ,0], ideal: 0 }, { inputs: [1 ,0], ideal: 0 }, { inputs: [0 ,1], ideal: 0 }, { inputs: [1 ,1], ideal: 1 }, ]); console.log({ perceptron: perceptron.getConnections(), inputs: [1, 0], output: perceptron.output() }); // or-perceptron: weights: [1,2], bias: -1 perceptron.setWeights([-20,-30]); perceptron.setBias(1); trainer.train(perceptron, [ { inputs: [0 ,0], ideal: 0 }, { inputs: [1 ,0], ideal: 1 }, { inputs: [0 ,1], ideal: 1 }, { inputs: [1 ,1], ideal: 1 }, ]); console.log({ perceptron: perceptron.getConnections(), inputs: [1, 0], output: perceptron.output() });
pascalvree/example-perceptron-implementation
src/example.js
JavaScript
mit
998
import { getElementIfNotEmpty } from './getElementIfNotEmpty.js'; export function getStackDataIfNotEmpty(viewportIndex) { const element = getElementIfNotEmpty(viewportIndex); if (!element) { return; } const stackToolData = cornerstoneTools.getToolState(element, 'stack'); if (!stackToolData || !stackToolData.data || !stackToolData.data.length) { return; } const stack = stackToolData.data[0]; if (!stack) { return; } return stack; }
NucleusIo/HealthGenesis
viewerApp/Packages/ohif-viewerbase/client/lib/getStackDataIfNotEmpty.js
JavaScript
mit
518
// Load the test base const reload = require('require-reload')(require); const tests = reload('../base/tests'); module.exports = function promiseTestRunner (qb) { Object.keys(tests).forEach(describeName => { describe(describeName, async () => { let currentSuite = tests[describeName]; Object.keys(currentSuite).forEach(testDesc => { it(testDesc, done => { const methodObj = currentSuite[testDesc]; const methodNames = Object.keys(methodObj); let results = []; methodNames.forEach(name => { const args = methodObj[name]; const method = qb[name]; if (args[0] === 'multiple') { args.shift(); args.forEach(argSet => { results.push(method.apply(qb, argSet)); }); } else { results.push(method.apply(qb, args)); } }); const promise = results.pop(); promise.then(result => { // expect(result.rows).is.an('array'); expect(result.rowCount()).toEqual(expect.anything()); expect(result.columnCount()).toEqual(expect.anything()); return done(); }).catch(e => done(e)); }); }); }); }); describe('DB update tests -', () => { beforeAll(done => { let sql = qb.driver.truncate('create_test'); qb.query(sql).then(() => done()) .catch(err => done(err)); }); it('Test Insert', async () => { const promise = await qb.set('id', 98) .set('key', '84') .set('val', Buffer.from('120')) .insert('create_test'); expect(promise).toEqual(expect.anything()); }); it('Test Insert Object', async () => { const promise = await qb.insert('create_test', { id: 587, key: 1, val: Buffer.from('2') }); expect(promise).toEqual(expect.anything()); }); it('Test Update', async () => { const promise = await qb.where('id', 7) .update('create_test', { id: 7, key: 'gogle', val: Buffer.from('non-word') }); expect(promise).toEqual(expect.anything()); }); it('Test set Array Update', async () => { let object = { id: 22, key: 'gogle', val: Buffer.from('non-word') }; const promise = await qb.set(object) .where('id', 22) .update('create_test'); expect(promise).toEqual(expect.anything()); }); it('Test where set update', async () => { const promise = await qb.where('id', 36) .set('id', 36) .set('key', 'gogle') .set('val', Buffer.from('non-word')) .update('create_test'); expect(promise).toEqual(expect.anything()); }); it('Test delete', async () => { const promise = await qb.delete('create_test', {id: 5}); expect(promise).toEqual(expect.anything()); }); it('Delete with where', async () => { const promise = await qb.where('id', 5) .delete('create_test'); expect(promise).toEqual(expect.anything()); }); it('Delete multiple where values', async () => { const promise = await qb.delete('create_test', { id: 5, key: 'gogle' }); expect(promise).toEqual(expect.anything()); }); }); describe('Batch tests -', () => { it('Test Insert Batch', async () => { const data = [ { id: 544, key: 3, val: Buffer.from('7') }, { id: 89, key: 34, val: Buffer.from('10 o\'clock') }, { id: 48, key: 403, val: Buffer.from('97') } ]; const promise = await qb.insertBatch('create_test', data); expect(promise).toEqual(expect.anything()); }); it('Test Update Batch', async () => { const data = [{ id: 480, key: 49, val: '7x7' }, { id: 890, key: 100, val: '10x10' }]; const affectedRows = qb.updateBatch('create_test', data, 'id'); expect(affectedRows).toBe(2); }); }); describe('Grouping tests -', () => { it('Using grouping method', async () => { const promise = await qb.select('id, key as k, val') .from('create_test') .groupStart() .where('id >', 1) .where('id <', 900) .groupEnd() .limit(2, 1) .get(); expect(promise).toEqual(expect.anything()); }); it('Using where first grouping', async () => { const promise = await qb.select('id, key as k, val') .from('create_test') .where('id !=', 5) .groupStart() .where('id >', 1) .where('id <', 900) .groupEnd() .limit(2, 1) .get(); expect(promise).toEqual(expect.anything()); }); it('Using or grouping method', async () => { const promise = await qb.select('id, key as k, val') .from('create_test') .groupStart() .where('id >', 1) .where('id <', 900) .groupEnd() .orGroupStart() .where('id', 0) .groupEnd() .limit(2, 1) .get(); expect(promise).toEqual(expect.anything()); }); it('Using or not grouping method', async () => { const promise = await qb.select('id, key as k, val') .from('create_test') .groupStart() .where('id >', 1) .where('id <', 900) .groupEnd() .orNotGroupStart() .where('id', 0) .groupEnd() .limit(2, 1) .get(); expect(promise).toEqual(expect.anything()); }); }); describe('Get compiled - ', () => { it('getCompiledSelect', () => { const sql = qb.select('id, key as k, val') .from('create_test') .groupStart() .where('id >', 1) .where('id <', 900) .groupEnd() .limit(2, 1) .getCompiledSelect(); expect(sql).toMatchSnapshot(); }); it('getCompiledSelect 2', () => { const sql = qb.select('id, key as k, val') .groupStart() .where('id >', 1) .where('id <', 900) .groupEnd() .limit(2, 1) .getCompiledSelect('create_test'); expect(sql).toMatchSnapshot(); }); it('getCompiledInsert', () => { const sql = qb.set({ id: 587, key: 1, val: Buffer.from('2') }).getCompiledInsert('create_test'); expect(sql).toMatchSnapshot(); }); it('getCompiledUpdate', () => { const sql = qb.where('id', 36) .set('id', 36) .set('key', 'gogle') .set('val', Buffer.from('non-word')) .getCompiledUpdate('create_test'); expect(sql).toMatchSnapshot(); }); it('getCompiledDelete', () => { const sql = qb.where({id: 5}).getCompiledDelete('create_test'); expect(sql).toMatchSnapshot(); }); }); };
timw4mail/node-query
test/base/adapterPromiseTestRunner.js
JavaScript
mit
6,181
var Quad = Class.create(Renderable, { initialize: function($super, width, height, position) { this.width = width; this.height = height; $super(); if (position) this.orientation.setPosition(position); }, setWidth: function(width) { this.setSize(width, this.height); }, setHeight: function(height) { this.setSize(this.width, height); }, setSize: function(width, height) { this.width = width; this.height = height; this.rebuildAll(); }, init: function(vertices, colors, textureCoords) { this.draw_mode = GL_TRIANGLE_STRIP; var width = this.width, height = this.height; vertices.push(-width/2, -height/2, 0); vertices.push(-width/2, height/2, 0); vertices.push( width/2, -height/2, 0); vertices.push( width/2, height/2, 0); textureCoords.push(0, 1); textureCoords.push(0, 0); textureCoords.push(1, 1); textureCoords.push(1, 0); colors.push(1,1,1,1); colors.push(1,1,1,1); colors.push(1,1,1,1); colors.push(1,1,1,1); } });
sinisterchipmunk/rails-webgl
public/javascripts/objects/quad.js
JavaScript
mit
1,039
/* * SpriteContainer * Visit http://createjs.com/ for documentation, updates and examples. * * Copyright (c) 2010 gskinner.com, inc. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ // namespace: //this.createjs = this.createjs||{}; (function() { "use strict"; /** * A SpriteContainer is a nestable display list that enables aggressively optimized rendering of bitmap content. * In order to accomplish these optimizations, SpriteContainer enforces a few restrictions on its content. * * Restrictions: * - only Sprite, SpriteContainer, BitmapText and DOMElement are allowed to be added as children. * - a spriteSheet MUST be either be passed into the constructor or defined on the first child added. * - all children (with the exception of DOMElement) MUST use the same spriteSheet. * * <h4>Example</h4> * * var data = { * images: ["sprites.jpg"], * frames: {width:50, height:50}, * animations: {run:[0,4], jump:[5,8,"run"]} * }; * var spriteSheet = new createjs.SpriteSheet(data); * var container = new createjs.SpriteContainer(spriteSheet); * container.addChild(spriteInstance, spriteInstance2); * container.x = 100; * * <strong>Note:</strong> SpriteContainer is not included in the minified version of EaselJS. * * @class SpriteContainer * @extends Container * @constructor * @param {SpriteSheet} [spriteSheet] The spriteSheet to use for this SpriteContainer and its children. **/ function SpriteContainer(spriteSheet) { this.Container_constructor(); // public properties: /** * The SpriteSheet that this container enforces use of. * @property spriteSheet * @type {SpriteSheet} * @readonly **/ this.spriteSheet = spriteSheet; } var p = createjs.extend(SpriteContainer, createjs.Container); /** * <strong>REMOVED</strong>. Removed in favor of using `MySuperClass_constructor`. * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} * for details. * * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. * * @method initialize * @protected * @deprecated */ // p.initialize = function() {}; // searchable for devs wondering where it is. // public methods: /** * Adds a child to the top of the display list. * Only children of type SpriteContainer, Sprite, Bitmap, BitmapText, or DOMElement are allowed. * The child must have the same spritesheet as this container (unless it's a DOMElement). * If a spritesheet hasn't been defined, this container uses this child's spritesheet. * * <h4>Example</h4> * container.addChild(bitmapInstance); * * You can also add multiple children at once: * * container.addChild(bitmapInstance, shapeInstance, textInstance); * * @method addChild * @param {DisplayObject} child The display object to add. * @return {DisplayObject} The child that was added, or the last child if multiple children were added. **/ p.addChild = function(child) { if (child == null) { return child; } if (arguments.length > 1) { return this.addChildAt.apply(this, Array.prototype.slice.call(arguments).concat([this.children.length])); } else { return this.addChildAt(child, this.children.length); } }; /** * Adds a child to the display list at the specified index, bumping children at equal or greater indexes up one, and * setting its parent to this Container. * Only children of type SpriteContainer, Sprite, Bitmap, BitmapText, or DOMElement are allowed. * The child must have the same spritesheet as this container (unless it's a DOMElement). * If a spritesheet hasn't been defined, this container uses this child's spritesheet. * * <h4>Example</h4> * addChildAt(child1, index); * * You can also add multiple children, such as: * * addChildAt(child1, child2, ..., index); * * The index must be between 0 and numChildren. For example, to add myShape under otherShape in the display list, * you could use: * * container.addChildAt(myShape, container.getChildIndex(otherShape)); * * This would also bump otherShape's index up by one. Fails silently if the index is out of range. * * @method addChildAt * @param {DisplayObject} child The display object to add. * @param {Number} index The index to add the child at. * @return {DisplayObject} Returns the last child that was added, or the last child if multiple children were added. **/ p.addChildAt = function(child, index) { var l = arguments.length; var indx = arguments[l-1]; // can't use the same name as the index param or it replaces arguments[1] if (indx < 0 || indx > this.children.length) { return arguments[l-2]; } if (l > 2) { for (var i=0; i<l-1; i++) { this.addChildAt(arguments[i], indx+i); } return arguments[l-2]; } if (child._spritestage_compatibility >= 1) { // The child is compatible with SpriteStage/SpriteContainer. } else { console && console.log("Error: You can only add children of type SpriteContainer, Sprite, BitmapText, or DOMElement [" + child.toString() + "]"); return child; } if (child._spritestage_compatibility <= 4) { var spriteSheet = child.spriteSheet; if ((!spriteSheet || !spriteSheet._images || spriteSheet._images.length > 1) || (this.spriteSheet && this.spriteSheet !== spriteSheet)) { console && console.log("Error: A child's spriteSheet must be equal to its parent spriteSheet and only use one image. [" + child.toString() + "]"); return child; } this.spriteSheet = spriteSheet; } if (child.parent) { child.parent.removeChild(child); } child.parent = this; this.children.splice(index, 0, child); return child; }; /** * Returns a string representation of this object. * @method toString * @return {String} a string representation of the instance. **/ p.toString = function() { return "[SpriteContainer (name="+ this.name +")]"; }; createjs.SpriteContainer = createjs.promote(SpriteContainer, "Container"); }());
iwangx/createjs
src/easeljs/display/SpriteContainer.js
JavaScript
mit
7,122
/** * Babel plugin for removing specific properties that match a given regular expression. * */ "use strict"; exports.default = function() { return { visitor: { // ObjectProperty Visitor ObjectProperty: function ObjectProperty(path, state) { /** * Define a visitor for nodes of type `ObjectProperty`. * Nodes w/ property names that match a specified regex will be removed. * * :param path: the path of the visited node * :param state: options that are passed to the plugin * */ const regexp = new RegExp(state.opts.regexp); if (regexp.test(path.node.key.name) || regexp.test(path.node.key.value)) { // Oh sheet, found a match, remove dis beech path.remove(); } } } }; }; module.exports = exports["default"];
bdupharm/babel-plugin-remove-object-properties
lib/plugin.js
JavaScript
mit
998
// Simple JavaScript Templating // Heavily based on: John Resig - http://ejohn.org/blog/javascript-micro-templating/ var argName = 'data'; function getFuncBody(str) { return argName+"="+argName+"||{};var p=[];p.push('" + str .replace(/[\r\t\n]/g, " ") .split("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');return p.join('');"; } function mtmpl(str,data) { var fn = new Function(argName,getFuncBody(str)); return data ? fn(data) : fn; } function precompile(str) { return "function("+argName+"){"+getFuncBody(str)+"}"; } module.exports = { mtmpl:mtmpl, precompile:precompile };
theakman2/node-modules-mtmpl
lib/index.js
JavaScript
mit
756
'use strict'; var nodeSassImport = require('../'); var test = require('tape'); var sass = require('node-sass'); test('base:function:test', function (t) { t.ok(typeof nodeSassImport === 'function'); t.end(); }); test('base:importer:test', function (t) { sass.render({ file: 'test/fixtures/main.scss', importer: nodeSassImport }, function (err, result) { t.error(err, 'should render SASS without errors'); t.end(); }); }); test('base:importer:globs:test', function (t) { sass.render({ file: 'test/fixtures/glob.scss', importer: nodeSassImport }, function (err, result) { var css = result.css.toString(); t.error(err, 'should render SASS without errors'); t.ok(/div\.one/.test(css), 'renders one.scss'); t.ok(/div\.two/.test(css), 'renders two.scss'); t.end(); }); });
anarh/node-sass-import
test/index.js
JavaScript
mit
830
"use strict"; const assert = require("assert"); const Message = require("../lib/vehicle-message"); describe("vehicle-message", () => { it("get MQTT packet and return VehicleMessage data model", () => { const msg = Message.from({ topic: "vehicle/foo", payload: new Buffer(JSON.stringify({ timestamp: "2016-04-30T05:41:08.915Z", longitude: 37.481200, latitude: 126.948004 })) }); assert.strictEqual(msg.vehicleId, "foo"); assert.strictEqual(msg.timestamp, "2016-04-30T05:41:08.915Z"); assert.strictEqual(msg.longitude, 37.481200); assert.strictEqual(msg.latitude, 126.948004); }); it("validate MQTT packet to create VehicleMessage data model", () => { const bool = Message.validate({ topic: "vehicle/foo", payload: new Buffer(JSON.stringify({ timestamp: "invalid date", longitude: 37.481200, latitude: 126.948004 })) }); assert.strictEqual(bool, false); }); it("get MQTT packet and return null if it can't be compatible to VehicleMessage", () => { const msg = Message.from({ topic: "vehicle/foo", payload: new Buffer(JSON.stringify({ timestamp: "invalid date", longitude: 37.481200, latitude: 126.948004 })) }); assert.strictEqual(msg, null); }); it("JSON.stringify and parse", () => { const msg = Message.from({ topic: "vehicle/foo", payload: new Buffer(JSON.stringify({ timestamp: "2016-04-30T05:41:08.915Z", longitude: 37.481200, latitude: 126.948004 })) }); assert.deepEqual(JSON.parse(JSON.stringify(msg)), { vehicleId: "foo", timestamp: "2016-04-30T05:41:08.915Z", longitude: 37.481200, latitude: 126.948004 }); }); });
esmusssein/SNU-grad-proj
broker/test/vehicle-message.js
JavaScript
mit
1,804
'use strict'; // http://stackoverflow.com/a/365853 Object.defineProperty(exports, "__esModule", { value: true }); exports.toRad = toRad; exports.getShortestDistance = getShortestDistance; exports.getLonguestDistance = getLonguestDistance; exports.getLonguestDistanceFromCoordinates = getLonguestDistanceFromCoordinates; exports.getAverageETA = getAverageETA; function toRad(deg) { return deg * (Math.PI / 180); } function getShortestDistance(lat1, lon1, lat2, lon2) { var R = 6371000; // m var dLat = toRad(lat2 - lat1); var dLon = toRad(lon2 - lon1); var rLat1 = toRad(lat1); var rLat2 = toRad(lat2); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(rLat1) * Math.cos(rLat2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d; } function getLonguestDistance(lat1, lon1, lat2, lon2) { // Just the sum of two special cases of getShortestDistance var R = 6371000; // m var dLon = toRad(lon2 - lon1); var dLat = toRad(lat2 - lat1); var rLat1 = toRad(lat1); var rLat2 = toRad(lat1); var a = Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(rLat1) * Math.cos(rLat2); var distA = R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var b = Math.sin(dLat / 2) * Math.sin(dLat / 2); var distB = R * 2 * Math.atan2(Math.sqrt(b), Math.sqrt(1 - b)); return distA + distB; } function getLonguestDistanceFromCoordinates(from, to, waypoints) { var points = []; points.push(from); points.push.apply(points, waypoints); points.push(to); var distance = 0; points.forEach(function (point, i) { if (!i) return; distance += getLonguestDistance(points[i - 1][0], points[i - 1][1], point[0], point[1]); }); return distance; } function getAverageETA(distance, speed) { return Math.round(distance / speed); }
alexjab/node-simple-eta
lib/distances.js
JavaScript
mit
1,850
$(function() { var background = chrome.extension.getBackgroundPage(); var defaultOptions = background.defaultOptions; var options = {}; function createFrames() { var frames = options.frames.split('\n'); $('.js-frame').remove(); for (var i = 0; i < frames.length; i++) { var src = frames[i]; if (!src) { continue; } var $frame = $( '<div class="frame js-frame">' + '<div class="frame-iframe-wrapper js-iframe-wrapper">' + '<iframe frameborder="0" scrolling="no"></iframe>' + '</div>' + '<div class="frame-title-container">' + '<a class="frame-title js-title" ' + 'href="' + src + '" target="_blank">' + src + '</a>' + '</div>' + '</div>' ); $('.js-frames').append($frame); src += src.indexOf('?') !== -1 ? '&' : '?'; src += 'timestamp=' + (new Date()).getTime(); $frame.find('iframe').attr('src', src); } resizeFrames(); } function resizeFrames() { var resolutionX = options.resolutionX; var resolutionY = options.resolutionY; var gutterWidth = 10; var frameWidth = ( ($(document).width() - options.columns * gutterWidth - gutterWidth) / options.columns ); var scale = frameWidth / resolutionX; $('.js-frame').each(function() { var $frame = $(this); var $wrapper = $frame.find('.js-iframe-wrapper'); var $iframe = $wrapper.find('iframe'); $frame.width(frameWidth); $wrapper.height(frameWidth * (resolutionY / resolutionX)); $iframe.css({ transform: 'scale(' + scale + ')', }); }); } $(window).on('resize', resizeFrames); chrome.storage.sync.get('options', function(result) { options = result.options || defaultOptions; createFrames(); }); });
laurentguilbert/overseer
js/frames.js
JavaScript
mit
1,827
module.exports = { presets: [ [ '@babel/preset-env', { targets: { node: '12', }, }, ], '@babel/preset-react', ], };
dannegm/danielgarcia
.babelrc.js
JavaScript
mit
236
/* * Module dependencies */ var conf = module.exports = require('nconf'); /* Last fallback : environment variables */ conf.env().argv(); /* Dev fallback : config.json */ conf.file(__dirname + '/../config.json'); /* Default values */ conf.defaults({ title: 'Meishengo', debug: false, port: 8000, host: 'localhost', gameTTL: 24 * 3600, nickTTL: 60 });
dawicorti/meishengo
lib/conf.js
JavaScript
mit
372
module.exports = { mixins: [__dirname], fragmentsFile: '<rootDir>/fragmentTypes.json', graphqlMockServerPath: '/graphql', configSchema: { fragmentsFile: { type: 'string', absolutePath: true, }, graphqlSchemaFile: { type: 'string', absolutePath: true, }, graphqlMockSchemaFile: { type: 'string', }, graphqlMockServerPath: { type: 'string', }, graphqlMockContextExtenderFile: { type: 'string', }, }, };
xing/hops
packages/apollo-mock-server/preset.js
JavaScript
mit
493
import { CHOOSE_MEMORY, LOAD_PHOTO_ERROR, LOAD_PHOTO_SUCCESS, } from './constants'; export function chooseMemory({ id, index }) { return { type: CHOOSE_MEMORY, id, index, }; } export function photoLoadSuccess({ host, gallery, setCurrentMemory, album, id, photoLink, }) { return { type: LOAD_PHOTO_SUCCESS, id, photoLink, setCurrentMemory, host, gallery, album, }; } export function photoLoadError(error, filename) { return { type: LOAD_PHOTO_ERROR, filename, error, }; }
danactive/history
ui/app/containers/App/actions.js
JavaScript
mit
556
function saveUser({state, input}) { state.set(['user', 'user'], input.user); state.set(['session', 'jwt'], input.jwt); } export default saveUser;
testpackbin/testpackbin
app/modules/home/actions/saveUser.js
JavaScript
mit
151
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zm-2 5.79V18h-3.52L12 20.48 9.52 18H6v-3.52L3.52 12 6 9.52V6h3.52L12 3.52 14.48 6H18v3.52L20.48 12 18 14.48zM12 6.5c-3.03 0-5.5 2.47-5.5 5.5s2.47 5.5 5.5 5.5 5.5-2.47 5.5-5.5-2.47-5.5-5.5-5.5zm0 9c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z" /><circle cx="12" cy="12" r="2" /></React.Fragment> , 'Brightness7Outlined');
kybarg/material-ui
packages/material-ui-icons/src/Brightness7Outlined.js
JavaScript
mit
593