/** * @license Angulartics * (c) 2013 Luis Farzati http://angulartics.github.io/ * License: MIT */ (function(angular, analytics) { 'use strict'; var angulartics = window.angulartics || (window.angulartics = {}); angulartics.waitForVendorCount = 0; angulartics.waitForVendorApi = function (objectName, delay, containsField, registerFn, onTimeout) { if (!onTimeout) { angulartics.waitForVendorCount++; } if (!registerFn) { registerFn = containsField; containsField = undefined; } if (!Object.prototype.hasOwnProperty.call(window, objectName) || (containsField !== undefined && window[objectName][containsField] === undefined)) { setTimeout(function () { angulartics.waitForVendorApi(objectName, delay, containsField, registerFn, true); }, delay); } else { angulartics.waitForVendorCount--; registerFn(window[objectName]); } }; /** * @ngdoc overview * @name angulartics */ angular.module('angulartics', []) .provider('$analytics', $analytics) .run(['$rootScope', '$window', '$analytics', '$injector', $analyticsRun]) .directive('analyticsOn', ['$analytics', analyticsOn]) .config(['$provide', exceptionTrack]); function $analytics() { var vm = this; var settings = { pageTracking: { autoTrackFirstPage: true, autoTrackVirtualPages: true, trackRelativePath: false, trackRoutes: true, trackStates: true, autoBasePath: false, basePath: '', excludedRoutes: [], queryKeysWhitelisted: [], queryKeysBlacklisted: [] }, eventTracking: {}, bufferFlushDelay: 1000, // Support only one configuration for buffer flush delay to simplify buffering trackExceptions: false, optOut: false, developerMode: false // Prevent sending data in local/development environment }; // List of known handlers that plugins can register themselves for var knownHandlers = [ 'pageTrack', 'eventTrack', 'exceptionTrack', 'transactionTrack', 'setAlias', 'setUsername', 'setUserProperties', 'setUserPropertiesOnce', 'setSuperProperties', 'setSuperPropertiesOnce', 'incrementProperty', 'userTimings', 'clearCookies' ]; // Cache and handler properties will match values in 'knownHandlers' as the buffering functons are installed. var cache = {}; var handlers = {}; var handlerOptions = {}; // General buffering handler function bufferedHandler(handlerName){ return function(){ if(angulartics.waitForVendorCount){ if(!cache[handlerName]){ cache[handlerName] = []; } cache[handlerName].push(arguments); } }; } // As handlers are installed by plugins, they get pushed into a list and invoked in order. function updateHandlers(handlerName, fn, options){ if(!handlers[handlerName]){ handlers[handlerName] = []; } handlers[handlerName].push(fn); handlerOptions[fn] = options; return function(){ if(!this.settings.optOut) { var handlerArgs = Array.prototype.slice.apply(arguments); return this.$inject(['$q', angular.bind(this, function($q) { return $q.all(handlers[handlerName].map(function(handlerFn) { var options = handlerOptions[handlerFn] || {}; if (options.async) { var deferred = $q.defer(); var currentArgs = angular.copy(handlerArgs); currentArgs.unshift(deferred.resolve); handlerFn.apply(this, currentArgs); return deferred.promise; } else{ return $q.when(handlerFn.apply(this, handlerArgs)); } }, this)); })]); } }; } // The api (returned by this provider) gets populated with handlers below. var api = { settings: settings }; // Opt in and opt out functions api.setOptOut = function(optOut) { this.settings.optOut = optOut; triggerRegister(); }; api.getOptOut = function() { return this.settings.optOut; }; // Will run setTimeout if delay is > 0 // Runs immediately if no delay to make sure cache/buffer is flushed before anything else. // Plugins should take care to register handlers by order of precedence. function onTimeout(fn, delay){ if(delay){ setTimeout(fn, delay); } else { fn(); } } var provider = { $get: ['$injector', function($injector) { return apiWithInjector($injector); }], api: api, settings: settings, virtualPageviews: function (value) { this.settings.pageTracking.autoTrackVirtualPages = value; }, trackStates: function (value) { this.settings.pageTracking.trackStates = value; }, trackRoutes: function (value) { this.settings.pageTracking.trackRoutes = value; }, excludeRoutes: function(routes) { this.settings.pageTracking.excludedRoutes = routes; }, queryKeysWhitelist: function(keys) { this.settings.pageTracking.queryKeysWhitelisted = keys; }, queryKeysBlacklist: function(keys) { this.settings.pageTracking.queryKeysBlacklisted = keys; }, firstPageview: function (value) { this.settings.pageTracking.autoTrackFirstPage = value; }, withBase: function (value) { this.settings.pageTracking.basePath = (value) ? angular.element(document).find('base').attr('href') : ''; }, withAutoBase: function (value) { this.settings.pageTracking.autoBasePath = value; }, trackExceptions: function (value) { this.settings.trackExceptions = value; }, developerMode: function(value) { this.settings.developerMode = value; } }; // General function to register plugin handlers. Flushes buffers immediately upon registration according to the specified delay. function register(handlerName, fn, options){ // Do not add a handler if developerMode is true if (settings.developerMode) { return; } api[handlerName] = updateHandlers(handlerName, fn, options); var handlerSettings = settings[handlerName]; var handlerDelay = (handlerSettings) ? handlerSettings.bufferFlushDelay : null; var delay = (handlerDelay !== null) ? handlerDelay : settings.bufferFlushDelay; angular.forEach(cache[handlerName], function (args, index) { onTimeout(function () { fn.apply(this, args); }, index * delay); }); } function capitalize(input) { return input.replace(/^./, function (match) { return match.toUpperCase(); }); } //provide a method to inject services into handlers var apiWithInjector = function(injector) { return angular.extend(api, { '$inject': injector.invoke }); }; // Adds to the provider a 'register#{handlerName}' function that manages multiple plugins and buffer flushing. function installHandlerRegisterFunction(handlerName){ var registerName = 'register'+capitalize(handlerName); provider[registerName] = function(fn, options){ register(handlerName, fn, options); }; api[handlerName] = updateHandlers(handlerName, bufferedHandler(handlerName)); } function startRegistering(_provider, _knownHandlers, _installHandlerRegisterFunction) { angular.forEach(_knownHandlers, _installHandlerRegisterFunction); for (var key in _provider) { vm[key] = _provider[key]; } } // Allow $angulartics to trigger the register to update opt in/out var triggerRegister = function() { startRegistering(provider, knownHandlers, installHandlerRegisterFunction); }; // Initial register startRegistering(provider, knownHandlers, installHandlerRegisterFunction); } function $analyticsRun($rootScope, $window, $analytics, $injector) { function matchesExcludedRoute(url) { for (var i = 0; i < $analytics.settings.pageTracking.excludedRoutes.length; i++) { var excludedRoute = $analytics.settings.pageTracking.excludedRoutes[i]; if ((excludedRoute instanceof RegExp && excludedRoute.test(url)) || url.indexOf(excludedRoute) > -1) { return true; } } return false; } function arrayDifference(a1, a2) { var result = []; for (var i = 0; i < a1.length; i++) { if (a2.indexOf(a1[i]) === -1) { result.push(a1[i]); } } return result; } function filterQueryString(url, keysMatchArr, thisType){ if (/\?/.test(url) && keysMatchArr.length > 0) { var urlArr = url.split('?'); var urlBase = urlArr[0]; var pairs = urlArr[1].split('&'); var matchedPairs = []; for (var i = 0; i < keysMatchArr.length; i++) { var listedKey = keysMatchArr[i]; for (var j = 0; j < pairs.length; j++) { if ((listedKey instanceof RegExp && listedKey.test(pairs[j])) || pairs[j].indexOf(listedKey) > -1) matchedPairs.push(pairs[j]); } } var matchedPairsArr = (thisType == 'white' ? matchedPairs : arrayDifference(pairs,matchedPairs)); if(matchedPairsArr.length > 0){ return urlBase + '?' + matchedPairsArr.join('&'); }else{ return urlBase; } } else { return url; } } function whitelistQueryString(url){ return filterQueryString(url, $analytics.settings.pageTracking.queryKeysWhitelisted, 'white'); } function blacklistQueryString(url){ return filterQueryString(url, $analytics.settings.pageTracking.queryKeysBlacklisted, 'black'); } function pageTrack(url, $location) { if (!matchesExcludedRoute(url)) { url = whitelistQueryString(url); url = blacklistQueryString(url); $analytics.pageTrack(url, $location); } } if ($analytics.settings.pageTracking.autoTrackFirstPage) { $injector.invoke(['$location', function ($location) { /* Only track the 'first page' if there are no routes or states on the page */ var noRoutesOrStates = true; if ($injector.has('$route')) { var $route = $injector.get('$route'); if ($route) { for (var route in $route.routes) { noRoutesOrStates = false; break; } } else if ($route === null){ noRoutesOrStates = false; } } else if ($injector.has('$state')) { var $state = $injector.get('$state'); if ($state.get().length > 1) noRoutesOrStates = false; } if (noRoutesOrStates) { if ($analytics.settings.pageTracking.autoBasePath) { $analytics.settings.pageTracking.basePath = $window.location.pathname; } if ($analytics.settings.pageTracking.trackRelativePath) { var url = $analytics.settings.pageTracking.basePath + $location.url(); pageTrack(url, $location); } else { pageTrack($location.absUrl(), $location); } } }]); } if ($analytics.settings.pageTracking.autoTrackVirtualPages) { $injector.invoke(['$location', function ($location) { if ($analytics.settings.pageTracking.autoBasePath) { /* Add the full route to the base. */ $analytics.settings.pageTracking.basePath = $window.location.pathname + "#"; } var noRoutesOrStates = true; if ($analytics.settings.pageTracking.trackRoutes) { if ($injector.has('$route')) { var $route = $injector.get('$route'); if ($route) { for (var route in $route.routes) { noRoutesOrStates = false; break; } } else if ($route === null){ noRoutesOrStates = false; } $rootScope.$on('$routeChangeSuccess', function (event, current) { if (current && (current.$$route||current).redirectTo) return; var url = $analytics.settings.pageTracking.basePath + $location.url(); pageTrack(url, $location); }); } } if ($analytics.settings.pageTracking.trackStates) { if ($injector.has('$state') && !$injector.has('$transitions')) { noRoutesOrStates = false; $rootScope.$on('$stateChangeSuccess', function (event, current) { var url = $analytics.settings.pageTracking.basePath + $location.url(); pageTrack(url, $location); }); } if ($injector.has('$state') && $injector.has('$transitions')) { noRoutesOrStates = false; $injector.invoke(['$transitions', function($transitions) { $transitions.onSuccess({}, function($transition$) { var transitionOptions = $transition$.options(); // only track for transitions that would have triggered $stateChangeSuccess if (transitionOptions.notify) { var url = $analytics.settings.pageTracking.basePath + $location.url(); pageTrack(url, $location); } }); }]); } } if (noRoutesOrStates) { $rootScope.$on('$locationChangeSuccess', function (event, current) { if (current && (current.$$route || current).redirectTo) return; if ($analytics.settings.pageTracking.trackRelativePath) { var url = $analytics.settings.pageTracking.basePath + $location.url(); pageTrack(url, $location); } else { pageTrack($location.absUrl(), $location); } }); } }]); } if ($analytics.settings.developerMode) { angular.forEach($analytics, function(attr, name) { if (typeof attr === 'function') { $analytics[name] = function(){}; } }); } } function analyticsOn($analytics) { return { restrict: 'A', link: function ($scope, $element, $attrs) { var eventType = $attrs.analyticsOn || 'click'; var trackingData = {}; angular.forEach($attrs.$attr, function(attr, name) { if (isProperty(name)) { trackingData[propertyName(name)] = $attrs[name]; $attrs.$observe(name, function(value){ trackingData[propertyName(name)] = value; }); } }); angular.element($element[0]).on(eventType, function ($event) { var eventName = $attrs.analyticsEvent || inferEventName($element[0]); trackingData.eventType = $event.type; if($attrs.analyticsIf){ if(! $scope.$eval($attrs.analyticsIf)){ return; // Cancel this event if we don't pass the analytics-if condition } } // Allow components to pass through an expression that gets merged on to the event properties // eg. analytics-properites='myComponentScope.someConfigExpression.$analyticsProperties' if($attrs.analyticsProperties){ angular.extend(trackingData, $scope.$eval($attrs.analyticsProperties)); } $analytics.eventTrack(eventName, trackingData); }); } }; } function exceptionTrack($provide) { $provide.decorator('$exceptionHandler', ['$delegate', '$injector', function ($delegate, $injector) { return function (error, cause) { var result = $delegate(error, cause); var $analytics = $injector.get('$analytics'); if ($analytics.settings.trackExceptions) { $analytics.exceptionTrack(error, cause); } return result; }; }]); } function isCommand(element) { return ['a:','button:','button:button','button:submit','input:button','input:submit'].indexOf( element.tagName.toLowerCase()+':'+(element.type||'')) >= 0; } function inferEventType(element) { if (isCommand(element)) return 'click'; return 'click'; } function inferEventName(element) { if (isCommand(element)) return element.innerText || element.value; return element.id || element.name || element.tagName; } function isProperty(name) { return name.substr(0, 9) === 'analytics' && ['On', 'Event', 'If', 'Properties', 'EventType'].indexOf(name.substr(9)) === -1; } function propertyName(name) { var s = name.slice(9); // slice off the 'analytics' prefix if (typeof s !== 'undefined' && s!==null && s.length > 0) { return s.substring(0, 1).toLowerCase() + s.substring(1); } else { return s; } } })(angular); (function() { var showErrorsModule; showErrorsModule = angular.module('ui.bootstrap.showErrors', []); showErrorsModule.directive('showErrors', [ '$timeout', 'showErrorsConfig', '$interpolate', function($timeout, showErrorsConfig, $interpolate) { var getShowSuccess, getTrigger, linkFn; getTrigger = function(options) { var trigger; trigger = showErrorsConfig.trigger; if (options && (options.trigger != null)) { trigger = options.trigger; } return trigger; }; getShowSuccess = function(options) { var showSuccess; showSuccess = showErrorsConfig.showSuccess; if (options && (options.showSuccess != null)) { showSuccess = options.showSuccess; } return showSuccess; }; linkFn = function(scope, el, attrs, formCtrl) { var blurred, inputEl, inputName, inputNgEl, options, showSuccess, toggleClasses, trigger; blurred = false; options = scope.$eval(attrs.showErrors); showSuccess = getShowSuccess(options); trigger = getTrigger(options); inputEl = el[0].querySelector('.form-control[name]'); inputNgEl = angular.element(inputEl); inputName = $interpolate(inputNgEl.attr('name') || '')(scope); if (!inputName) { throw "show-errors element has no child input elements with a 'name' attribute and a 'form-control' class"; } inputNgEl.bind(trigger, function() { blurred = true; return toggleClasses(formCtrl[inputName].$invalid); }); scope.$watch(function() { return formCtrl[inputName] && formCtrl[inputName].$invalid; }, function(invalid) { if (!blurred) { return; } return toggleClasses(invalid); }); scope.$on('show-errors-check-validity', function() { return toggleClasses(formCtrl[inputName].$invalid); }); scope.$on('show-errors-reset', function() { return $timeout(function() { el.removeClass('has-error'); el.removeClass('has-success'); return blurred = false; }, 0, false); }); return toggleClasses = function(invalid) { el.toggleClass('has-error', invalid); if (showSuccess) { return el.toggleClass('has-success', !invalid); } }; }; return { restrict: 'A', require: '^form', compile: function(elem, attrs) { if (attrs['showErrors'].indexOf('skipFormGroupCheck') === -1) { if (!(elem.hasClass('form-group') || elem.hasClass('input-group'))) { throw "show-errors element does not have the 'form-group' or 'input-group' class"; } } return linkFn; } }; } ]); showErrorsModule.provider('showErrorsConfig', function() { var _showSuccess, _trigger; _showSuccess = false; _trigger = 'blur'; this.showSuccess = function(showSuccess) { return _showSuccess = showSuccess; }; this.trigger = function(trigger) { return _trigger = trigger; }; this.$get = function() { return { showSuccess: _showSuccess, trigger: _trigger }; }; }); }).call(this); /** * @license AngularJS v1.6.7 * (c) 2010-2017 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular) {'use strict'; /** * @ngdoc module * @name ngCookies * @description * * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies. * * See {@link ngCookies.$cookies `$cookies`} for usage. */ angular.module('ngCookies', ['ng']). info({ angularVersion: '1.6.7' }). /** * @ngdoc provider * @name $cookiesProvider * @description * Use `$cookiesProvider` to change the default behavior of the {@link ngCookies.$cookies $cookies} service. * */ provider('$cookies', [/** @this */function $CookiesProvider() { /** * @ngdoc property * @name $cookiesProvider#defaults * @description * * Object containing default options to pass when setting cookies. * * The object may have following properties: * * - **path** - `{string}` - The cookie will be available only for this path and its * sub-paths. By default, this is the URL that appears in your `` tag. * - **domain** - `{string}` - The cookie will be available only for this domain and * its sub-domains. For security reasons the user agent will not accept the cookie * if the current domain is not a sub-domain of this domain or equal to it. * - **expires** - `{string|Date}` - String of the form "Wdy, DD Mon YYYY HH:MM:SS GMT" * or a Date object indicating the exact date/time this cookie will expire. * - **secure** - `{boolean}` - If `true`, then the cookie will only be available through a * secured connection. * * Note: By default, the address that appears in your `` tag will be used as the path. * This is important so that cookies will be visible for all routes when html5mode is enabled. * * @example * * ```js * angular.module('cookiesProviderExample', ['ngCookies']) * .config(['$cookiesProvider', function($cookiesProvider) { * // Setting default options * $cookiesProvider.defaults.domain = 'foo.com'; * $cookiesProvider.defaults.secure = true; * }]); * ``` **/ var defaults = this.defaults = {}; function calcOptions(options) { return options ? angular.extend({}, defaults, options) : defaults; } /** * @ngdoc service * @name $cookies * * @description * Provides read/write access to browser's cookies. * *
* Up until Angular 1.3, `$cookies` exposed properties that represented the * current browser cookie values. In version 1.4, this behavior has changed, and * `$cookies` now provides a standard api of getters, setters etc. *
* * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * angular.module('cookiesExample', ['ngCookies']) * .controller('ExampleController', ['$cookies', function($cookies) { * // Retrieving a cookie * var favoriteCookie = $cookies.get('myFavorite'); * // Setting a cookie * $cookies.put('myFavorite', 'oatmeal'); * }]); * ``` */ this.$get = ['$$cookieReader', '$$cookieWriter', function($$cookieReader, $$cookieWriter) { return { /** * @ngdoc method * @name $cookies#get * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {string} Raw cookie value. */ get: function(key) { return $$cookieReader()[key]; }, /** * @ngdoc method * @name $cookies#getObject * * @description * Returns the deserialized value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ getObject: function(key) { var value = this.get(key); return value ? angular.fromJson(value) : value; }, /** * @ngdoc method * @name $cookies#getAll * * @description * Returns a key value object with all the cookies * * @returns {Object} All cookies */ getAll: function() { return $$cookieReader(); }, /** * @ngdoc method * @name $cookies#put * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {string} value Raw value to be stored. * @param {Object=} options Options object. * See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} */ put: function(key, value, options) { $$cookieWriter(key, value, calcOptions(options)); }, /** * @ngdoc method * @name $cookies#putObject * * @description * Serializes and sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. * @param {Object=} options Options object. * See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} */ putObject: function(key, value, options) { this.put(key, angular.toJson(value), options); }, /** * @ngdoc method * @name $cookies#remove * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. * @param {Object=} options Options object. * See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} */ remove: function(key, options) { $$cookieWriter(key, undefined, calcOptions(options)); } }; }]; }]); angular.module('ngCookies'). /** * @ngdoc service * @name $cookieStore * @deprecated * sinceVersion="v1.4.0" * Please use the {@link ngCookies.$cookies `$cookies`} service instead. * * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * angular.module('cookieStoreExample', ['ngCookies']) * .controller('ExampleController', ['$cookieStore', function($cookieStore) { * // Put cookie * $cookieStore.put('myFavorite','oatmeal'); * // Get cookie * var favoriteCookie = $cookieStore.get('myFavorite'); * // Removing a cookie * $cookieStore.remove('myFavorite'); * }]); * ``` */ factory('$cookieStore', ['$cookies', function($cookies) { return { /** * @ngdoc method * @name $cookieStore#get * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value, undefined if the cookie does not exist. */ get: function(key) { return $cookies.getObject(key); }, /** * @ngdoc method * @name $cookieStore#put * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $cookies.putObject(key, value); }, /** * @ngdoc method * @name $cookieStore#remove * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { $cookies.remove(key); } }; }]); /** * @name $$cookieWriter * @requires $document * * @description * This is a private service for writing cookies * * @param {string} name Cookie name * @param {string=} value Cookie value (if undefined, cookie will be deleted) * @param {Object=} options Object with options that need to be stored for the cookie. */ function $$CookieWriter($document, $log, $browser) { var cookiePath = $browser.baseHref(); var rawDocument = $document[0]; function buildCookieString(name, value, options) { var path, expires; options = options || {}; expires = options.expires; path = angular.isDefined(options.path) ? options.path : cookiePath; if (angular.isUndefined(value)) { expires = 'Thu, 01 Jan 1970 00:00:00 GMT'; value = ''; } if (angular.isString(expires)) { expires = new Date(expires); } var str = encodeURIComponent(name) + '=' + encodeURIComponent(value); str += path ? ';path=' + path : ''; str += options.domain ? ';domain=' + options.domain : ''; str += expires ? ';expires=' + expires.toUTCString() : ''; str += options.secure ? ';secure' : ''; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: // - 300 cookies // - 20 cookies per unique domain // - 4096 bytes per cookie var cookieLength = str.length + 1; if (cookieLength > 4096) { $log.warn('Cookie \'' + name + '\' possibly not set or overflowed because it was too large (' + cookieLength + ' > 4096 bytes)!'); } return str; } return function(name, value, options) { rawDocument.cookie = buildCookieString(name, value, options); }; } $$CookieWriter.$inject = ['$document', '$log', '$browser']; angular.module('ngCookies').provider('$$cookieWriter', /** @this */ function $$CookieWriterProvider() { this.$get = $$CookieWriter; }); })(window, window.angular); (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.angularCreditCards = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= new Date(year, month) } function parseMonth (month) { return parseIntStrict(month) } function formatExpYear (year, strip) { year = year.toString() return strip ? year.substr(2, 4) : year } function isExpYearValid (year) { if (typeof year !== 'number') return false year = parseIntStrict(year) return year > 0 } function isExpYearPast (year) { return new Date().getFullYear() > year } },{"is-valid-month":21,"parse-int":24,"parse-year":25}],13:[function(_dereq_,module,exports){ 'use strict' module.exports = { card: _dereq_('./card'), cvc: _dereq_('./cvc'), expiration: _dereq_('./expiration') } },{"./card":10,"./cvc":11,"./expiration":12}],14:[function(_dereq_,module,exports){ 'use strict' var ccTypes = _dereq_('creditcards-types') var camel = _dereq_('to-camel-case') var extend = _dereq_('xtend') module.exports = extend(ccTypes, { get: function getTypeByName (name) { return ccTypes.types[camel(name)] } }) },{"creditcards-types":7,"to-camel-case":26,"xtend":29}],15:[function(_dereq_,module,exports){ 'use strict' var zeroFill = _dereq_('zero-fill') var parseIntStrict = _dereq_('parse-int') var pad = zeroFill(2) module.exports = function expandYear (year, now) { now = now || new Date() var base = now.getFullYear().toString().substr(0, 2) year = parseIntStrict(year) return parseIntStrict(base + pad(year)) } },{"parse-int":24,"zero-fill":31}],16:[function(_dereq_,module,exports){ 'use strict' module.exports = (function (array) { return function luhn (number) { if (typeof number !== 'string') throw new TypeError('Expected string input') if (!number) return false var length = number.length var bit = 1 var sum = 0 var value while (length) { value = parseInt(number.charAt(--length), 10) sum += (bit ^= 1) ? array[value] : value } return !!sum && sum % 10 === 0 } }([0, 2, 4, 6, 8, 1, 3, 5, 7, 9])) },{}],17:[function(_dereq_,module,exports){ 'use strict'; /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var slice = Array.prototype.slice; var toStr = Object.prototype.toString; var funcType = '[object Function]'; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push('$' + i); } bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; },{}],18:[function(_dereq_,module,exports){ 'use strict'; var implementation = _dereq_('./implementation'); module.exports = Function.prototype.bind || implementation; },{"./implementation":17}],19:[function(_dereq_,module,exports){ 'use strict'; var numberIsNan = _dereq_('number-is-nan'); module.exports = Number.isFinite || function (val) { return !(typeof val !== 'number' || numberIsNan(val) || val === Infinity || val === -Infinity); }; },{"number-is-nan":23}],20:[function(_dereq_,module,exports){ // https://github.com/paulmillr/es6-shim // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isinteger var isFinite = _dereq_("is-finite"); module.exports = Number.isInteger || function(val) { return typeof val === "number" && isFinite(val) && Math.floor(val) === val; }; },{"is-finite":19}],21:[function(_dereq_,module,exports){ 'use strict' var isInteger = _dereq_('is-integer') module.exports = function isValidMonth (month) { if (typeof month !== 'number' || !isInteger(month)) return false return month >= 1 && month <= 12 } },{"is-integer":20}],22:[function(_dereq_,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; },{}],23:[function(_dereq_,module,exports){ 'use strict'; module.exports = Number.isNaN || function (x) { return x !== x; }; },{}],24:[function(_dereq_,module,exports){ 'use strict' var isInteger = _dereq_('is-integer') module.exports = function parseIntStrict (integer) { if (typeof integer === 'number') { return isInteger(integer) ? integer : undefined } if (typeof integer === 'string') { return /^-?\d+$/.test(integer) ? parseInt(integer, 10) : undefined } } },{"is-integer":20}],25:[function(_dereq_,module,exports){ 'use strict' var parseIntStrict = _dereq_('parse-int') var expandYear = _dereq_('expand-year') module.exports = function parseYear (year, expand, now) { year = parseIntStrict(year) if (year == null) return if (!expand) return year return expandYear(year, now) } },{"expand-year":15,"parse-int":24}],26:[function(_dereq_,module,exports){ var space = _dereq_('to-space-case') /** * Export. */ module.exports = toCamelCase /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toCamelCase(string) { return space(string).replace(/\s(\w)/g, function (matches, letter) { return letter.toUpperCase() }) } },{"to-space-case":28}],27:[function(_dereq_,module,exports){ /** * Export. */ module.exports = toNoCase /** * Test whether a string is camel-case. */ var hasSpace = /\s/ var hasSeparator = /(_|-|\.|:)/ var hasCamel = /([a-z][A-Z]|[A-Z][a-z])/ /** * Remove any starting case from a `string`, like camel or snake, but keep * spaces and punctuation that may be important otherwise. * * @param {String} string * @return {String} */ function toNoCase(string) { if (hasSpace.test(string)) return string.toLowerCase() if (hasSeparator.test(string)) return (unseparate(string) || string).toLowerCase() if (hasCamel.test(string)) return uncamelize(string).toLowerCase() return string.toLowerCase() } /** * Separator splitter. */ var separatorSplitter = /[\W_]+(.|$)/g /** * Un-separate a `string`. * * @param {String} string * @return {String} */ function unseparate(string) { return string.replace(separatorSplitter, function (m, next) { return next ? ' ' + next : '' }) } /** * Camelcase splitter. */ var camelSplitter = /(.)([A-Z]+)/g /** * Un-camelcase a `string`. * * @param {String} string * @return {String} */ function uncamelize(string) { return string.replace(camelSplitter, function (m, previous, uppers) { return previous + ' ' + uppers.toLowerCase().split('').join(' ') }) } },{}],28:[function(_dereq_,module,exports){ var clean = _dereq_('to-no-case') /** * Export. */ module.exports = toSpaceCase /** * Convert a `string` to space case. * * @param {String} string * @return {String} */ function toSpaceCase(string) { return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) { return match ? ' ' + match : '' }).trim() } },{"to-no-case":27}],29:[function(_dereq_,module,exports){ module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (hasOwnProperty.call(source, key)) { target[key] = source[key] } } } return target } },{}],30:[function(_dereq_,module,exports){ module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; function extend(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (hasOwnProperty.call(source, key)) { target[key] = source[key] } } } return target } },{}],31:[function(_dereq_,module,exports){ /** * Given a number, return a zero-filled string. * From http://stackoverflow.com/questions/1267283/ * @param {number} width * @param {number} number * @return {string} */ module.exports = function zeroFill (width, number, pad) { if (number === undefined) { return function (number, pad) { return zeroFill(width, number, pad) } } if (pad === undefined) pad = '0' width -= number.toString().length if (width > 0) return new Array(width + (/\./.test(number) ? 2 : 1)).join(pad) + number return number + '' } },{}]},{},[3])(3) }); (function() { // Create all modules and define dependencies to make sure they exist // and are loaded in the correct order to satisfy dependency injection // before all nested files are concatenated by Grunt // Modules angular.module('angular-jwt', [ 'angular-jwt.options', 'angular-jwt.interceptor', 'angular-jwt.jwt', 'angular-jwt.authManager' ]); angular.module('angular-jwt.authManager', []) .provider('authManager', function () { this.$get = ["$rootScope", "$injector", "$location", "jwtHelper", "jwtInterceptor", "jwtOptions", function ($rootScope, $injector, $location, jwtHelper, jwtInterceptor, jwtOptions) { var config = jwtOptions.getConfig(); function invokeToken(tokenGetter) { var token = null; if (Array.isArray(tokenGetter)) { token = $injector.invoke(tokenGetter, this, {options: null}); } else { token = tokenGetter(); } return token; } function invokeRedirector(redirector) { if (Array.isArray(redirector) || angular.isFunction(redirector)) { return $injector.invoke(redirector, config, {}); } else { throw new Error('unauthenticatedRedirector must be a function'); } } function isAuthenticated() { var token = invokeToken(config.tokenGetter); if (token) { return !jwtHelper.isTokenExpired(token); } } $rootScope.isAuthenticated = false; function authenticate() { $rootScope.isAuthenticated = true; } function unauthenticate() { $rootScope.isAuthenticated = false; } function checkAuthOnRefresh() { $rootScope.$on('$locationChangeStart', function () { var token = invokeToken(config.tokenGetter); if (token) { if (!jwtHelper.isTokenExpired(token)) { authenticate(); } else { $rootScope.$broadcast('tokenHasExpired', token); } } }); } function redirectWhenUnauthenticated() { $rootScope.$on('unauthenticated', function () { invokeRedirector(config.unauthenticatedRedirector); unauthenticate(); }); } function verifyRoute(event, next) { if (!next) { return false; } var routeData = (next.$$route) ? next.$$route : next.data; if (routeData && routeData.requiresLogin === true) { var token = invokeToken(config.tokenGetter); if (!token || jwtHelper.isTokenExpired(token)) { event.preventDefault(); invokeRedirector(config.unauthenticatedRedirector); } } } var eventName = ($injector.has('$state')) ? '$stateChangeStart' : '$routeChangeStart'; $rootScope.$on(eventName, verifyRoute); return { authenticate: authenticate, unauthenticate: unauthenticate, getToken: function(){ return invokeToken(config.tokenGetter); }, redirect: function() { return invokeRedirector(config.unauthenticatedRedirector); }, checkAuthOnRefresh: checkAuthOnRefresh, redirectWhenUnauthenticated: redirectWhenUnauthenticated, isAuthenticated: isAuthenticated } }] }); angular.module('angular-jwt.interceptor', []) .provider('jwtInterceptor', function() { this.urlParam; this.authHeader; this.authPrefix; this.whiteListedDomains; this.tokenGetter; var config = this; this.$get = ["$q", "$injector", "$rootScope", "urlUtils", "jwtOptions", function($q, $injector, $rootScope, urlUtils, jwtOptions) { var options = angular.extend({}, jwtOptions.getConfig(), config); function isSafe (url) { if (!urlUtils.isSameOrigin(url) && !options.whiteListedDomains.length) { throw new Error('As of v0.1.0, requests to domains other than the application\'s origin must be white listed. Use jwtOptionsProvider.config({ whiteListedDomains: [] }); to whitelist.') } var hostname = urlUtils.urlResolve(url).hostname.toLowerCase(); for (var i = 0; i < options.whiteListedDomains.length; i++) { var domain = options.whiteListedDomains[i]; var regexp = domain instanceof RegExp ? domain : new RegExp(domain, 'i'); if (hostname.match(regexp)) { return true; } } if (urlUtils.isSameOrigin(url)) { return true; } return false; } return { request: function (request) { if (request.skipAuthorization || !isSafe(request.url)) { return request; } if (options.urlParam) { request.params = request.params || {}; // Already has the token in the url itself if (request.params[options.urlParam]) { return request; } } else { request.headers = request.headers || {}; // Already has an Authorization header if (request.headers[options.authHeader]) { return request; } } var tokenPromise = $q.when($injector.invoke(options.tokenGetter, this, { options: request })); return tokenPromise.then(function(token) { if (token) { if (options.urlParam) { request.params[options.urlParam] = token; } else { request.headers[options.authHeader] = options.authPrefix + token; } } return request; }); }, responseError: function (response) { // handle the case where the user is not authenticated if (response.status === 401) { $rootScope.$broadcast('unauthenticated', response); } return $q.reject(response); } }; }] }); angular.module('angular-jwt.jwt', []) .service('jwtHelper', ["$window", function($window) { this.urlBase64Decode = function(str) { var output = str.replace(/-/g, '+').replace(/_/g, '/'); switch (output.length % 4) { case 0: { break; } case 2: { output += '=='; break; } case 3: { output += '='; break; } default: { throw 'Illegal base64url string!'; } } return $window.decodeURIComponent(escape($window.atob(output))); //polyfill https://github.com/davidchambers/Base64.js }; this.decodeToken = function(token) { var parts = token.split('.'); if (parts.length !== 3) { throw new Error('JWT must have 3 parts'); } var decoded = this.urlBase64Decode(parts[1]); if (!decoded) { throw new Error('Cannot decode the token'); } return angular.fromJson(decoded); }; this.getTokenExpirationDate = function(token) { var decoded = this.decodeToken(token); if(typeof decoded.exp === "undefined") { return null; } var d = new Date(0); // The 0 here is the key, which sets the date to the epoch d.setUTCSeconds(decoded.exp); return d; }; this.isTokenExpired = function(token, offsetSeconds) { var d = this.getTokenExpirationDate(token); offsetSeconds = offsetSeconds || 0; if (d === null) { return false; } // Token expired? return !(d.valueOf() > (new Date().valueOf() + (offsetSeconds * 1000))); }; }]); angular.module('angular-jwt.options', []) .provider('jwtOptions', function() { var globalConfig = {}; this.config = function(value) { globalConfig = value; }; this.$get = function() { var options = { urlParam: null, authHeader: 'Authorization', authPrefix: 'Bearer ', whiteListedDomains: [], tokenGetter: function() { return null; }, loginPath: '/', unauthenticatedRedirectPath: '/', unauthenticatedRedirector: ['$location', function($location) { $location.path(this.unauthenticatedRedirectPath); }] }; function JwtOptions() { var config = this.config = angular.extend({}, options, globalConfig); } JwtOptions.prototype.getConfig = function() { return this.config; }; return new JwtOptions(); } }); /** * The content from this file was directly lifted from Angular. It is * unfortunately not a public API, so the best we can do is copy it. * * Angular References: * https://github.com/angular/angular.js/issues/3299 * https://github.com/angular/angular.js/blob/d077966ff1ac18262f4615ff1a533db24d4432a7/src/ng/urlUtils.js */ angular.module('angular-jwt.interceptor') .service('urlUtils', function () { // NOTE: The usage of window and document instead of $window and $document here is // deliberate. This service depends on the specific behavior of anchor nodes created by the // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and // cause us to break tests. In addition, when the browser resolves a URL for XHR, it // doesn't know about mocked locations and resolves URLs to the real document - which is // exactly the behavior needed here. There is little value is mocking these out for this // service. var urlParsingNode = document.createElement("a"); var originUrl = urlResolve(window.location.href); /** * * Implementation Notes for non-IE browsers * ---------------------------------------- * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, * results both in the normalizing and parsing of the URL. Normalizing means that a relative * URL will be resolved into an absolute URL in the context of the application document. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related * properties are all populated to reflect the normalized URL. This approach has wide * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html * * Implementation Notes for IE * --------------------------- * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other * browsers. However, the parsed components will not be set if the URL assigned did not specify * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We * work around that by performing the parsing in a 2nd step by taking a previously normalized * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the * properties such as protocol, hostname, port, etc. * * References: * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html * http://url.spec.whatwg.org/#urlutils * https://github.com/angular/angular.js/pull/2902 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ * * @kind function * @param {string} url The URL to be parsed. * @description Normalizes and parses a URL. * @returns {object} Returns the normalized URL as a dictionary. * * | member name | Description | * |---------------|----------------| * | href | A normalized version of the provided URL if it was not an absolute URL | * | protocol | The protocol including the trailing colon | * | host | The host and port (if the port is non-default) of the normalizedUrl | * | search | The search params, minus the question mark | * | hash | The hash string, minus the hash symbol * | hostname | The hostname * | port | The port, without ":" * | pathname | The pathname, beginning with "/" * */ function urlResolve(url) { var href = url; // Normalize before parse. Refer Implementation Notes on why this is // done in two steps on IE. urlParsingNode.setAttribute("href", href); href = urlParsingNode.href; urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } /** * Parse a request URL and determine whether this is a same-origin request as the application document. * * @param {string|object} requestUrl The url of the request as a string that will be resolved * or a parsed URL object. * @returns {boolean} Whether the request is for the same origin as the application document. */ function urlIsSameOrigin(requestUrl) { var parsed = (angular.isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; return (parsed.protocol === originUrl.protocol && parsed.host === originUrl.host); } return { urlResolve: urlResolve, isSameOrigin: urlIsSameOrigin }; }); }()); /** * @license AngularJS v1.6.7 * (c) 2010-2017 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular) {'use strict'; var forEach; var isArray; var isString; var jqLite; /** * @ngdoc module * @name ngMessages * @description * * The `ngMessages` module provides enhanced support for displaying messages within templates * (typically within forms or when rendering message objects that return key/value data). * Instead of relying on JavaScript code and/or complex ng-if statements within your form template to * show and hide error messages specific to the state of an input field, the `ngMessages` and * `ngMessage` directives are designed to handle the complexity, inheritance and priority * sequencing based on the order of how the messages are defined in the template. * * Currently, the ngMessages module only contains the code for the `ngMessages`, `ngMessagesInclude` * `ngMessage` and `ngMessageExp` directives. * * ## Usage * The `ngMessages` directive allows keys in a key/value collection to be associated with a child element * (or 'message') that will show or hide based on the truthiness of that key's value in the collection. A common use * case for `ngMessages` is to display error messages for inputs using the `$error` object exposed by the * {@link ngModel ngModel} directive. * * The child elements of the `ngMessages` directive are matched to the collection keys by a `ngMessage` or * `ngMessageExp` directive. The value of these attributes must match a key in the collection that is provided by * the `ngMessages` directive. * * Consider the following example, which illustrates a typical use case of `ngMessages`. Within the form `myForm` we * have a text input named `myField` which is bound to the scope variable `field` using the {@link ngModel ngModel} * directive. * * The `myField` field is a required input of type `email` with a maximum length of 15 characters. * * ```html *
* *
*
Please enter a value for this field.
*
This field must be a valid email address.
*
This field can be at most 15 characters long.
*
*
* ``` * * In order to show error messages corresponding to `myField` we first create an element with an `ngMessages` attribute * set to the `$error` object owned by the `myField` input in our `myForm` form. * * Within this element we then create separate elements for each of the possible errors that `myField` could have. * The `ngMessage` attribute is used to declare which element(s) will appear for which error - for example, * setting `ng-message="required"` specifies that this particular element should be displayed when there * is no value present for the required field `myField` (because the key `required` will be `true` in the object * `myForm.myField.$error`). * * ### Message order * * By default, `ngMessages` will only display one message for a particular key/value collection at any time. If more * than one message (or error) key is currently true, then which message is shown is determined by the order of messages * in the HTML template code (messages declared first are prioritised). This mechanism means the developer does not have * to prioritize messages using custom JavaScript code. * * Given the following error object for our example (which informs us that the field `myField` currently has both the * `required` and `email` errors): * * ```javascript * * myField.$error = { required : true, email: true, maxlength: false }; * ``` * The `required` message will be displayed to the user since it appears before the `email` message in the DOM. * Once the user types a single character, the `required` message will disappear (since the field now has a value) * but the `email` message will be visible because it is still applicable. * * ### Displaying multiple messages at the same time * * While `ngMessages` will by default only display one error element at a time, the `ng-messages-multiple` attribute can * be applied to the `ngMessages` container element to cause it to display all applicable error messages at once: * * ```html * *
...
* * * ... * ``` * * ## Reusing and Overriding Messages * In addition to prioritization, ngMessages also allows for including messages from a remote or an inline * template. This allows for generic collection of messages to be reused across multiple parts of an * application. * * ```html * * *
*
*
* ``` * * However, including generic messages may not be useful enough to match all input fields, therefore, * `ngMessages` provides the ability to override messages defined in the remote template by redefining * them within the directive container. * * ```html * * * *
* * *
* *
You did not enter your email address
* * *
Your email address is invalid
* * *
*
*
* ``` * * In the example HTML code above the message that is set on required will override the corresponding * required message defined within the remote template. Therefore, with particular input fields (such * email addresses, date fields, autocomplete inputs, etc...), specialized error messages can be applied * while more generic messages can be used to handle other, more general input errors. * * ## Dynamic Messaging * ngMessages also supports using expressions to dynamically change key values. Using arrays and * repeaters to list messages is also supported. This means that the code below will be able to * fully adapt itself and display the appropriate message when any of the expression data changes: * * ```html *
* *
*
You did not enter your email address
*
* *
{{ errorMessage.text }}
*
*
*
* ``` * * The `errorMessage.type` expression can be a string value or it can be an array so * that multiple errors can be associated with a single error message: * * ```html * *
*
You did not enter your email address
*
* Your email must be between 5 and 100 characters long *
*
* ``` * * Feel free to use other structural directives such as ng-if and ng-switch to further control * what messages are active and when. Be careful, if you place ng-message on the same element * as these structural directives, Angular may not be able to determine if a message is active * or not. Therefore it is best to place the ng-message on a child element of the structural * directive. * * ```html *
*
*
Please enter something
*
*
* ``` * * ## Animations * If the `ngAnimate` module is active within the application then the `ngMessages`, `ngMessage` and * `ngMessageExp` directives will trigger animations whenever any messages are added and removed from * the DOM by the `ngMessages` directive. * * Whenever the `ngMessages` directive contains one or more visible messages then the `.ng-active` CSS * class will be added to the element. The `.ng-inactive` CSS class will be applied when there are no * messages present. Therefore, CSS transitions and keyframes as well as JavaScript animations can * hook into the animations whenever these classes are added/removed. * * Let's say that our HTML code for our messages container looks like so: * * ```html * * ``` * * Then the CSS animation code for the message container looks like so: * * ```css * .my-messages { * transition:1s linear all; * } * .my-messages.ng-active { * // messages are visible * } * .my-messages.ng-inactive { * // messages are hidden * } * ``` * * Whenever an inner message is attached (becomes visible) or removed (becomes hidden) then the enter * and leave animation is triggered for each particular element bound to the `ngMessage` directive. * * Therefore, the CSS code for the inner messages looks like so: * * ```css * .some-message { * transition:1s linear all; * } * * .some-message.ng-enter {} * .some-message.ng-enter.ng-enter-active {} * * .some-message.ng-leave {} * .some-message.ng-leave.ng-leave-active {} * ``` * * {@link ngAnimate Click here} to learn how to use JavaScript animations or to learn more about ngAnimate. */ angular.module('ngMessages', [], function initAngularHelpers() { // Access helpers from angular core. // Do it inside a `config` block to ensure `window.angular` is available. forEach = angular.forEach; isArray = angular.isArray; isString = angular.isString; jqLite = angular.element; }) .info({ angularVersion: '1.6.7' }) /** * @ngdoc directive * @module ngMessages * @name ngMessages * @restrict AE * * @description * `ngMessages` is a directive that is designed to show and hide messages based on the state * of a key/value object that it listens on. The directive itself complements error message * reporting with the `ngModel` $error object (which stores a key/value state of validation errors). * * `ngMessages` manages the state of internal messages within its container element. The internal * messages use the `ngMessage` directive and will be inserted/removed from the page depending * on if they're present within the key/value object. By default, only one message will be displayed * at a time and this depends on the prioritization of the messages within the template. (This can * be changed by using the `ng-messages-multiple` or `multiple` attribute on the directive container.) * * A remote template can also be used to promote message reusability and messages can also be * overridden. * * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. * * @usage * ```html * * * ... * ... * ... * * * * * ... * ... * ... * * ``` * * @param {string} ngMessages an angular expression evaluating to a key/value object * (this is typically the $error object on an ngModel instance). * @param {string=} ngMessagesMultiple|multiple when set, all messages will be displayed with true * * @example * * *
* *
myForm.myName.$error = {{ myForm.myName.$error | json }}
* *
*
You did not enter a field
*
Your field is too short
*
Your field is too long
*
*
*
* * angular.module('ngMessagesExample', ['ngMessages']); * *
*/ .directive('ngMessages', ['$animate', function($animate) { var ACTIVE_CLASS = 'ng-active'; var INACTIVE_CLASS = 'ng-inactive'; return { require: 'ngMessages', restrict: 'AE', controller: ['$element', '$scope', '$attrs', function NgMessagesCtrl($element, $scope, $attrs) { var ctrl = this; var latestKey = 0; var nextAttachId = 0; this.getAttachId = function getAttachId() { return nextAttachId++; }; var messages = this.messages = {}; var renderLater, cachedCollection; this.render = function(collection) { collection = collection || {}; renderLater = false; cachedCollection = collection; // this is true if the attribute is empty or if the attribute value is truthy var multiple = isAttrTruthy($scope, $attrs.ngMessagesMultiple) || isAttrTruthy($scope, $attrs.multiple); var unmatchedMessages = []; var matchedKeys = {}; var messageItem = ctrl.head; var messageFound = false; var totalMessages = 0; // we use != instead of !== to allow for both undefined and null values while (messageItem != null) { totalMessages++; var messageCtrl = messageItem.message; var messageUsed = false; if (!messageFound) { forEach(collection, function(value, key) { if (!messageUsed && truthy(value) && messageCtrl.test(key)) { // this is to prevent the same error name from showing up twice if (matchedKeys[key]) return; matchedKeys[key] = true; messageUsed = true; messageCtrl.attach(); } }); } if (messageUsed) { // unless we want to display multiple messages then we should // set a flag here to avoid displaying the next message in the list messageFound = !multiple; } else { unmatchedMessages.push(messageCtrl); } messageItem = messageItem.next; } forEach(unmatchedMessages, function(messageCtrl) { messageCtrl.detach(); }); if (unmatchedMessages.length !== totalMessages) { $animate.setClass($element, ACTIVE_CLASS, INACTIVE_CLASS); } else { $animate.setClass($element, INACTIVE_CLASS, ACTIVE_CLASS); } }; $scope.$watchCollection($attrs.ngMessages || $attrs['for'], ctrl.render); // If the element is destroyed, proactively destroy all the currently visible messages $element.on('$destroy', function() { forEach(messages, function(item) { item.message.detach(); }); }); this.reRender = function() { if (!renderLater) { renderLater = true; $scope.$evalAsync(function() { if (renderLater && cachedCollection) { ctrl.render(cachedCollection); } }); } }; this.register = function(comment, messageCtrl) { var nextKey = latestKey.toString(); messages[nextKey] = { message: messageCtrl }; insertMessageNode($element[0], comment, nextKey); comment.$$ngMessageNode = nextKey; latestKey++; ctrl.reRender(); }; this.deregister = function(comment) { var key = comment.$$ngMessageNode; delete comment.$$ngMessageNode; removeMessageNode($element[0], comment, key); delete messages[key]; ctrl.reRender(); }; function findPreviousMessage(parent, comment) { var prevNode = comment; var parentLookup = []; while (prevNode && prevNode !== parent) { var prevKey = prevNode.$$ngMessageNode; if (prevKey && prevKey.length) { return messages[prevKey]; } // dive deeper into the DOM and examine its children for any ngMessage // comments that may be in an element that appears deeper in the list if (prevNode.childNodes.length && parentLookup.indexOf(prevNode) === -1) { parentLookup.push(prevNode); prevNode = prevNode.childNodes[prevNode.childNodes.length - 1]; } else if (prevNode.previousSibling) { prevNode = prevNode.previousSibling; } else { prevNode = prevNode.parentNode; parentLookup.push(prevNode); } } } function insertMessageNode(parent, comment, key) { var messageNode = messages[key]; if (!ctrl.head) { ctrl.head = messageNode; } else { var match = findPreviousMessage(parent, comment); if (match) { messageNode.next = match.next; match.next = messageNode; } else { messageNode.next = ctrl.head; ctrl.head = messageNode; } } } function removeMessageNode(parent, comment, key) { var messageNode = messages[key]; var match = findPreviousMessage(parent, comment); if (match) { match.next = messageNode.next; } else { ctrl.head = messageNode.next; } } }] }; function isAttrTruthy(scope, attr) { return (isString(attr) && attr.length === 0) || //empty attribute truthy(scope.$eval(attr)); } function truthy(val) { return isString(val) ? val.length : !!val; } }]) /** * @ngdoc directive * @name ngMessagesInclude * @restrict AE * @scope * * @description * `ngMessagesInclude` is a directive with the purpose to import existing ngMessage template * code from a remote template and place the downloaded template code into the exact spot * that the ngMessagesInclude directive is placed within the ngMessages container. This allows * for a series of pre-defined messages to be reused and also allows for the developer to * determine what messages are overridden due to the placement of the ngMessagesInclude directive. * * @usage * ```html * * * ... * * * * * ... * * ``` * * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. * * @param {string} ngMessagesInclude|src a string value corresponding to the remote template. */ .directive('ngMessagesInclude', ['$templateRequest', '$document', '$compile', function($templateRequest, $document, $compile) { return { restrict: 'AE', require: '^^ngMessages', // we only require this for validation sake link: function($scope, element, attrs) { var src = attrs.ngMessagesInclude || attrs.src; $templateRequest(src).then(function(html) { if ($scope.$$destroyed) return; if (isString(html) && !html.trim()) { // Empty template - nothing to compile replaceElementWithMarker(element, src); } else { // Non-empty template - compile and link $compile(html)($scope, function(contents) { element.after(contents); replaceElementWithMarker(element, src); }); } }); } }; // Helpers function replaceElementWithMarker(element, src) { // A comment marker is placed for debugging purposes var comment = $compile.$$createComment ? $compile.$$createComment('ngMessagesInclude', src) : $document[0].createComment(' ngMessagesInclude: ' + src + ' '); var marker = jqLite(comment); element.after(marker); // Don't pollute the DOM anymore by keeping an empty directive element element.remove(); } }]) /** * @ngdoc directive * @name ngMessage * @restrict AE * @scope * @priority 1 * * @description * `ngMessage` is a directive with the purpose to show and hide a particular message. * For `ngMessage` to operate, a parent `ngMessages` directive on a parent DOM element * must be situated since it determines which messages are visible based on the state * of the provided key/value map that `ngMessages` listens on. * * More information about using `ngMessage` can be found in the * {@link module:ngMessages `ngMessages` module documentation}. * * @usage * ```html * * * ... * ... * * * * * ... * ... * * ``` * * @param {expression} ngMessage|when a string value corresponding to the message key. */ .directive('ngMessage', ngMessageDirectiveFactory()) /** * @ngdoc directive * @name ngMessageExp * @restrict AE * @priority 1 * @scope * * @description * `ngMessageExp` is the same as {@link directive:ngMessage `ngMessage`}, but instead of a static * value, it accepts an expression to be evaluated for the message key. * * @usage * ```html * * * ... * * * * * ... * * ``` * * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. * * @param {expression} ngMessageExp|whenExp an expression value corresponding to the message key. */ .directive('ngMessageExp', ngMessageDirectiveFactory()); function ngMessageDirectiveFactory() { return ['$animate', function($animate) { return { restrict: 'AE', transclude: 'element', priority: 1, // must run before ngBind, otherwise the text is set on the comment terminal: true, require: '^^ngMessages', link: function(scope, element, attrs, ngMessagesCtrl, $transclude) { var commentNode = element[0]; var records; var staticExp = attrs.ngMessage || attrs.when; var dynamicExp = attrs.ngMessageExp || attrs.whenExp; var assignRecords = function(items) { records = items ? (isArray(items) ? items : items.split(/[\s,]+/)) : null; ngMessagesCtrl.reRender(); }; if (dynamicExp) { assignRecords(scope.$eval(dynamicExp)); scope.$watchCollection(dynamicExp, assignRecords); } else { assignRecords(staticExp); } var currentElement, messageCtrl; ngMessagesCtrl.register(commentNode, messageCtrl = { test: function(name) { return contains(records, name); }, attach: function() { if (!currentElement) { $transclude(function(elm, newScope) { $animate.enter(elm, null, element); currentElement = elm; // Each time we attach this node to a message we get a new id that we can match // when we are destroying the node later. var $$attachId = currentElement.$$attachId = ngMessagesCtrl.getAttachId(); // in the event that the element or a parent element is destroyed // by another structural directive then it's time // to deregister the message from the controller currentElement.on('$destroy', function() { if (currentElement && currentElement.$$attachId === $$attachId) { ngMessagesCtrl.deregister(commentNode); messageCtrl.detach(); } newScope.$destroy(); }); }); } }, detach: function() { if (currentElement) { var elm = currentElement; currentElement = null; $animate.leave(elm); } } }); } }; }]; function contains(collection, key) { if (collection) { return isArray(collection) ? collection.indexOf(key) >= 0 : collection.hasOwnProperty(key); } } } })(window, window.angular); 'use strict'; var app = angular .module('angular-promise-polyfill', []) .run(['$q', '$window', function($q, $window) { $window.Promise = function(executor) { return $q(executor); }; $window.Promise.all = $q.all.bind($q); $window.Promise.reject = $q.reject.bind($q); $window.Promise.resolve = $q.when.bind($q); $window.Promise.race = function(promises) { var promiseMgr = $q.defer(); for(var i = 0; i < promises.length; i++) { promises[i].then(function(result) { if(promiseMgr) { promiseMgr.resolve(result); promiseMgr = null; } }); promises[i].catch(function(result) { if(promiseMgr) { promiseMgr.reject(result); promiseMgr = null; } }); } return promiseMgr.promise; }; }]); if (typeof module === 'object') { module.exports = app.name; } /** * @license AngularJS v1.6.7 * (c) 2010-2017 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular) {'use strict'; var $resourceMinErr = angular.$$minErr('$resource'); // Helper functions and regex to lookup a dotted path on an object // stopping at undefined/null. The path must be composed of ASCII // identifiers (just like $parse) var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/; function isValidDottedPath(path) { return (path != null && path !== '' && path !== 'hasOwnProperty' && MEMBER_NAME_REGEX.test('.' + path)); } function lookupDottedPath(obj, path) { if (!isValidDottedPath(path)) { throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path); } var keys = path.split('.'); for (var i = 0, ii = keys.length; i < ii && angular.isDefined(obj); i++) { var key = keys[i]; obj = (obj !== null) ? obj[key] : undefined; } return obj; } /** * Create a shallow copy of an object and clear other fields from the destination */ function shallowClearAndCopy(src, dst) { dst = dst || {}; angular.forEach(dst, function(value, key) { delete dst[key]; }); for (var key in src) { if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) { dst[key] = src[key]; } } return dst; } /** * @ngdoc module * @name ngResource * @description * * The `ngResource` module provides interaction support with RESTful services * via the $resource service. * * See {@link ngResource.$resourceProvider} and {@link ngResource.$resource} for usage. */ /** * @ngdoc provider * @name $resourceProvider * * @description * * Use `$resourceProvider` to change the default behavior of the {@link ngResource.$resource} * service. * * ## Dependencies * Requires the {@link ngResource } module to be installed. * */ /** * @ngdoc service * @name $resource * @requires $http * @requires ng.$log * @requires $q * @requires ng.$timeout * * @description * A factory which creates a resource object that lets you interact with * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. * * The returned resource object has action methods which provide high-level behaviors without * the need to interact with the low level {@link ng.$http $http} service. * * Requires the {@link ngResource `ngResource`} module to be installed. * * By default, trailing slashes will be stripped from the calculated URLs, * which can pose problems with server backends that do not expect that * behavior. This can be disabled by configuring the `$resourceProvider` like * this: * * ```js app.config(['$resourceProvider', function($resourceProvider) { // Don't strip trailing slashes from calculated URLs $resourceProvider.defaults.stripTrailingSlashes = false; }]); * ``` * * @param {string} url A parameterized URL template with parameters prefixed by `:` as in * `/user/:username`. If you are using a URL with a port number (e.g. * `http://example.com:8080/api`), it will be respected. * * If you are using a url with a suffix, just add the suffix, like this: * `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')` * or even `$resource('http://example.com/resource/:resource_id.:format')` * If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be * collapsed down to a single `.`. If you need this sequence to appear and not collapse then you * can escape it with `/\.`. * * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in * `actions` methods. If a parameter value is a function, it will be called every time * a param value needs to be obtained for a request (unless the param was overridden). The function * will be passed the current data value as an argument. * * Each key value in the parameter object is first bound to url template if present and then any * excess keys are appended to the url search query after the `?`. * * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in * URL `/path/greet?salutation=Hello`. * * If the parameter value is prefixed with `@`, then the value for that parameter will be * extracted from the corresponding property on the `data` object (provided when calling actions * with a request body). * For example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of * `someParam` will be `data.someProp`. * Note that the parameter will be ignored, when calling a "GET" action method (i.e. an action * method that does not accept a request body) * * @param {Object.=} actions Hash with declaration of custom actions that will be available * in addition to the default set of resource actions (see below). If a custom action has the same * key as a default action (e.g. `save`), then the default action will be *overwritten*, and not * extended. * * The declaration should be created in the format of {@link ng.$http#usage $http.config}: * * {action1: {method:?, params:?, isArray:?, headers:?, ...}, * action2: {method:?, params:?, isArray:?, headers:?, ...}, * ...} * * Where: * * - **`action`** – {string} – The name of action. This name becomes the name of the method on * your resource object. * - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`, * `DELETE`, `JSONP`, etc). * - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of * the parameter value is a function, it will be called every time when a param value needs to * be obtained for a request (unless the param was overridden). The function will be passed the * current data value as an argument. * - **`url`** – {string} – action specific `url` override. The url templating is supported just * like for the resource-level urls. * - **`isArray`** – {boolean=} – If true then the returned object for this action is an array, * see `returns` section. * - **`transformRequest`** – * `{function(data, headersGetter)|Array.}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * By default, transformRequest will contain one function that checks if the request data is * an object and serializes it using `angular.toJson`. To prevent this behavior, set * `transformRequest` to an empty array: `transformRequest: []` * - **`transformResponse`** – * `{function(data, headersGetter, status)|Array.}` – * transform function or an array of such functions. The transform function takes the http * response body, headers and status and returns its transformed (typically deserialized) * version. * By default, transformResponse will contain one function that checks if the response looks * like a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior, * set `transformResponse` to an empty array: `transformResponse: []` * - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link ng.$cacheFactory $cacheFactory} is supplied, this cache will be used for * caching. * - **`timeout`** – `{number}` – timeout in milliseconds.
* **Note:** In contrast to {@link ng.$http#usage $http.config}, {@link ng.$q promises} are * **not** supported in $resource, because the same value would be used for multiple requests. * If you are looking for a way to cancel requests, you should use the `cancellable` option. * - **`cancellable`** – `{boolean}` – if set to true, the request made by a "non-instance" call * will be cancelled (if not already completed) by calling `$cancelRequest()` on the call's * return value. Calling `$cancelRequest()` for a non-cancellable or an already * completed/cancelled request will have no effect.
* - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the * XHR object. See * [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5) * for more information. * - **`responseType`** - `{string}` - see * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). * - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods - * `response` and `responseError`. Both `response` and `responseError` interceptors get called * with `http response` object. See {@link ng.$http $http interceptors}. In addition, the * resource instance or array object is accessible by the `resource` property of the * `http response` object. * Keep in mind that the associated promise will be resolved with the value returned by the * response interceptor, if one is specified. The default response interceptor returns * `response.resource` (i.e. the resource instance or array). * - **`hasBody`** - `{boolean}` - allows to specify if a request body should be included or not. * If not specified only POST, PUT and PATCH requests will have a body. * * @param {Object} options Hash with custom settings that should extend the * default `$resourceProvider` behavior. The supported options are: * * - **`stripTrailingSlashes`** – {boolean} – If true then the trailing * slashes from any calculated URL will be stripped. (Defaults to true.) * - **`cancellable`** – {boolean} – If true, the request made by a "non-instance" call will be * cancelled (if not already completed) by calling `$cancelRequest()` on the call's return value. * This can be overwritten per action. (Defaults to false.) * * @returns {Object} A resource "class" object with methods for the default set of resource actions * optionally extended with custom `actions`. The default set contains these actions: * ```js * { 'get': {method:'GET'}, * 'save': {method:'POST'}, * 'query': {method:'GET', isArray:true}, * 'remove': {method:'DELETE'}, * 'delete': {method:'DELETE'} }; * ``` * * Calling these methods invoke an {@link ng.$http} with the specified http method, * destination and parameters. When the data is returned from the server then the object is an * instance of the resource class. The actions `save`, `remove` and `delete` are available on it * as methods with the `$` prefix. This allows you to easily perform CRUD operations (create, * read, update, delete) on server-side data like this: * ```js * var User = $resource('/user/:userId', {userId:'@id'}); * var user = User.get({userId:123}, function() { * user.abc = true; * user.$save(); * }); * ``` * * It is important to realize that invoking a $resource object method immediately returns an * empty reference (object or array depending on `isArray`). Once the data is returned from the * server the existing reference is populated with the actual data. This is a useful trick since * usually the resource is assigned to a model which is then rendered by the view. Having an empty * object results in no rendering, once the data arrives from the server then the object is * populated with the data and the view automatically re-renders itself showing the new data. This * means that in most cases one never has to write a callback function for the action methods. * * The action methods on the class object or instance object can be invoked with the following * parameters: * * - "class" actions without a body: `Resource.action([parameters], [success], [error])` * - "class" actions with a body: `Resource.action([parameters], postData, [success], [error])` * - instance actions: `instance.$action([parameters], [success], [error])` * * * When calling instance methods, the instance itself is used as the request body (if the action * should have a body). By default, only actions using `POST`, `PUT` or `PATCH` have request * bodies, but you can use the `hasBody` configuration option to specify whether an action * should have a body or not (regardless of its HTTP method). * * * Success callback is called with (value (Object|Array), responseHeaders (Function), * status (number), statusText (string)) arguments, where the value is the populated resource * instance or collection object. The error callback is called with (httpResponse) argument. * * Class actions return empty instance (with additional properties below). * Instance actions return promise of the action. * * The Resource instances and collections have these additional properties: * * - `$promise`: the {@link ng.$q promise} of the original server interaction that created this * instance or collection. * * On success, the promise is resolved with the same resource instance or collection object, * updated with data from server. This makes it easy to use in * {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view * rendering until the resource(s) are loaded. * * On failure, the promise is rejected with the {@link ng.$http http response} object. * * If an interceptor object was provided, the promise will instead be resolved with the value * returned by the interceptor. * * - `$resolved`: `true` after first server interaction is completed (either with success or * rejection), `false` before that. Knowing if the Resource has been resolved is useful in * data-binding. * * The Resource instances and collections have these additional methods: * * - `$cancelRequest`: If there is a cancellable, pending request related to the instance or * collection, calling this method will abort the request. * * The Resource instances have these additional methods: * * - `toJSON`: It returns a simple object without any of the extra properties added as part of * the Resource API. This object can be serialized through {@link angular.toJson} safely * without attaching Angular-specific fields. Notice that `JSON.stringify` (and * `angular.toJson`) automatically use this method when serializing a Resource instance * (see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON%28%29_behavior)). * * @example * * ### Credit card resource * * ```js // Define CreditCard class var CreditCard = $resource('/user/:userId/card/:cardId', {userId:123, cardId:'@id'}, { charge: {method:'POST', params:{charge:true}} }); // We can retrieve a collection from the server var cards = CreditCard.query(function() { // GET: /user/123/card // server returns: [ {id:456, number:'1234', name:'Smith'} ]; var card = cards[0]; // each item is an instance of CreditCard expect(card instanceof CreditCard).toEqual(true); card.name = "J. Smith"; // non GET methods are mapped onto the instances card.$save(); // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // our custom method is mapped as well. card.$charge({amount:9.99}); // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} }); // we can create an instance as well var newCard = new CreditCard({number:'0123'}); newCard.name = "Mike Smith"; newCard.$save(); // POST: /user/123/card {number:'0123', name:'Mike Smith'} // server returns: {id:789, number:'0123', name: 'Mike Smith'}; expect(newCard.id).toEqual(789); * ``` * * The object returned from this function execution is a resource "class" which has "static" method * for each action in the definition. * * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and * `headers`. * * @example * * ### User resource * * When the data is returned from the server then the object is an instance of the resource type and * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD * operations (create, read, update, delete) on server-side data. ```js var User = $resource('/user/:userId', {userId:'@id'}); User.get({userId:123}, function(user) { user.abc = true; user.$save(); }); ``` * * It's worth noting that the success callback for `get`, `query` and other methods gets passed * in the response that came from the server as well as $http header getter function, so one * could rewrite the above example and get access to http headers as: * ```js var User = $resource('/user/:userId', {userId:'@id'}); User.get({userId:123}, function(user, getResponseHeaders){ user.abc = true; user.$save(function(user, putResponseHeaders) { //user => saved user object //putResponseHeaders => $http header getter }); }); ``` * * You can also access the raw `$http` promise via the `$promise` property on the object returned * ``` var User = $resource('/user/:userId', {userId:'@id'}); User.get({userId:123}) .$promise.then(function(user) { $scope.user = user; }); ``` * * @example * * ### Creating a custom 'PUT' request * * In this example we create a custom method on our resource to make a PUT request * ```js * var app = angular.module('app', ['ngResource', 'ngRoute']); * * // Some APIs expect a PUT request in the format URL/object/ID * // Here we are creating an 'update' method * app.factory('Notes', ['$resource', function($resource) { * return $resource('/notes/:id', null, * { * 'update': { method:'PUT' } * }); * }]); * * // In our controller we get the ID from the URL using ngRoute and $routeParams * // We pass in $routeParams and our Notes factory along with $scope * app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes', function($scope, $routeParams, Notes) { * // First get a note object from the factory * var note = Notes.get({ id:$routeParams.id }); * $id = note.id; * * // Now call update passing in the ID first then the object you are updating * Notes.update({ id:$id }, note); * * // This will PUT /notes/ID with the note object in the request payload * }]); * ``` * * @example * * ### Cancelling requests * * If an action's configuration specifies that it is cancellable, you can cancel the request related * to an instance or collection (as long as it is a result of a "non-instance" call): * ```js // ...defining the `Hotel` resource... var Hotel = $resource('/api/hotel/:id', {id: '@id'}, { // Let's make the `query()` method cancellable query: {method: 'get', isArray: true, cancellable: true} }); // ...somewhere in the PlanVacationController... ... this.onDestinationChanged = function onDestinationChanged(destination) { // We don't care about any pending request for hotels // in a different destination any more this.availableHotels.$cancelRequest(); // Let's query for hotels in '' // (calls: /api/hotel?location=) this.availableHotels = Hotel.query({location: destination}); }; ``` * */ angular.module('ngResource', ['ng']). info({ angularVersion: '1.6.7' }). provider('$resource', function ResourceProvider() { var PROTOCOL_AND_IPV6_REGEX = /^https?:\/\/\[[^\]]*][^/]*/; var provider = this; /** * @ngdoc property * @name $resourceProvider#defaults * @description * Object containing default options used when creating `$resource` instances. * * The default values satisfy a wide range of usecases, but you may choose to overwrite any of * them to further customize your instances. The available properties are: * * - **stripTrailingSlashes** – `{boolean}` – If true, then the trailing slashes from any * calculated URL will be stripped.
* (Defaults to true.) * - **cancellable** – `{boolean}` – If true, the request made by a "non-instance" call will be * cancelled (if not already completed) by calling `$cancelRequest()` on the call's return * value. For more details, see {@link ngResource.$resource}. This can be overwritten per * resource class or action.
* (Defaults to false.) * - **actions** - `{Object.}` - A hash with default actions declarations. Actions are * high-level methods corresponding to RESTful actions/methods on resources. An action may * specify what HTTP method to use, what URL to hit, if the return value will be a single * object or a collection (array) of objects etc. For more details, see * {@link ngResource.$resource}. The actions can also be enhanced or overwritten per resource * class.
* The default actions are: * ```js * { * get: {method: 'GET'}, * save: {method: 'POST'}, * query: {method: 'GET', isArray: true}, * remove: {method: 'DELETE'}, * delete: {method: 'DELETE'} * } * ``` * * #### Example * * For example, you can specify a new `update` action that uses the `PUT` HTTP verb: * * ```js * angular. * module('myApp'). * config(['$resourceProvider', function ($resourceProvider) { * $resourceProvider.defaults.actions.update = { * method: 'PUT' * }; * }]); * ``` * * Or you can even overwrite the whole `actions` list and specify your own: * * ```js * angular. * module('myApp'). * config(['$resourceProvider', function ($resourceProvider) { * $resourceProvider.defaults.actions = { * create: {method: 'POST'}, * get: {method: 'GET'}, * getAll: {method: 'GET', isArray:true}, * update: {method: 'PUT'}, * delete: {method: 'DELETE'} * }; * }); * ``` * */ this.defaults = { // Strip slashes by default stripTrailingSlashes: true, // Make non-instance requests cancellable (via `$cancelRequest()`) cancellable: false, // Default actions configuration actions: { 'get': {method: 'GET'}, 'save': {method: 'POST'}, 'query': {method: 'GET', isArray: true}, 'remove': {method: 'DELETE'}, 'delete': {method: 'DELETE'} } }; this.$get = ['$http', '$log', '$q', '$timeout', function($http, $log, $q, $timeout) { var noop = angular.noop, forEach = angular.forEach, extend = angular.extend, copy = angular.copy, isArray = angular.isArray, isDefined = angular.isDefined, isFunction = angular.isFunction, isNumber = angular.isNumber, encodeUriQuery = angular.$$encodeUriQuery, encodeUriSegment = angular.$$encodeUriSegment; function Route(template, defaults) { this.template = template; this.defaults = extend({}, provider.defaults, defaults); this.urlParams = {}; } Route.prototype = { setUrlParams: function(config, params, actionUrl) { var self = this, url = actionUrl || self.template, val, encodedVal, protocolAndIpv6 = ''; var urlParams = self.urlParams = Object.create(null); forEach(url.split(/\W/), function(param) { if (param === 'hasOwnProperty') { throw $resourceMinErr('badname', 'hasOwnProperty is not a valid parameter name.'); } if (!(new RegExp('^\\d+$').test(param)) && param && (new RegExp('(^|[^\\\\]):' + param + '(\\W|$)').test(url))) { urlParams[param] = { isQueryParamValue: (new RegExp('\\?.*=:' + param + '(?:\\W|$)')).test(url) }; } }); url = url.replace(/\\:/g, ':'); url = url.replace(PROTOCOL_AND_IPV6_REGEX, function(match) { protocolAndIpv6 = match; return ''; }); params = params || {}; forEach(self.urlParams, function(paramInfo, urlParam) { val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; if (isDefined(val) && val !== null) { if (paramInfo.isQueryParamValue) { encodedVal = encodeUriQuery(val, true); } else { encodedVal = encodeUriSegment(val); } url = url.replace(new RegExp(':' + urlParam + '(\\W|$)', 'g'), function(match, p1) { return encodedVal + p1; }); } else { url = url.replace(new RegExp('(/?):' + urlParam + '(\\W|$)', 'g'), function(match, leadingSlashes, tail) { if (tail.charAt(0) === '/') { return tail; } else { return leadingSlashes + tail; } }); } }); // strip trailing slashes and set the url (unless this behavior is specifically disabled) if (self.defaults.stripTrailingSlashes) { url = url.replace(/\/+$/, '') || '/'; } // Collapse `/.` if found in the last URL path segment before the query. // E.g. `http://url.com/id/.format?q=x` becomes `http://url.com/id.format?q=x`. url = url.replace(/\/\.(?=\w+($|\?))/, '.'); // Replace escaped `/\.` with `/.`. // (If `\.` comes from a param value, it will be encoded as `%5C.`.) config.url = protocolAndIpv6 + url.replace(/\/(\\|%5C)\./, '/.'); // set params - delegate param encoding to $http forEach(params, function(value, key) { if (!self.urlParams[key]) { config.params = config.params || {}; config.params[key] = value; } }); } }; function resourceFactory(url, paramDefaults, actions, options) { var route = new Route(url, options); actions = extend({}, provider.defaults.actions, actions); function extractParams(data, actionParams) { var ids = {}; actionParams = extend({}, paramDefaults, actionParams); forEach(actionParams, function(value, key) { if (isFunction(value)) { value = value(data); } ids[key] = value && value.charAt && value.charAt(0) === '@' ? lookupDottedPath(data, value.substr(1)) : value; }); return ids; } function defaultResponseInterceptor(response) { return response.resource; } function Resource(value) { shallowClearAndCopy(value || {}, this); } Resource.prototype.toJSON = function() { var data = extend({}, this); delete data.$promise; delete data.$resolved; delete data.$cancelRequest; return data; }; forEach(actions, function(action, name) { var hasBody = action.hasBody === true || (action.hasBody !== false && /^(POST|PUT|PATCH)$/i.test(action.method)); var numericTimeout = action.timeout; var cancellable = isDefined(action.cancellable) ? action.cancellable : route.defaults.cancellable; if (numericTimeout && !isNumber(numericTimeout)) { $log.debug('ngResource:\n' + ' Only numeric values are allowed as `timeout`.\n' + ' Promises are not supported in $resource, because the same value would ' + 'be used for multiple requests. If you are looking for a way to cancel ' + 'requests, you should use the `cancellable` option.'); delete action.timeout; numericTimeout = null; } Resource[name] = function(a1, a2, a3, a4) { var params = {}, data, success, error; switch (arguments.length) { case 4: error = a4; success = a3; // falls through case 3: case 2: if (isFunction(a2)) { if (isFunction(a1)) { success = a1; error = a2; break; } success = a2; error = a3; // falls through } else { params = a1; data = a2; success = a3; break; } // falls through case 1: if (isFunction(a1)) success = a1; else if (hasBody) data = a1; else params = a1; break; case 0: break; default: throw $resourceMinErr('badargs', 'Expected up to 4 arguments [params, data, success, error], got {0} arguments', arguments.length); } var isInstanceCall = this instanceof Resource; var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data)); var httpConfig = {}; var responseInterceptor = action.interceptor && action.interceptor.response || defaultResponseInterceptor; var responseErrorInterceptor = action.interceptor && action.interceptor.responseError || undefined; var hasError = !!error; var hasResponseErrorInterceptor = !!responseErrorInterceptor; var timeoutDeferred; var numericTimeoutPromise; forEach(action, function(value, key) { switch (key) { default: httpConfig[key] = copy(value); break; case 'params': case 'isArray': case 'interceptor': case 'cancellable': break; } }); if (!isInstanceCall && cancellable) { timeoutDeferred = $q.defer(); httpConfig.timeout = timeoutDeferred.promise; if (numericTimeout) { numericTimeoutPromise = $timeout(timeoutDeferred.resolve, numericTimeout); } } if (hasBody) httpConfig.data = data; route.setUrlParams(httpConfig, extend({}, extractParams(data, action.params || {}), params), action.url); var promise = $http(httpConfig).then(function(response) { var data = response.data; if (data) { // Need to convert action.isArray to boolean in case it is undefined if (isArray(data) !== (!!action.isArray)) { throw $resourceMinErr('badcfg', 'Error in resource configuration for action `{0}`. Expected response to ' + 'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object', isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url); } if (action.isArray) { value.length = 0; forEach(data, function(item) { if (typeof item === 'object') { value.push(new Resource(item)); } else { // Valid JSON values may be string literals, and these should not be converted // into objects. These items will not have access to the Resource prototype // methods, but unfortunately there value.push(item); } }); } else { var promise = value.$promise; // Save the promise shallowClearAndCopy(data, value); value.$promise = promise; // Restore the promise } } response.resource = value; return response; }, function(response) { response.resource = value; return $q.reject(response); }); promise = promise['finally'](function() { value.$resolved = true; if (!isInstanceCall && cancellable) { value.$cancelRequest = noop; $timeout.cancel(numericTimeoutPromise); timeoutDeferred = numericTimeoutPromise = httpConfig.timeout = null; } }); promise = promise.then( function(response) { var value = responseInterceptor(response); (success || noop)(value, response.headers, response.status, response.statusText); return value; }, (hasError || hasResponseErrorInterceptor) ? function(response) { if (hasError && !hasResponseErrorInterceptor) { // Avoid `Possibly Unhandled Rejection` error, // but still fulfill the returned promise with a rejection promise.catch(noop); } if (hasError) error(response); return hasResponseErrorInterceptor ? responseErrorInterceptor(response) : $q.reject(response); } : undefined); if (!isInstanceCall) { // we are creating instance / collection // - set the initial promise // - return the instance / collection value.$promise = promise; value.$resolved = false; if (cancellable) value.$cancelRequest = cancelRequest; return value; } // instance call return promise; function cancelRequest(value) { promise.catch(noop); if (timeoutDeferred !== null) { timeoutDeferred.resolve(value); } } }; Resource.prototype['$' + name] = function(params, success, error) { if (isFunction(params)) { error = success; success = params; params = {}; } var result = Resource[name].call(this, params, this, success, error); return result.$promise || result; }; }); return Resource; } return resourceFactory; }]; }); })(window, window.angular); /** * @license AngularJS v1.6.7 * (c) 2010-2017 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular) {'use strict'; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Any commits to this file should be reviewed with security in mind. * * Changes to this file can potentially create security vulnerabilities. * * An approval from 2 Core members with history of modifying * * this file is required. * * * * Does the change somehow allow for arbitrary javascript to be executed? * * Or allows for someone to change the prototype of built-in objects? * * Or gives undesired access to variables likes document or window? * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ var $sanitizeMinErr = angular.$$minErr('$sanitize'); var bind; var extend; var forEach; var isDefined; var lowercase; var noop; var nodeContains; var htmlParser; var htmlSanitizeWriter; /** * @ngdoc module * @name ngSanitize * @description * * The `ngSanitize` module provides functionality to sanitize HTML. * * See {@link ngSanitize.$sanitize `$sanitize`} for usage. */ /** * @ngdoc service * @name $sanitize * @kind function * * @description * Sanitizes an html string by stripping all potentially dangerous tokens. * * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string. * * The whitelist for URL sanitization of attribute values is configured using the functions * `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider * `$compileProvider`}. * * The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}. * * @param {string} html HTML input. * @returns {string} Sanitized HTML. * * @example
Snippet:
Directive How Source Rendered
ng-bind-html Automatically uses $sanitize
<div ng-bind-html="snippet">
</div>
ng-bind-html Bypass $sanitize by explicitly trusting the dangerous value
<div ng-bind-html="deliberatelyTrustDangerousSnippet()">
</div>
ng-bind Automatically escapes
<div ng-bind="snippet">
</div>
it('should sanitize the html snippet by default', function() { expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')). toBe('

an html\nclick here\nsnippet

'); }); it('should inline raw snippet if bound to a trusted value', function() { expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')). toBe("

an html\n" + "click here\n" + "snippet

"); }); it('should escape snippet without any filter', function() { expect(element(by.css('#bind-default div')).getAttribute('innerHTML')). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new text'); expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')). toBe('new text'); expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')).toBe( 'new text'); expect(element(by.css('#bind-default div')).getAttribute('innerHTML')).toBe( "new <b onclick=\"alert(1)\">text</b>"); });
*/ /** * @ngdoc provider * @name $sanitizeProvider * @this * * @description * Creates and configures {@link $sanitize} instance. */ function $SanitizeProvider() { var svgEnabled = false; this.$get = ['$$sanitizeUri', function($$sanitizeUri) { if (svgEnabled) { extend(validElements, svgElements); } return function(html) { var buf = []; htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { return !/^unsafe:/.test($$sanitizeUri(uri, isImage)); })); return buf.join(''); }; }]; /** * @ngdoc method * @name $sanitizeProvider#enableSvg * @kind function * * @description * Enables a subset of svg to be supported by the sanitizer. * *
*

By enabling this setting without taking other precautions, you might expose your * application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned * outside of the containing element and be rendered over other elements on the page (e.g. a login * link). Such behavior can then result in phishing incidents.

* *

To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg * tags within the sanitized content:

* *
* *

   *   .rootOfTheIncludedContent svg {
   *     overflow: hidden !important;
   *   }
   *   
*
* * @param {boolean=} flag Enable or disable SVG support in the sanitizer. * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called * without an argument or self for chaining otherwise. */ this.enableSvg = function(enableSvg) { if (isDefined(enableSvg)) { svgEnabled = enableSvg; return this; } else { return svgEnabled; } }; ////////////////////////////////////////////////////////////////////////////////////////////////// // Private stuff ////////////////////////////////////////////////////////////////////////////////////////////////// bind = angular.bind; extend = angular.extend; forEach = angular.forEach; isDefined = angular.isDefined; lowercase = angular.lowercase; noop = angular.noop; htmlParser = htmlParserImpl; htmlSanitizeWriter = htmlSanitizeWriterImpl; nodeContains = window.Node.prototype.contains || /** @this */ function(arg) { // eslint-disable-next-line no-bitwise return !!(this.compareDocumentPosition(arg) & 16); }; // Regular Expressions for parsing tags and attributes var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, // Match everything outside of normal chars and " (quote character) NON_ALPHANUMERIC_REGEXP = /([^#-~ |!])/g; // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements var voidElements = toMap('area,br,col,hr,img,wbr'); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags var optionalEndTagBlockElements = toMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'), optionalEndTagInlineElements = toMap('rp,rt'), optionalEndTagElements = extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); // Safe Block Elements - HTML5 var blockElements = extend({}, optionalEndTagBlockElements, toMap('address,article,' + 'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' + 'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul')); // Inline Elements - HTML5 var inlineElements = extend({}, optionalEndTagInlineElements, toMap('a,abbr,acronym,b,' + 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' + 'samp,small,span,strike,strong,sub,sup,time,tt,u,var')); // SVG Elements // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements // Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted. // They can potentially allow for arbitrary javascript to be executed. See #11290 var svgElements = toMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' + 'hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,' + 'radialGradient,rect,stop,svg,switch,text,title,tspan'); // Blocked Elements (will be stripped) var blockedElements = toMap('script,style'); var validElements = extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements); //Attributes that have href and hence need to be sanitized var uriAttrs = toMap('background,cite,href,longdesc,src,xlink:href'); var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' + 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' + 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' + 'valign,value,vspace,width'); // SVG attributes (without "id" and "name" attributes) // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' + 'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' + 'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' + 'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' + 'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' + 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' + 'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' + 'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' + 'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' + 'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' + 'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' + 'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' + 'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' + 'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' + 'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true); var validAttrs = extend({}, uriAttrs, svgAttrs, htmlAttrs); function toMap(str, lowercaseKeys) { var obj = {}, items = str.split(','), i; for (i = 0; i < items.length; i++) { obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true; } return obj; } /** * Create an inert document that contains the dirty HTML that needs sanitizing * Depending upon browser support we use one of three strategies for doing this. * Support: Safari 10.x -> XHR strategy * Support: Firefox -> DomParser strategy */ var getInertBodyElement /* function(html: string): HTMLBodyElement */ = (function(window, document) { var inertDocument; if (document && document.implementation) { inertDocument = document.implementation.createHTMLDocument('inert'); } else { throw $sanitizeMinErr('noinert', 'Can\'t create an inert html document'); } var inertBodyElement = (inertDocument.documentElement || inertDocument.getDocumentElement()).querySelector('body'); // Check for the Safari 10.1 bug - which allows JS to run inside the SVG G element inertBodyElement.innerHTML = ''; if (!inertBodyElement.querySelector('svg')) { return getInertBodyElement_XHR; } else { // Check for the Firefox bug - which prevents the inner img JS from being sanitized inertBodyElement.innerHTML = '

'; if (inertBodyElement.querySelector('svg img')) { return getInertBodyElement_DOMParser; } else { return getInertBodyElement_InertDocument; } } function getInertBodyElement_XHR(html) { // We add this dummy element to ensure that the rest of the content is parsed as expected // e.g. leading whitespace is maintained and tags like `` do not get hoisted to the `` tag. html = '' + html; try { html = encodeURI(html); } catch (e) { return undefined; } var xhr = new window.XMLHttpRequest(); xhr.responseType = 'document'; xhr.open('GET', 'data:text/html;charset=utf-8,' + html, false); xhr.send(null); var body = xhr.response.body; body.firstChild.remove(); return body; } function getInertBodyElement_DOMParser(html) { // We add this dummy element to ensure that the rest of the content is parsed as expected // e.g. leading whitespace is maintained and tags like `` do not get hoisted to the `` tag. html = '' + html; try { var body = new window.DOMParser().parseFromString(html, 'text/html').body; body.firstChild.remove(); return body; } catch (e) { return undefined; } } function getInertBodyElement_InertDocument(html) { inertBodyElement.innerHTML = html; // Support: IE 9-11 only // strip custom-namespaced attributes on IE<=11 if (document.documentMode) { stripCustomNsAttrs(inertBodyElement); } return inertBodyElement; } })(window, window.document); /** * @example * htmlParser(htmlString, { * start: function(tag, attrs) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParserImpl(html, handler) { if (html === null || html === undefined) { html = ''; } else if (typeof html !== 'string') { html = '' + html; } var inertBodyElement = getInertBodyElement(html); if (!inertBodyElement) return ''; //mXSS protection var mXSSAttempts = 5; do { if (mXSSAttempts === 0) { throw $sanitizeMinErr('uinput', 'Failed to sanitize html because the input is unstable'); } mXSSAttempts--; // trigger mXSS if it is going to happen by reading and writing the innerHTML html = inertBodyElement.innerHTML; inertBodyElement = getInertBodyElement(html); } while (html !== inertBodyElement.innerHTML); var node = inertBodyElement.firstChild; while (node) { switch (node.nodeType) { case 1: // ELEMENT_NODE handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes)); break; case 3: // TEXT NODE handler.chars(node.textContent); break; } var nextNode; if (!(nextNode = node.firstChild)) { if (node.nodeType === 1) { handler.end(node.nodeName.toLowerCase()); } nextNode = getNonDescendant('nextSibling', node); if (!nextNode) { while (nextNode == null) { node = getNonDescendant('parentNode', node); if (node === inertBodyElement) break; nextNode = getNonDescendant('nextSibling', node); if (node.nodeType === 1) { handler.end(node.nodeName.toLowerCase()); } } } } node = nextNode; } while ((node = inertBodyElement.firstChild)) { inertBodyElement.removeChild(node); } } function attrToMap(attrs) { var map = {}; for (var i = 0, ii = attrs.length; i < ii; i++) { var attr = attrs[i]; map[attr.name] = attr.value; } return map; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns {string} escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&'). replace(SURROGATE_PAIR_REGEXP, function(value) { var hi = value.charCodeAt(0); var low = value.charCodeAt(1); return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; }). replace(NON_ALPHANUMERIC_REGEXP, function(value) { return '&#' + value.charCodeAt(0) + ';'; }). replace(//g, '>'); } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.join('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriterImpl(buf, uriValidator) { var ignoreCurrentElement = false; var out = bind(buf, buf.push); return { start: function(tag, attrs) { tag = lowercase(tag); if (!ignoreCurrentElement && blockedElements[tag]) { ignoreCurrentElement = tag; } if (!ignoreCurrentElement && validElements[tag] === true) { out('<'); out(tag); forEach(attrs, function(value, key) { var lkey = lowercase(key); var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); if (validAttrs[lkey] === true && (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out('>'); } }, end: function(tag) { tag = lowercase(tag); if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) { out(''); } // eslint-disable-next-line eqeqeq if (tag == ignoreCurrentElement) { ignoreCurrentElement = false; } }, chars: function(chars) { if (!ignoreCurrentElement) { out(encodeEntities(chars)); } } }; } /** * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare * ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want * to allow any of these custom attributes. This method strips them all. * * @param node Root element to process */ function stripCustomNsAttrs(node) { while (node) { if (node.nodeType === window.Node.ELEMENT_NODE) { var attrs = node.attributes; for (var i = 0, l = attrs.length; i < l; i++) { var attrNode = attrs[i]; var attrName = attrNode.name.toLowerCase(); if (attrName === 'xmlns:ns1' || attrName.lastIndexOf('ns1:', 0) === 0) { node.removeAttributeNode(attrNode); i--; l--; } } } var nextNode = node.firstChild; if (nextNode) { stripCustomNsAttrs(nextNode); } node = getNonDescendant('nextSibling', node); } } function getNonDescendant(propName, node) { // An element is clobbered if its `propName` property points to one of its descendants var nextNode = node[propName]; if (nextNode && nodeContains.call(node, nextNode)) { throw $sanitizeMinErr('elclob', 'Failed to sanitize html because the element is clobbered: {0}', node.outerHTML || node.outerText); } return nextNode; } } function sanitizeText(chars) { var buf = []; var writer = htmlSanitizeWriter(buf, noop); writer.chars(chars); return buf.join(''); } // define ngSanitize module and register $sanitize service angular.module('ngSanitize', []) .provider('$sanitize', $SanitizeProvider) .info({ angularVersion: '1.6.7' }); /** * @ngdoc filter * @name linky * @kind function * * @description * Finds links in text input and turns them into html links. Supports `http/https/ftp/sftp/mailto` and * plain email address links. * * Requires the {@link ngSanitize `ngSanitize`} module to be installed. * * @param {string} text Input text. * @param {string} [target] Window (`_blank|_self|_parent|_top`) or named frame to open links in. * @param {object|function(url)} [attributes] Add custom attributes to the link element. * * Can be one of: * * - `object`: A map of attributes * - `function`: Takes the url as a parameter and returns a map of attributes * * If the map of attributes contains a value for `target`, it overrides the value of * the target parameter. * * * @returns {string} Html-linkified and {@link $sanitize sanitized} text. * * @usage * * @example

Snippet:
Filter Source Rendered
linky filter
<div ng-bind-html="snippet | linky">
</div>
linky target
<div ng-bind-html="snippetWithSingleURL | linky:'_blank'">
</div>
linky custom attributes
<div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}">
</div>
no filter
<div ng-bind="snippet">
</div>
angular.module('linkyExample', ['ngSanitize']) .controller('ExampleController', ['$scope', function($scope) { $scope.snippet = 'Pretty text with some links:\n' + 'http://angularjs.org/,\n' + 'mailto:us@somewhere.org,\n' + 'another@somewhere.org,\n' + 'and one more: ftp://127.0.0.1/.'; $scope.snippetWithSingleURL = 'http://angularjs.org/'; }]); it('should linkify the snippet with urls', function() { expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(4); }); it('should not linkify snippet without the linky filter', function() { expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()). toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#escaped-html a')).count()).toEqual(0); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new http://link.'); expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('new http://link.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(1); expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()) .toBe('new http://link.'); }); it('should work with the target property', function() { expect(element(by.id('linky-target')). element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()). toBe('http://angularjs.org/'); expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank'); }); it('should optionally add custom attributes', function() { expect(element(by.id('linky-custom-attributes')). element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()). toBe('http://angularjs.org/'); expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow'); }); */ angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { var LINKY_URL_REGEXP = /((s?ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i, MAILTO_REGEXP = /^mailto:/i; var linkyMinErr = angular.$$minErr('linky'); var isDefined = angular.isDefined; var isFunction = angular.isFunction; var isObject = angular.isObject; var isString = angular.isString; return function(text, target, attributes) { if (text == null || text === '') return text; if (!isString(text)) throw linkyMinErr('notstring', 'Expected string but received: {0}', text); var attributesFn = isFunction(attributes) ? attributes : isObject(attributes) ? function getAttributesObject() {return attributes;} : function getEmptyAttributesObject() {return {};}; var match; var raw = text; var html = []; var url; var i; while ((match = raw.match(LINKY_URL_REGEXP))) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/www/mailto then assume mailto if (!match[2] && !match[4]) { url = (match[3] ? 'http://' : 'mailto:') + url; } i = match.index; addText(raw.substr(0, i)); addLink(url, match[0].replace(MAILTO_REGEXP, '')); raw = raw.substring(i + match[0].length); } addText(raw); return $sanitize(html.join('')); function addText(text) { if (!text) { return; } html.push(sanitizeText(text)); } function addLink(url, text) { var key, linkAttributes = attributesFn(url); html.push(''); addText(text); html.push(''); } }; }]); })(window, window.angular); /* * angular-ui-bootstrap * http://angular-ui.github.io/bootstrap/ * Version: 2.5.6 - 2017-10-14 * License: MIT */angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.collapse","ui.bootstrap.tabindex","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.isClass","ui.bootstrap.datepicker","ui.bootstrap.position","ui.bootstrap.datepickerPopup","ui.bootstrap.debounce","ui.bootstrap.multiMap","ui.bootstrap.dropdown","ui.bootstrap.stackedMap","ui.bootstrap.modal","ui.bootstrap.paging","ui.bootstrap.pager","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.typeahead"]); angular.module("ui.bootstrap.tpls", ["uib/template/accordion/accordion-group.html","uib/template/accordion/accordion.html","uib/template/alert/alert.html","uib/template/carousel/carousel.html","uib/template/carousel/slide.html","uib/template/datepicker/datepicker.html","uib/template/datepicker/day.html","uib/template/datepicker/month.html","uib/template/datepicker/year.html","uib/template/datepickerPopup/popup.html","uib/template/modal/window.html","uib/template/pager/pager.html","uib/template/pagination/pagination.html","uib/template/tooltip/tooltip-html-popup.html","uib/template/tooltip/tooltip-popup.html","uib/template/tooltip/tooltip-template-popup.html","uib/template/popover/popover-html.html","uib/template/popover/popover-template.html","uib/template/popover/popover.html","uib/template/progressbar/bar.html","uib/template/progressbar/progress.html","uib/template/progressbar/progressbar.html","uib/template/rating/rating.html","uib/template/tabs/tab.html","uib/template/tabs/tabset.html","uib/template/timepicker/timepicker.html","uib/template/typeahead/typeahead-match.html","uib/template/typeahead/typeahead-popup.html"]); angular.module('ui.bootstrap.collapse', []) .directive('uibCollapse', ['$animate', '$q', '$parse', '$injector', function($animate, $q, $parse, $injector) { var $animateCss = $injector.has('$animateCss') ? $injector.get('$animateCss') : null; return { link: function(scope, element, attrs) { var expandingExpr = $parse(attrs.expanding), expandedExpr = $parse(attrs.expanded), collapsingExpr = $parse(attrs.collapsing), collapsedExpr = $parse(attrs.collapsed), horizontal = false, css = {}, cssTo = {}; init(); function init() { horizontal = !!('horizontal' in attrs); if (horizontal) { css = { width: '' }; cssTo = {width: '0'}; } else { css = { height: '' }; cssTo = {height: '0'}; } if (!scope.$eval(attrs.uibCollapse)) { element.addClass('in') .addClass('collapse') .attr('aria-expanded', true) .attr('aria-hidden', false) .css(css); } } function getScrollFromElement(element) { if (horizontal) { return {width: element.scrollWidth + 'px'}; } return {height: element.scrollHeight + 'px'}; } function expand() { if (element.hasClass('collapse') && element.hasClass('in')) { return; } $q.resolve(expandingExpr(scope)) .then(function() { element.removeClass('collapse') .addClass('collapsing') .attr('aria-expanded', true) .attr('aria-hidden', false); if ($animateCss) { $animateCss(element, { addClass: 'in', easing: 'ease', css: { overflow: 'hidden' }, to: getScrollFromElement(element[0]) }).start()['finally'](expandDone); } else { $animate.addClass(element, 'in', { css: { overflow: 'hidden' }, to: getScrollFromElement(element[0]) }).then(expandDone); } }, angular.noop); } function expandDone() { element.removeClass('collapsing') .addClass('collapse') .css(css); expandedExpr(scope); } function collapse() { if (!element.hasClass('collapse') && !element.hasClass('in')) { return collapseDone(); } $q.resolve(collapsingExpr(scope)) .then(function() { element // IMPORTANT: The width must be set before adding "collapsing" class. // Otherwise, the browser attempts to animate from width 0 (in // collapsing class) to the given width here. .css(getScrollFromElement(element[0])) // initially all panel collapse have the collapse class, this removal // prevents the animation from jumping to collapsed state .removeClass('collapse') .addClass('collapsing') .attr('aria-expanded', false) .attr('aria-hidden', true); if ($animateCss) { $animateCss(element, { removeClass: 'in', to: cssTo }).start()['finally'](collapseDone); } else { $animate.removeClass(element, 'in', { to: cssTo }).then(collapseDone); } }, angular.noop); } function collapseDone() { element.css(cssTo); // Required so that collapse works when animation is disabled element.removeClass('collapsing') .addClass('collapse'); collapsedExpr(scope); } scope.$watch(attrs.uibCollapse, function(shouldCollapse) { if (shouldCollapse) { collapse(); } else { expand(); } }); } }; }]); angular.module('ui.bootstrap.tabindex', []) .directive('uibTabindexToggle', function() { return { restrict: 'A', link: function(scope, elem, attrs) { attrs.$observe('disabled', function(disabled) { attrs.$set('tabindex', disabled ? -1 : null); }); } }; }); angular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse', 'ui.bootstrap.tabindex']) .constant('uibAccordionConfig', { closeOthers: true }) .controller('UibAccordionController', ['$scope', '$attrs', 'uibAccordionConfig', function($scope, $attrs, accordionConfig) { // This array keeps track of the accordion groups this.groups = []; // Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to this.closeOthers = function(openGroup) { var closeOthers = angular.isDefined($attrs.closeOthers) ? $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers; if (closeOthers) { angular.forEach(this.groups, function(group) { if (group !== openGroup) { group.isOpen = false; } }); } }; // This is called from the accordion-group directive to add itself to the accordion this.addGroup = function(groupScope) { var that = this; this.groups.push(groupScope); groupScope.$on('$destroy', function(event) { that.removeGroup(groupScope); }); }; // This is called from the accordion-group directive when to remove itself this.removeGroup = function(group) { var index = this.groups.indexOf(group); if (index !== -1) { this.groups.splice(index, 1); } }; }]) // The accordion directive simply sets up the directive controller // and adds an accordion CSS class to itself element. .directive('uibAccordion', function() { return { controller: 'UibAccordionController', controllerAs: 'accordion', transclude: true, templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/accordion/accordion.html'; } }; }) // The accordion-group directive indicates a block of html that will expand and collapse in an accordion .directive('uibAccordionGroup', function() { return { require: '^uibAccordion', // We need this directive to be inside an accordion transclude: true, // It transcludes the contents of the directive into the template restrict: 'A', templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/accordion/accordion-group.html'; }, scope: { heading: '@', // Interpolate the heading attribute onto this scope panelClass: '@?', // Ditto with panelClass isOpen: '=?', isDisabled: '=?' }, controller: function() { this.setHeading = function(element) { this.heading = element; }; }, link: function(scope, element, attrs, accordionCtrl) { element.addClass('panel'); accordionCtrl.addGroup(scope); scope.openClass = attrs.openClass || 'panel-open'; scope.panelClass = attrs.panelClass || 'panel-default'; scope.$watch('isOpen', function(value) { element.toggleClass(scope.openClass, !!value); if (value) { accordionCtrl.closeOthers(scope); } }); scope.toggleOpen = function($event) { if (!scope.isDisabled) { if (!$event || $event.which === 32) { scope.isOpen = !scope.isOpen; } } }; var id = 'accordiongroup-' + scope.$id + '-' + Math.floor(Math.random() * 10000); scope.headingId = id + '-tab'; scope.panelId = id + '-panel'; } }; }) // Use accordion-heading below an accordion-group to provide a heading containing HTML .directive('uibAccordionHeading', function() { return { transclude: true, // Grab the contents to be used as the heading template: '', // In effect remove this element! replace: true, require: '^uibAccordionGroup', link: function(scope, element, attrs, accordionGroupCtrl, transclude) { // Pass the heading to the accordion-group controller // so that it can be transcluded into the right place in the template // [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat] accordionGroupCtrl.setHeading(transclude(scope, angular.noop)); } }; }) // Use in the accordion-group template to indicate where you want the heading to be transcluded // You must provide the property on the accordion-group controller that will hold the transcluded element .directive('uibAccordionTransclude', function() { return { require: '^uibAccordionGroup', link: function(scope, element, attrs, controller) { scope.$watch(function() { return controller[attrs.uibAccordionTransclude]; }, function(heading) { if (heading) { var elem = angular.element(element[0].querySelector(getHeaderSelectors())); elem.html(''); elem.append(heading); } }); } }; function getHeaderSelectors() { return 'uib-accordion-header,' + 'data-uib-accordion-header,' + 'x-uib-accordion-header,' + 'uib\\:accordion-header,' + '[uib-accordion-header],' + '[data-uib-accordion-header],' + '[x-uib-accordion-header]'; } }); angular.module('ui.bootstrap.alert', []) .controller('UibAlertController', ['$scope', '$element', '$attrs', '$interpolate', '$timeout', function($scope, $element, $attrs, $interpolate, $timeout) { $scope.closeable = !!$attrs.close; $element.addClass('alert'); $attrs.$set('role', 'alert'); if ($scope.closeable) { $element.addClass('alert-dismissible'); } var dismissOnTimeout = angular.isDefined($attrs.dismissOnTimeout) ? $interpolate($attrs.dismissOnTimeout)($scope.$parent) : null; if (dismissOnTimeout) { $timeout(function() { $scope.close(); }, parseInt(dismissOnTimeout, 10)); } }]) .directive('uibAlert', function() { return { controller: 'UibAlertController', controllerAs: 'alert', restrict: 'A', templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/alert/alert.html'; }, transclude: true, scope: { close: '&' } }; }); angular.module('ui.bootstrap.buttons', []) .constant('uibButtonConfig', { activeClass: 'active', toggleEvent: 'click' }) .controller('UibButtonsController', ['uibButtonConfig', function(buttonConfig) { this.activeClass = buttonConfig.activeClass || 'active'; this.toggleEvent = buttonConfig.toggleEvent || 'click'; }]) .directive('uibBtnRadio', ['$parse', function($parse) { return { require: ['uibBtnRadio', 'ngModel'], controller: 'UibButtonsController', controllerAs: 'buttons', link: function(scope, element, attrs, ctrls) { var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; var uncheckableExpr = $parse(attrs.uibUncheckable); element.find('input').css({display: 'none'}); //model -> UI ngModelCtrl.$render = function() { element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.uibBtnRadio))); }; //ui->model element.on(buttonsCtrl.toggleEvent, function() { if (attrs.disabled) { return; } var isActive = element.hasClass(buttonsCtrl.activeClass); if (!isActive || angular.isDefined(attrs.uncheckable)) { scope.$apply(function() { ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.uibBtnRadio)); ngModelCtrl.$render(); }); } }); if (attrs.uibUncheckable) { scope.$watch(uncheckableExpr, function(uncheckable) { attrs.$set('uncheckable', uncheckable ? '' : undefined); }); } } }; }]) .directive('uibBtnCheckbox', function() { return { require: ['uibBtnCheckbox', 'ngModel'], controller: 'UibButtonsController', controllerAs: 'button', link: function(scope, element, attrs, ctrls) { var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; element.find('input').css({display: 'none'}); function getTrueValue() { return getCheckboxValue(attrs.btnCheckboxTrue, true); } function getFalseValue() { return getCheckboxValue(attrs.btnCheckboxFalse, false); } function getCheckboxValue(attribute, defaultValue) { return angular.isDefined(attribute) ? scope.$eval(attribute) : defaultValue; } //model -> UI ngModelCtrl.$render = function() { element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue())); }; //ui->model element.on(buttonsCtrl.toggleEvent, function() { if (attrs.disabled) { return; } scope.$apply(function() { ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue()); ngModelCtrl.$render(); }); }); } }; }); angular.module('ui.bootstrap.carousel', []) .controller('UibCarouselController', ['$scope', '$element', '$interval', '$timeout', '$animate', function($scope, $element, $interval, $timeout, $animate) { var self = this, slides = self.slides = $scope.slides = [], SLIDE_DIRECTION = 'uib-slideDirection', currentIndex = $scope.active, currentInterval, isPlaying; var destroyed = false; $element.addClass('carousel'); self.addSlide = function(slide, element) { slides.push({ slide: slide, element: element }); slides.sort(function(a, b) { return +a.slide.index - +b.slide.index; }); //if this is the first slide or the slide is set to active, select it if (slide.index === $scope.active || slides.length === 1 && !angular.isNumber($scope.active)) { if ($scope.$currentTransition) { $scope.$currentTransition = null; } currentIndex = slide.index; $scope.active = slide.index; setActive(currentIndex); self.select(slides[findSlideIndex(slide)]); if (slides.length === 1) { $scope.play(); } } }; self.getCurrentIndex = function() { for (var i = 0; i < slides.length; i++) { if (slides[i].slide.index === currentIndex) { return i; } } }; self.next = $scope.next = function() { var newIndex = (self.getCurrentIndex() + 1) % slides.length; if (newIndex === 0 && $scope.noWrap()) { $scope.pause(); return; } return self.select(slides[newIndex], 'next'); }; self.prev = $scope.prev = function() { var newIndex = self.getCurrentIndex() - 1 < 0 ? slides.length - 1 : self.getCurrentIndex() - 1; if ($scope.noWrap() && newIndex === slides.length - 1) { $scope.pause(); return; } return self.select(slides[newIndex], 'prev'); }; self.removeSlide = function(slide) { var index = findSlideIndex(slide); //get the index of the slide inside the carousel slides.splice(index, 1); if (slides.length > 0 && currentIndex === index) { if (index >= slides.length) { currentIndex = slides.length - 1; $scope.active = currentIndex; setActive(currentIndex); self.select(slides[slides.length - 1]); } else { currentIndex = index; $scope.active = currentIndex; setActive(currentIndex); self.select(slides[index]); } } else if (currentIndex > index) { currentIndex--; $scope.active = currentIndex; } //clean the active value when no more slide if (slides.length === 0) { currentIndex = null; $scope.active = null; } }; /* direction: "prev" or "next" */ self.select = $scope.select = function(nextSlide, direction) { var nextIndex = findSlideIndex(nextSlide.slide); //Decide direction if it's not given if (direction === undefined) { direction = nextIndex > self.getCurrentIndex() ? 'next' : 'prev'; } //Prevent this user-triggered transition from occurring if there is already one in progress if (nextSlide.slide.index !== currentIndex && !$scope.$currentTransition) { goNext(nextSlide.slide, nextIndex, direction); } }; /* Allow outside people to call indexOf on slides array */ $scope.indexOfSlide = function(slide) { return +slide.slide.index; }; $scope.isActive = function(slide) { return $scope.active === slide.slide.index; }; $scope.isPrevDisabled = function() { return $scope.active === 0 && $scope.noWrap(); }; $scope.isNextDisabled = function() { return $scope.active === slides.length - 1 && $scope.noWrap(); }; $scope.pause = function() { if (!$scope.noPause) { isPlaying = false; resetTimer(); } }; $scope.play = function() { if (!isPlaying) { isPlaying = true; restartTimer(); } }; $element.on('mouseenter', $scope.pause); $element.on('mouseleave', $scope.play); $scope.$on('$destroy', function() { destroyed = true; resetTimer(); }); $scope.$watch('noTransition', function(noTransition) { $animate.enabled($element, !noTransition); }); $scope.$watch('interval', restartTimer); $scope.$watchCollection('slides', resetTransition); $scope.$watch('active', function(index) { if (angular.isNumber(index) && currentIndex !== index) { for (var i = 0; i < slides.length; i++) { if (slides[i].slide.index === index) { index = i; break; } } var slide = slides[index]; if (slide) { setActive(index); self.select(slides[index]); currentIndex = index; } } }); function getSlideByIndex(index) { for (var i = 0, l = slides.length; i < l; ++i) { if (slides[i].index === index) { return slides[i]; } } } function setActive(index) { for (var i = 0; i < slides.length; i++) { slides[i].slide.active = i === index; } } function goNext(slide, index, direction) { if (destroyed) { return; } angular.extend(slide, {direction: direction}); angular.extend(slides[currentIndex].slide || {}, {direction: direction}); if ($animate.enabled($element) && !$scope.$currentTransition && slides[index].element && self.slides.length > 1) { slides[index].element.data(SLIDE_DIRECTION, slide.direction); var currentIdx = self.getCurrentIndex(); if (angular.isNumber(currentIdx) && slides[currentIdx].element) { slides[currentIdx].element.data(SLIDE_DIRECTION, slide.direction); } $scope.$currentTransition = true; $animate.on('addClass', slides[index].element, function(element, phase) { if (phase === 'close') { $scope.$currentTransition = null; $animate.off('addClass', element); } }); } $scope.active = slide.index; currentIndex = slide.index; setActive(index); //every time you change slides, reset the timer restartTimer(); } function findSlideIndex(slide) { for (var i = 0; i < slides.length; i++) { if (slides[i].slide === slide) { return i; } } } function resetTimer() { if (currentInterval) { $interval.cancel(currentInterval); currentInterval = null; } } function resetTransition(slides) { if (!slides.length) { $scope.$currentTransition = null; } } function restartTimer() { resetTimer(); var interval = +$scope.interval; if (!isNaN(interval) && interval > 0) { currentInterval = $interval(timerFn, interval); } } function timerFn() { var interval = +$scope.interval; if (isPlaying && !isNaN(interval) && interval > 0 && slides.length) { $scope.next(); } else { $scope.pause(); } } }]) .directive('uibCarousel', function() { return { transclude: true, controller: 'UibCarouselController', controllerAs: 'carousel', restrict: 'A', templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/carousel/carousel.html'; }, scope: { active: '=', interval: '=', noTransition: '=', noPause: '=', noWrap: '&' } }; }) .directive('uibSlide', ['$animate', function($animate) { return { require: '^uibCarousel', restrict: 'A', transclude: true, templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/carousel/slide.html'; }, scope: { actual: '=?', index: '=?' }, link: function (scope, element, attrs, carouselCtrl) { element.addClass('item'); carouselCtrl.addSlide(scope, element); //when the scope is destroyed then remove the slide from the current slides array scope.$on('$destroy', function() { carouselCtrl.removeSlide(scope); }); scope.$watch('active', function(active) { $animate[active ? 'addClass' : 'removeClass'](element, 'active'); }); } }; }]) .animation('.item', ['$animateCss', function($animateCss) { var SLIDE_DIRECTION = 'uib-slideDirection'; function removeClass(element, className, callback) { element.removeClass(className); if (callback) { callback(); } } return { beforeAddClass: function(element, className, done) { if (className === 'active') { var stopped = false; var direction = element.data(SLIDE_DIRECTION); var directionClass = direction === 'next' ? 'left' : 'right'; var removeClassFn = removeClass.bind(this, element, directionClass + ' ' + direction, done); element.addClass(direction); $animateCss(element, {addClass: directionClass}) .start() .done(removeClassFn); return function() { stopped = true; }; } done(); }, beforeRemoveClass: function (element, className, done) { if (className === 'active') { var stopped = false; var direction = element.data(SLIDE_DIRECTION); var directionClass = direction === 'next' ? 'left' : 'right'; var removeClassFn = removeClass.bind(this, element, directionClass, done); $animateCss(element, {addClass: directionClass}) .start() .done(removeClassFn); return function() { stopped = true; }; } done(); } }; }]); angular.module('ui.bootstrap.dateparser', []) .service('uibDateParser', ['$log', '$locale', 'dateFilter', 'orderByFilter', 'filterFilter', function($log, $locale, dateFilter, orderByFilter, filterFilter) { // Pulled from https://github.com/mbostock/d3/blob/master/src/format/requote.js var SPECIAL_CHARACTERS_REGEXP = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; var localeId; var formatCodeToRegex; this.init = function() { localeId = $locale.id; this.parsers = {}; this.formatters = {}; formatCodeToRegex = [ { key: 'yyyy', regex: '\\d{4}', apply: function(value) { this.year = +value; }, formatter: function(date) { var _date = new Date(); _date.setFullYear(Math.abs(date.getFullYear())); return dateFilter(_date, 'yyyy'); } }, { key: 'yy', regex: '\\d{2}', apply: function(value) { value = +value; this.year = value < 69 ? value + 2000 : value + 1900; }, formatter: function(date) { var _date = new Date(); _date.setFullYear(Math.abs(date.getFullYear())); return dateFilter(_date, 'yy'); } }, { key: 'y', regex: '\\d{1,4}', apply: function(value) { this.year = +value; }, formatter: function(date) { var _date = new Date(); _date.setFullYear(Math.abs(date.getFullYear())); return dateFilter(_date, 'y'); } }, { key: 'M!', regex: '0?[1-9]|1[0-2]', apply: function(value) { this.month = value - 1; }, formatter: function(date) { var value = date.getMonth(); if (/^[0-9]$/.test(value)) { return dateFilter(date, 'MM'); } return dateFilter(date, 'M'); } }, { key: 'MMMM', regex: $locale.DATETIME_FORMATS.MONTH.join('|'), apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); }, formatter: function(date) { return dateFilter(date, 'MMMM'); } }, { key: 'MMM', regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'), apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); }, formatter: function(date) { return dateFilter(date, 'MMM'); } }, { key: 'MM', regex: '0[1-9]|1[0-2]', apply: function(value) { this.month = value - 1; }, formatter: function(date) { return dateFilter(date, 'MM'); } }, { key: 'M', regex: '[1-9]|1[0-2]', apply: function(value) { this.month = value - 1; }, formatter: function(date) { return dateFilter(date, 'M'); } }, { key: 'd!', regex: '[0-2]?[0-9]{1}|3[0-1]{1}', apply: function(value) { this.date = +value; }, formatter: function(date) { var value = date.getDate(); if (/^[1-9]$/.test(value)) { return dateFilter(date, 'dd'); } return dateFilter(date, 'd'); } }, { key: 'dd', regex: '[0-2][0-9]{1}|3[0-1]{1}', apply: function(value) { this.date = +value; }, formatter: function(date) { return dateFilter(date, 'dd'); } }, { key: 'd', regex: '[1-2]?[0-9]{1}|3[0-1]{1}', apply: function(value) { this.date = +value; }, formatter: function(date) { return dateFilter(date, 'd'); } }, { key: 'EEEE', regex: $locale.DATETIME_FORMATS.DAY.join('|'), formatter: function(date) { return dateFilter(date, 'EEEE'); } }, { key: 'EEE', regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|'), formatter: function(date) { return dateFilter(date, 'EEE'); } }, { key: 'HH', regex: '(?:0|1)[0-9]|2[0-3]', apply: function(value) { this.hours = +value; }, formatter: function(date) { return dateFilter(date, 'HH'); } }, { key: 'hh', regex: '0[0-9]|1[0-2]', apply: function(value) { this.hours = +value; }, formatter: function(date) { return dateFilter(date, 'hh'); } }, { key: 'H', regex: '1?[0-9]|2[0-3]', apply: function(value) { this.hours = +value; }, formatter: function(date) { return dateFilter(date, 'H'); } }, { key: 'h', regex: '[0-9]|1[0-2]', apply: function(value) { this.hours = +value; }, formatter: function(date) { return dateFilter(date, 'h'); } }, { key: 'mm', regex: '[0-5][0-9]', apply: function(value) { this.minutes = +value; }, formatter: function(date) { return dateFilter(date, 'mm'); } }, { key: 'm', regex: '[0-9]|[1-5][0-9]', apply: function(value) { this.minutes = +value; }, formatter: function(date) { return dateFilter(date, 'm'); } }, { key: 'sss', regex: '[0-9][0-9][0-9]', apply: function(value) { this.milliseconds = +value; }, formatter: function(date) { return dateFilter(date, 'sss'); } }, { key: 'ss', regex: '[0-5][0-9]', apply: function(value) { this.seconds = +value; }, formatter: function(date) { return dateFilter(date, 'ss'); } }, { key: 's', regex: '[0-9]|[1-5][0-9]', apply: function(value) { this.seconds = +value; }, formatter: function(date) { return dateFilter(date, 's'); } }, { key: 'a', regex: $locale.DATETIME_FORMATS.AMPMS.join('|'), apply: function(value) { if (this.hours === 12) { this.hours = 0; } if (value === 'PM') { this.hours += 12; } }, formatter: function(date) { return dateFilter(date, 'a'); } }, { key: 'Z', regex: '[+-]\\d{4}', apply: function(value) { var matches = value.match(/([+-])(\d{2})(\d{2})/), sign = matches[1], hours = matches[2], minutes = matches[3]; this.hours += toInt(sign + hours); this.minutes += toInt(sign + minutes); }, formatter: function(date) { return dateFilter(date, 'Z'); } }, { key: 'ww', regex: '[0-4][0-9]|5[0-3]', formatter: function(date) { return dateFilter(date, 'ww'); } }, { key: 'w', regex: '[0-9]|[1-4][0-9]|5[0-3]', formatter: function(date) { return dateFilter(date, 'w'); } }, { key: 'GGGG', regex: $locale.DATETIME_FORMATS.ERANAMES.join('|').replace(/\s/g, '\\s'), formatter: function(date) { return dateFilter(date, 'GGGG'); } }, { key: 'GGG', regex: $locale.DATETIME_FORMATS.ERAS.join('|'), formatter: function(date) { return dateFilter(date, 'GGG'); } }, { key: 'GG', regex: $locale.DATETIME_FORMATS.ERAS.join('|'), formatter: function(date) { return dateFilter(date, 'GG'); } }, { key: 'G', regex: $locale.DATETIME_FORMATS.ERAS.join('|'), formatter: function(date) { return dateFilter(date, 'G'); } } ]; if (angular.version.major >= 1 && angular.version.minor > 4) { formatCodeToRegex.push({ key: 'LLLL', regex: $locale.DATETIME_FORMATS.STANDALONEMONTH.join('|'), apply: function(value) { this.month = $locale.DATETIME_FORMATS.STANDALONEMONTH.indexOf(value); }, formatter: function(date) { return dateFilter(date, 'LLLL'); } }); } }; this.init(); function getFormatCodeToRegex(key) { return filterFilter(formatCodeToRegex, {key: key}, true)[0]; } this.getParser = function (key) { var f = getFormatCodeToRegex(key); return f && f.apply || null; }; this.overrideParser = function (key, parser) { var f = getFormatCodeToRegex(key); if (f && angular.isFunction(parser)) { this.parsers = {}; f.apply = parser; } }.bind(this); function createParser(format) { var map = [], regex = format.split(''); // check for literal values var quoteIndex = format.indexOf('\''); if (quoteIndex > -1) { var inLiteral = false; format = format.split(''); for (var i = quoteIndex; i < format.length; i++) { if (inLiteral) { if (format[i] === '\'') { if (i + 1 < format.length && format[i+1] === '\'') { // escaped single quote format[i+1] = '$'; regex[i+1] = ''; } else { // end of literal regex[i] = ''; inLiteral = false; } } format[i] = '$'; } else { if (format[i] === '\'') { // start of literal format[i] = '$'; regex[i] = ''; inLiteral = true; } } } format = format.join(''); } angular.forEach(formatCodeToRegex, function(data) { var index = format.indexOf(data.key); if (index > -1) { format = format.split(''); regex[index] = '(' + data.regex + ')'; format[index] = '$'; // Custom symbol to define consumed part of format for (var i = index + 1, n = index + data.key.length; i < n; i++) { regex[i] = ''; format[i] = '$'; } format = format.join(''); map.push({ index: index, key: data.key, apply: data.apply, matcher: data.regex }); } }); return { regex: new RegExp('^' + regex.join('') + '$'), map: orderByFilter(map, 'index') }; } function createFormatter(format) { var formatters = []; var i = 0; var formatter, literalIdx; while (i < format.length) { if (angular.isNumber(literalIdx)) { if (format.charAt(i) === '\'') { if (i + 1 >= format.length || format.charAt(i + 1) !== '\'') { formatters.push(constructLiteralFormatter(format, literalIdx, i)); literalIdx = null; } } else if (i === format.length) { while (literalIdx < format.length) { formatter = constructFormatterFromIdx(format, literalIdx); formatters.push(formatter); literalIdx = formatter.endIdx; } } i++; continue; } if (format.charAt(i) === '\'') { literalIdx = i; i++; continue; } formatter = constructFormatterFromIdx(format, i); formatters.push(formatter.parser); i = formatter.endIdx; } return formatters; } function constructLiteralFormatter(format, literalIdx, endIdx) { return function() { return format.substr(literalIdx + 1, endIdx - literalIdx - 1); }; } function constructFormatterFromIdx(format, i) { var currentPosStr = format.substr(i); for (var j = 0; j < formatCodeToRegex.length; j++) { if (new RegExp('^' + formatCodeToRegex[j].key).test(currentPosStr)) { var data = formatCodeToRegex[j]; return { endIdx: i + data.key.length, parser: data.formatter }; } } return { endIdx: i + 1, parser: function() { return currentPosStr.charAt(0); } }; } this.filter = function(date, format) { if (!angular.isDate(date) || isNaN(date) || !format) { return ''; } format = $locale.DATETIME_FORMATS[format] || format; if ($locale.id !== localeId) { this.init(); } if (!this.formatters[format]) { this.formatters[format] = createFormatter(format); } var formatters = this.formatters[format]; return formatters.reduce(function(str, formatter) { return str + formatter(date); }, ''); }; this.parse = function(input, format, baseDate) { if (!angular.isString(input) || !format) { return input; } format = $locale.DATETIME_FORMATS[format] || format; format = format.replace(SPECIAL_CHARACTERS_REGEXP, '\\$&'); if ($locale.id !== localeId) { this.init(); } if (!this.parsers[format]) { this.parsers[format] = createParser(format, 'apply'); } var parser = this.parsers[format], regex = parser.regex, map = parser.map, results = input.match(regex), tzOffset = false; if (results && results.length) { var fields, dt; if (angular.isDate(baseDate) && !isNaN(baseDate.getTime())) { fields = { year: baseDate.getFullYear(), month: baseDate.getMonth(), date: baseDate.getDate(), hours: baseDate.getHours(), minutes: baseDate.getMinutes(), seconds: baseDate.getSeconds(), milliseconds: baseDate.getMilliseconds() }; } else { if (baseDate) { $log.warn('dateparser:', 'baseDate is not a valid date'); } fields = { year: 1900, month: 0, date: 1, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 }; } for (var i = 1, n = results.length; i < n; i++) { var mapper = map[i - 1]; if (mapper.matcher === 'Z') { tzOffset = true; } if (mapper.apply) { mapper.apply.call(fields, results[i]); } } var datesetter = tzOffset ? Date.prototype.setUTCFullYear : Date.prototype.setFullYear; var timesetter = tzOffset ? Date.prototype.setUTCHours : Date.prototype.setHours; if (isValid(fields.year, fields.month, fields.date)) { if (angular.isDate(baseDate) && !isNaN(baseDate.getTime()) && !tzOffset) { dt = new Date(baseDate); datesetter.call(dt, fields.year, fields.month, fields.date); timesetter.call(dt, fields.hours, fields.minutes, fields.seconds, fields.milliseconds); } else { dt = new Date(0); datesetter.call(dt, fields.year, fields.month, fields.date); timesetter.call(dt, fields.hours || 0, fields.minutes || 0, fields.seconds || 0, fields.milliseconds || 0); } } return dt; } }; // Check if date is valid for specific month (and year for February). // Month: 0 = Jan, 1 = Feb, etc function isValid(year, month, date) { if (date < 1) { return false; } if (month === 1 && date > 28) { return date === 29 && (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0); } if (month === 3 || month === 5 || month === 8 || month === 10) { return date < 31; } return true; } function toInt(str) { return parseInt(str, 10); } this.toTimezone = toTimezone; this.fromTimezone = fromTimezone; this.timezoneToOffset = timezoneToOffset; this.addDateMinutes = addDateMinutes; this.convertTimezoneToLocal = convertTimezoneToLocal; function toTimezone(date, timezone) { return date && timezone ? convertTimezoneToLocal(date, timezone) : date; } function fromTimezone(date, timezone) { return date && timezone ? convertTimezoneToLocal(date, timezone, true) : date; } //https://github.com/angular/angular.js/blob/622c42169699ec07fc6daaa19fe6d224e5d2f70e/src/Angular.js#L1207 function timezoneToOffset(timezone, fallback) { timezone = timezone.replace(/:/g, ''); var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000; return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset; } function addDateMinutes(date, minutes) { date = new Date(date.getTime()); date.setMinutes(date.getMinutes() + minutes); return date; } function convertTimezoneToLocal(date, timezone, reverse) { reverse = reverse ? -1 : 1; var dateTimezoneOffset = date.getTimezoneOffset(); var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset)); } }]); // Avoiding use of ng-class as it creates a lot of watchers when a class is to be applied to // at most one element. angular.module('ui.bootstrap.isClass', []) .directive('uibIsClass', [ '$animate', function ($animate) { // 11111111 22222222 var ON_REGEXP = /^\s*([\s\S]+?)\s+on\s+([\s\S]+?)\s*$/; // 11111111 22222222 var IS_REGEXP = /^\s*([\s\S]+?)\s+for\s+([\s\S]+?)\s*$/; var dataPerTracked = {}; return { restrict: 'A', compile: function(tElement, tAttrs) { var linkedScopes = []; var instances = []; var expToData = {}; var lastActivated = null; var onExpMatches = tAttrs.uibIsClass.match(ON_REGEXP); var onExp = onExpMatches[2]; var expsStr = onExpMatches[1]; var exps = expsStr.split(','); return linkFn; function linkFn(scope, element, attrs) { linkedScopes.push(scope); instances.push({ scope: scope, element: element }); exps.forEach(function(exp, k) { addForExp(exp, scope); }); scope.$on('$destroy', removeScope); } function addForExp(exp, scope) { var matches = exp.match(IS_REGEXP); var clazz = scope.$eval(matches[1]); var compareWithExp = matches[2]; var data = expToData[exp]; if (!data) { var watchFn = function(compareWithVal) { var newActivated = null; instances.some(function(instance) { var thisVal = instance.scope.$eval(onExp); if (thisVal === compareWithVal) { newActivated = instance; return true; } }); if (data.lastActivated !== newActivated) { if (data.lastActivated) { $animate.removeClass(data.lastActivated.element, clazz); } if (newActivated) { $animate.addClass(newActivated.element, clazz); } data.lastActivated = newActivated; } }; expToData[exp] = data = { lastActivated: null, scope: scope, watchFn: watchFn, compareWithExp: compareWithExp, watcher: scope.$watch(compareWithExp, watchFn) }; } data.watchFn(scope.$eval(compareWithExp)); } function removeScope(e) { var removedScope = e.targetScope; var index = linkedScopes.indexOf(removedScope); linkedScopes.splice(index, 1); instances.splice(index, 1); if (linkedScopes.length) { var newWatchScope = linkedScopes[0]; angular.forEach(expToData, function(data) { if (data.scope === removedScope) { data.watcher = newWatchScope.$watch(data.compareWithExp, data.watchFn); data.scope = newWatchScope; } }); } else { expToData = {}; } } } }; }]); angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.isClass']) .value('$datepickerSuppressError', false) .value('$datepickerLiteralWarning', true) .constant('uibDatepickerConfig', { datepickerMode: 'day', formatDay: 'dd', formatMonth: 'MMMM', formatYear: 'yyyy', formatDayHeader: 'EEE', formatDayTitle: 'MMMM yyyy', formatMonthTitle: 'yyyy', maxDate: null, maxMode: 'year', minDate: null, minMode: 'day', monthColumns: 3, ngModelOptions: {}, shortcutPropagation: false, showWeeks: true, yearColumns: 5, yearRows: 4 }) .controller('UibDatepickerController', ['$scope', '$element', '$attrs', '$parse', '$interpolate', '$locale', '$log', 'dateFilter', 'uibDatepickerConfig', '$datepickerLiteralWarning', '$datepickerSuppressError', 'uibDateParser', function($scope, $element, $attrs, $parse, $interpolate, $locale, $log, dateFilter, datepickerConfig, $datepickerLiteralWarning, $datepickerSuppressError, dateParser) { var self = this, ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl; ngModelOptions = {}, watchListeners = []; $element.addClass('uib-datepicker'); $attrs.$set('role', 'application'); if (!$scope.datepickerOptions) { $scope.datepickerOptions = {}; } // Modes chain this.modes = ['day', 'month', 'year']; [ 'customClass', 'dateDisabled', 'datepickerMode', 'formatDay', 'formatDayHeader', 'formatDayTitle', 'formatMonth', 'formatMonthTitle', 'formatYear', 'maxDate', 'maxMode', 'minDate', 'minMode', 'monthColumns', 'showWeeks', 'shortcutPropagation', 'startingDay', 'yearColumns', 'yearRows' ].forEach(function(key) { switch (key) { case 'customClass': case 'dateDisabled': $scope[key] = $scope.datepickerOptions[key] || angular.noop; break; case 'datepickerMode': $scope.datepickerMode = angular.isDefined($scope.datepickerOptions.datepickerMode) ? $scope.datepickerOptions.datepickerMode : datepickerConfig.datepickerMode; break; case 'formatDay': case 'formatDayHeader': case 'formatDayTitle': case 'formatMonth': case 'formatMonthTitle': case 'formatYear': self[key] = angular.isDefined($scope.datepickerOptions[key]) ? $interpolate($scope.datepickerOptions[key])($scope.$parent) : datepickerConfig[key]; break; case 'monthColumns': case 'showWeeks': case 'shortcutPropagation': case 'yearColumns': case 'yearRows': self[key] = angular.isDefined($scope.datepickerOptions[key]) ? $scope.datepickerOptions[key] : datepickerConfig[key]; break; case 'startingDay': if (angular.isDefined($scope.datepickerOptions.startingDay)) { self.startingDay = $scope.datepickerOptions.startingDay; } else if (angular.isNumber(datepickerConfig.startingDay)) { self.startingDay = datepickerConfig.startingDay; } else { self.startingDay = ($locale.DATETIME_FORMATS.FIRSTDAYOFWEEK + 8) % 7; } break; case 'maxDate': case 'minDate': $scope.$watch('datepickerOptions.' + key, function(value) { if (value) { if (angular.isDate(value)) { self[key] = dateParser.fromTimezone(new Date(value), ngModelOptions.getOption('timezone')); } else { if ($datepickerLiteralWarning) { $log.warn('Literal date support has been deprecated, please switch to date object usage'); } self[key] = new Date(dateFilter(value, 'medium')); } } else { self[key] = datepickerConfig[key] ? dateParser.fromTimezone(new Date(datepickerConfig[key]), ngModelOptions.getOption('timezone')) : null; } self.refreshView(); }); break; case 'maxMode': case 'minMode': if ($scope.datepickerOptions[key]) { $scope.$watch(function() { return $scope.datepickerOptions[key]; }, function(value) { self[key] = $scope[key] = angular.isDefined(value) ? value : $scope.datepickerOptions[key]; if (key === 'minMode' && self.modes.indexOf($scope.datepickerOptions.datepickerMode) < self.modes.indexOf(self[key]) || key === 'maxMode' && self.modes.indexOf($scope.datepickerOptions.datepickerMode) > self.modes.indexOf(self[key])) { $scope.datepickerMode = self[key]; $scope.datepickerOptions.datepickerMode = self[key]; } }); } else { self[key] = $scope[key] = datepickerConfig[key] || null; } break; } }); $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000); $scope.disabled = angular.isDefined($attrs.disabled) || false; if (angular.isDefined($attrs.ngDisabled)) { watchListeners.push($scope.$parent.$watch($attrs.ngDisabled, function(disabled) { $scope.disabled = disabled; self.refreshView(); })); } $scope.isActive = function(dateObject) { if (self.compare(dateObject.date, self.activeDate) === 0) { $scope.activeDateId = dateObject.uid; return true; } return false; }; this.init = function(ngModelCtrl_) { ngModelCtrl = ngModelCtrl_; ngModelOptions = extractOptions(ngModelCtrl); if ($scope.datepickerOptions.initDate) { self.activeDate = dateParser.fromTimezone($scope.datepickerOptions.initDate, ngModelOptions.getOption('timezone')) || new Date(); $scope.$watch('datepickerOptions.initDate', function(initDate) { if (initDate && (ngModelCtrl.$isEmpty(ngModelCtrl.$modelValue) || ngModelCtrl.$invalid)) { self.activeDate = dateParser.fromTimezone(initDate, ngModelOptions.getOption('timezone')); self.refreshView(); } }); } else { self.activeDate = new Date(); } var date = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : new Date(); this.activeDate = !isNaN(date) ? dateParser.fromTimezone(date, ngModelOptions.getOption('timezone')) : dateParser.fromTimezone(new Date(), ngModelOptions.getOption('timezone')); ngModelCtrl.$render = function() { self.render(); }; }; this.render = function() { if (ngModelCtrl.$viewValue) { var date = new Date(ngModelCtrl.$viewValue), isValid = !isNaN(date); if (isValid) { this.activeDate = dateParser.fromTimezone(date, ngModelOptions.getOption('timezone')); } else if (!$datepickerSuppressError) { $log.error('Datepicker directive: "ng-model" value must be a Date object'); } } this.refreshView(); }; this.refreshView = function() { if (this.element) { $scope.selectedDt = null; this._refreshView(); if ($scope.activeDt) { $scope.activeDateId = $scope.activeDt.uid; } var date = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null; date = dateParser.fromTimezone(date, ngModelOptions.getOption('timezone')); ngModelCtrl.$setValidity('dateDisabled', !date || this.element && !this.isDisabled(date)); } }; this.createDateObject = function(date, format) { var model = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null; model = dateParser.fromTimezone(model, ngModelOptions.getOption('timezone')); var today = new Date(); today = dateParser.fromTimezone(today, ngModelOptions.getOption('timezone')); var time = this.compare(date, today); var dt = { date: date, label: dateParser.filter(date, format), selected: model && this.compare(date, model) === 0, disabled: this.isDisabled(date), past: time < 0, current: time === 0, future: time > 0, customClass: this.customClass(date) || null }; if (model && this.compare(date, model) === 0) { $scope.selectedDt = dt; } if (self.activeDate && this.compare(dt.date, self.activeDate) === 0) { $scope.activeDt = dt; } return dt; }; this.isDisabled = function(date) { return $scope.disabled || this.minDate && this.compare(date, this.minDate) < 0 || this.maxDate && this.compare(date, this.maxDate) > 0 || $scope.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode}); }; this.customClass = function(date) { return $scope.customClass({date: date, mode: $scope.datepickerMode}); }; // Split array into smaller arrays this.split = function(arr, size) { var arrays = []; while (arr.length > 0) { arrays.push(arr.splice(0, size)); } return arrays; }; $scope.select = function(date) { if ($scope.datepickerMode === self.minMode) { var dt = ngModelCtrl.$viewValue ? dateParser.fromTimezone(new Date(ngModelCtrl.$viewValue), ngModelOptions.getOption('timezone')) : new Date(0, 0, 0, 0, 0, 0, 0); dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); dt = dateParser.toTimezone(dt, ngModelOptions.getOption('timezone')); ngModelCtrl.$setViewValue(dt); ngModelCtrl.$render(); } else { self.activeDate = date; setMode(self.modes[self.modes.indexOf($scope.datepickerMode) - 1]); $scope.$emit('uib:datepicker.mode'); } $scope.$broadcast('uib:datepicker.focus'); }; $scope.move = function(direction) { var year = self.activeDate.getFullYear() + direction * (self.step.years || 0), month = self.activeDate.getMonth() + direction * (self.step.months || 0); self.activeDate.setFullYear(year, month, 1); self.refreshView(); }; $scope.toggleMode = function(direction) { direction = direction || 1; if ($scope.datepickerMode === self.maxMode && direction === 1 || $scope.datepickerMode === self.minMode && direction === -1) { return; } setMode(self.modes[self.modes.indexOf($scope.datepickerMode) + direction]); $scope.$emit('uib:datepicker.mode'); }; // Key event mapper $scope.keys = { 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; var focusElement = function() { self.element[0].focus(); }; // Listen for focus requests from popup directive $scope.$on('uib:datepicker.focus', focusElement); $scope.keydown = function(evt) { var key = $scope.keys[evt.which]; if (!key || evt.shiftKey || evt.altKey || $scope.disabled) { return; } evt.preventDefault(); if (!self.shortcutPropagation) { evt.stopPropagation(); } if (key === 'enter' || key === 'space') { if (self.isDisabled(self.activeDate)) { return; // do nothing } $scope.select(self.activeDate); } else if (evt.ctrlKey && (key === 'up' || key === 'down')) { $scope.toggleMode(key === 'up' ? 1 : -1); } else { self.handleKeyDown(key, evt); self.refreshView(); } }; $element.on('keydown', function(evt) { $scope.$apply(function() { $scope.keydown(evt); }); }); $scope.$on('$destroy', function() { //Clear all watch listeners on destroy while (watchListeners.length) { watchListeners.shift()(); } }); function setMode(mode) { $scope.datepickerMode = mode; $scope.datepickerOptions.datepickerMode = mode; } function extractOptions(ngModelCtrl) { var ngModelOptions; if (angular.version.minor < 6) { // in angular < 1.6 $options could be missing // guarantee a value ngModelOptions = ngModelCtrl.$options || $scope.datepickerOptions.ngModelOptions || datepickerConfig.ngModelOptions || {}; // mimic 1.6+ api ngModelOptions.getOption = function (key) { return ngModelOptions[key]; }; } else { // in angular >=1.6 $options is always present // ng-model-options defaults timezone to null; don't let its precedence squash a non-null value var timezone = ngModelCtrl.$options.getOption('timezone') || ($scope.datepickerOptions.ngModelOptions ? $scope.datepickerOptions.ngModelOptions.timezone : null) || (datepickerConfig.ngModelOptions ? datepickerConfig.ngModelOptions.timezone : null); // values passed to createChild override existing values ngModelOptions = ngModelCtrl.$options // start with a ModelOptions instance .createChild(datepickerConfig.ngModelOptions) // lowest precedence .createChild($scope.datepickerOptions.ngModelOptions) .createChild(ngModelCtrl.$options) // highest precedence .createChild({timezone: timezone}); // to keep from squashing a non-null value } return ngModelOptions; } }]) .controller('UibDaypickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) { var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; this.step = { months: 1 }; this.element = $element; function getDaysInMonth(year, month) { return month === 1 && year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : DAYS_IN_MONTH[month]; } this.init = function(ctrl) { angular.extend(ctrl, this); scope.showWeeks = ctrl.showWeeks; ctrl.refreshView(); }; this.getDates = function(startDate, n) { var dates = new Array(n), current = new Date(startDate), i = 0, date; while (i < n) { date = new Date(current); dates[i++] = date; current.setDate(current.getDate() + 1); } return dates; }; this._refreshView = function() { var year = this.activeDate.getFullYear(), month = this.activeDate.getMonth(), firstDayOfMonth = new Date(this.activeDate); firstDayOfMonth.setFullYear(year, month, 1); var difference = this.startingDay - firstDayOfMonth.getDay(), numDisplayedFromPreviousMonth = difference > 0 ? 7 - difference : - difference, firstDate = new Date(firstDayOfMonth); if (numDisplayedFromPreviousMonth > 0) { firstDate.setDate(-numDisplayedFromPreviousMonth + 1); } // 42 is the number of days on a six-week calendar var days = this.getDates(firstDate, 42); for (var i = 0; i < 42; i ++) { days[i] = angular.extend(this.createDateObject(days[i], this.formatDay), { secondary: days[i].getMonth() !== month, uid: scope.uniqueId + '-' + i }); } scope.labels = new Array(7); for (var j = 0; j < 7; j++) { scope.labels[j] = { abbr: dateFilter(days[j].date, this.formatDayHeader), full: dateFilter(days[j].date, 'EEEE') }; } scope.title = dateFilter(this.activeDate, this.formatDayTitle); scope.rows = this.split(days, 7); if (scope.showWeeks) { scope.weekNumbers = []; var thursdayIndex = (4 + 7 - this.startingDay) % 7, numWeeks = scope.rows.length; for (var curWeek = 0; curWeek < numWeeks; curWeek++) { scope.weekNumbers.push( getISO8601WeekNumber(scope.rows[curWeek][thursdayIndex].date)); } } }; this.compare = function(date1, date2) { var _date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()); var _date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()); _date1.setFullYear(date1.getFullYear()); _date2.setFullYear(date2.getFullYear()); return _date1 - _date2; }; function getISO8601WeekNumber(date) { var checkDate = new Date(date); checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday var time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; } this.handleKeyDown = function(key, evt) { var date = this.activeDate.getDate(); if (key === 'left') { date = date - 1; } else if (key === 'up') { date = date - 7; } else if (key === 'right') { date = date + 1; } else if (key === 'down') { date = date + 7; } else if (key === 'pageup' || key === 'pagedown') { var month = this.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1); this.activeDate.setMonth(month, 1); date = Math.min(getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth()), date); } else if (key === 'home') { date = 1; } else if (key === 'end') { date = getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth()); } this.activeDate.setDate(date); }; }]) .controller('UibMonthpickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) { this.step = { years: 1 }; this.element = $element; this.init = function(ctrl) { angular.extend(ctrl, this); ctrl.refreshView(); }; this._refreshView = function() { var months = new Array(12), year = this.activeDate.getFullYear(), date; for (var i = 0; i < 12; i++) { date = new Date(this.activeDate); date.setFullYear(year, i, 1); months[i] = angular.extend(this.createDateObject(date, this.formatMonth), { uid: scope.uniqueId + '-' + i }); } scope.title = dateFilter(this.activeDate, this.formatMonthTitle); scope.rows = this.split(months, this.monthColumns); scope.yearHeaderColspan = this.monthColumns > 3 ? this.monthColumns - 2 : 1; }; this.compare = function(date1, date2) { var _date1 = new Date(date1.getFullYear(), date1.getMonth()); var _date2 = new Date(date2.getFullYear(), date2.getMonth()); _date1.setFullYear(date1.getFullYear()); _date2.setFullYear(date2.getFullYear()); return _date1 - _date2; }; this.handleKeyDown = function(key, evt) { var date = this.activeDate.getMonth(); if (key === 'left') { date = date - 1; } else if (key === 'up') { date = date - this.monthColumns; } else if (key === 'right') { date = date + 1; } else if (key === 'down') { date = date + this.monthColumns; } else if (key === 'pageup' || key === 'pagedown') { var year = this.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1); this.activeDate.setFullYear(year); } else if (key === 'home') { date = 0; } else if (key === 'end') { date = 11; } this.activeDate.setMonth(date); }; }]) .controller('UibYearpickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) { var columns, range; this.element = $element; function getStartingYear(year) { return parseInt((year - 1) / range, 10) * range + 1; } this.yearpickerInit = function() { columns = this.yearColumns; range = this.yearRows * columns; this.step = { years: range }; }; this._refreshView = function() { var years = new Array(range), date; for (var i = 0, start = getStartingYear(this.activeDate.getFullYear()); i < range; i++) { date = new Date(this.activeDate); date.setFullYear(start + i, 0, 1); years[i] = angular.extend(this.createDateObject(date, this.formatYear), { uid: scope.uniqueId + '-' + i }); } scope.title = [years[0].label, years[range - 1].label].join(' - '); scope.rows = this.split(years, columns); scope.columns = columns; }; this.compare = function(date1, date2) { return date1.getFullYear() - date2.getFullYear(); }; this.handleKeyDown = function(key, evt) { var date = this.activeDate.getFullYear(); if (key === 'left') { date = date - 1; } else if (key === 'up') { date = date - columns; } else if (key === 'right') { date = date + 1; } else if (key === 'down') { date = date + columns; } else if (key === 'pageup' || key === 'pagedown') { date += (key === 'pageup' ? - 1 : 1) * range; } else if (key === 'home') { date = getStartingYear(this.activeDate.getFullYear()); } else if (key === 'end') { date = getStartingYear(this.activeDate.getFullYear()) + range - 1; } this.activeDate.setFullYear(date); }; }]) .directive('uibDatepicker', function() { return { templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/datepicker/datepicker.html'; }, scope: { datepickerOptions: '=?' }, require: ['uibDatepicker', '^ngModel'], restrict: 'A', controller: 'UibDatepickerController', controllerAs: 'datepicker', link: function(scope, element, attrs, ctrls) { var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; datepickerCtrl.init(ngModelCtrl); } }; }) .directive('uibDaypicker', function() { return { templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/datepicker/day.html'; }, require: ['^uibDatepicker', 'uibDaypicker'], restrict: 'A', controller: 'UibDaypickerController', link: function(scope, element, attrs, ctrls) { var datepickerCtrl = ctrls[0], daypickerCtrl = ctrls[1]; daypickerCtrl.init(datepickerCtrl); } }; }) .directive('uibMonthpicker', function() { return { templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/datepicker/month.html'; }, require: ['^uibDatepicker', 'uibMonthpicker'], restrict: 'A', controller: 'UibMonthpickerController', link: function(scope, element, attrs, ctrls) { var datepickerCtrl = ctrls[0], monthpickerCtrl = ctrls[1]; monthpickerCtrl.init(datepickerCtrl); } }; }) .directive('uibYearpicker', function() { return { templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/datepicker/year.html'; }, require: ['^uibDatepicker', 'uibYearpicker'], restrict: 'A', controller: 'UibYearpickerController', link: function(scope, element, attrs, ctrls) { var ctrl = ctrls[0]; angular.extend(ctrl, ctrls[1]); ctrl.yearpickerInit(); ctrl.refreshView(); } }; }); angular.module('ui.bootstrap.position', []) /** * A set of utility methods for working with the DOM. * It is meant to be used where we need to absolute-position elements in * relation to another element (this is the case for tooltips, popovers, * typeahead suggestions etc.). */ .factory('$uibPosition', ['$document', '$window', function($document, $window) { /** * Used by scrollbarWidth() function to cache scrollbar's width. * Do not access this variable directly, use scrollbarWidth() instead. */ var SCROLLBAR_WIDTH; /** * scrollbar on body and html element in IE and Edge overlay * content and should be considered 0 width. */ var BODY_SCROLLBAR_WIDTH; var OVERFLOW_REGEX = { normal: /(auto|scroll)/, hidden: /(auto|scroll|hidden)/ }; var PLACEMENT_REGEX = { auto: /\s?auto?\s?/i, primary: /^(top|bottom|left|right)$/, secondary: /^(top|bottom|left|right|center)$/, vertical: /^(top|bottom)$/ }; var BODY_REGEX = /(HTML|BODY)/; return { /** * Provides a raw DOM element from a jQuery/jQLite element. * * @param {element} elem - The element to convert. * * @returns {element} A HTML element. */ getRawNode: function(elem) { return elem.nodeName ? elem : elem[0] || elem; }, /** * Provides a parsed number for a style property. Strips * units and casts invalid numbers to 0. * * @param {string} value - The style value to parse. * * @returns {number} A valid number. */ parseStyle: function(value) { value = parseFloat(value); return isFinite(value) ? value : 0; }, /** * Provides the closest positioned ancestor. * * @param {element} element - The element to get the offest parent for. * * @returns {element} The closest positioned ancestor. */ offsetParent: function(elem) { elem = this.getRawNode(elem); var offsetParent = elem.offsetParent || $document[0].documentElement; function isStaticPositioned(el) { return ($window.getComputedStyle(el).position || 'static') === 'static'; } while (offsetParent && offsetParent !== $document[0].documentElement && isStaticPositioned(offsetParent)) { offsetParent = offsetParent.offsetParent; } return offsetParent || $document[0].documentElement; }, /** * Provides the scrollbar width, concept from TWBS measureScrollbar() * function in https://github.com/twbs/bootstrap/blob/master/js/modal.js * In IE and Edge, scollbar on body and html element overlay and should * return a width of 0. * * @returns {number} The width of the browser scollbar. */ scrollbarWidth: function(isBody) { if (isBody) { if (angular.isUndefined(BODY_SCROLLBAR_WIDTH)) { var bodyElem = $document.find('body'); bodyElem.addClass('uib-position-body-scrollbar-measure'); BODY_SCROLLBAR_WIDTH = $window.innerWidth - bodyElem[0].clientWidth; BODY_SCROLLBAR_WIDTH = isFinite(BODY_SCROLLBAR_WIDTH) ? BODY_SCROLLBAR_WIDTH : 0; bodyElem.removeClass('uib-position-body-scrollbar-measure'); } return BODY_SCROLLBAR_WIDTH; } if (angular.isUndefined(SCROLLBAR_WIDTH)) { var scrollElem = angular.element('
'); $document.find('body').append(scrollElem); SCROLLBAR_WIDTH = scrollElem[0].offsetWidth - scrollElem[0].clientWidth; SCROLLBAR_WIDTH = isFinite(SCROLLBAR_WIDTH) ? SCROLLBAR_WIDTH : 0; scrollElem.remove(); } return SCROLLBAR_WIDTH; }, /** * Provides the padding required on an element to replace the scrollbar. * * @returns {object} An object with the following properties: *
    *
  • **scrollbarWidth**: the width of the scrollbar
  • *
  • **widthOverflow**: whether the the width is overflowing
  • *
  • **right**: the amount of right padding on the element needed to replace the scrollbar
  • *
  • **rightOriginal**: the amount of right padding currently on the element
  • *
  • **heightOverflow**: whether the the height is overflowing
  • *
  • **bottom**: the amount of bottom padding on the element needed to replace the scrollbar
  • *
  • **bottomOriginal**: the amount of bottom padding currently on the element
  • *
*/ scrollbarPadding: function(elem) { elem = this.getRawNode(elem); var elemStyle = $window.getComputedStyle(elem); var paddingRight = this.parseStyle(elemStyle.paddingRight); var paddingBottom = this.parseStyle(elemStyle.paddingBottom); var scrollParent = this.scrollParent(elem, false, true); var scrollbarWidth = this.scrollbarWidth(BODY_REGEX.test(scrollParent.tagName)); return { scrollbarWidth: scrollbarWidth, widthOverflow: scrollParent.scrollWidth > scrollParent.clientWidth, right: paddingRight + scrollbarWidth, originalRight: paddingRight, heightOverflow: scrollParent.scrollHeight > scrollParent.clientHeight, bottom: paddingBottom + scrollbarWidth, originalBottom: paddingBottom }; }, /** * Checks to see if the element is scrollable. * * @param {element} elem - The element to check. * @param {boolean=} [includeHidden=false] - Should scroll style of 'hidden' be considered, * default is false. * * @returns {boolean} Whether the element is scrollable. */ isScrollable: function(elem, includeHidden) { elem = this.getRawNode(elem); var overflowRegex = includeHidden ? OVERFLOW_REGEX.hidden : OVERFLOW_REGEX.normal; var elemStyle = $window.getComputedStyle(elem); return overflowRegex.test(elemStyle.overflow + elemStyle.overflowY + elemStyle.overflowX); }, /** * Provides the closest scrollable ancestor. * A port of the jQuery UI scrollParent method: * https://github.com/jquery/jquery-ui/blob/master/ui/scroll-parent.js * * @param {element} elem - The element to find the scroll parent of. * @param {boolean=} [includeHidden=false] - Should scroll style of 'hidden' be considered, * default is false. * @param {boolean=} [includeSelf=false] - Should the element being passed be * included in the scrollable llokup. * * @returns {element} A HTML element. */ scrollParent: function(elem, includeHidden, includeSelf) { elem = this.getRawNode(elem); var overflowRegex = includeHidden ? OVERFLOW_REGEX.hidden : OVERFLOW_REGEX.normal; var documentEl = $document[0].documentElement; var elemStyle = $window.getComputedStyle(elem); if (includeSelf && overflowRegex.test(elemStyle.overflow + elemStyle.overflowY + elemStyle.overflowX)) { return elem; } var excludeStatic = elemStyle.position === 'absolute'; var scrollParent = elem.parentElement || documentEl; if (scrollParent === documentEl || elemStyle.position === 'fixed') { return documentEl; } while (scrollParent.parentElement && scrollParent !== documentEl) { var spStyle = $window.getComputedStyle(scrollParent); if (excludeStatic && spStyle.position !== 'static') { excludeStatic = false; } if (!excludeStatic && overflowRegex.test(spStyle.overflow + spStyle.overflowY + spStyle.overflowX)) { break; } scrollParent = scrollParent.parentElement; } return scrollParent; }, /** * Provides read-only equivalent of jQuery's position function: * http://api.jquery.com/position/ - distance to closest positioned * ancestor. Does not account for margins by default like jQuery position. * * @param {element} elem - The element to caclulate the position on. * @param {boolean=} [includeMargins=false] - Should margins be accounted * for, default is false. * * @returns {object} An object with the following properties: *
    *
  • **width**: the width of the element
  • *
  • **height**: the height of the element
  • *
  • **top**: distance to top edge of offset parent
  • *
  • **left**: distance to left edge of offset parent
  • *
*/ position: function(elem, includeMagins) { elem = this.getRawNode(elem); var elemOffset = this.offset(elem); if (includeMagins) { var elemStyle = $window.getComputedStyle(elem); elemOffset.top -= this.parseStyle(elemStyle.marginTop); elemOffset.left -= this.parseStyle(elemStyle.marginLeft); } var parent = this.offsetParent(elem); var parentOffset = {top: 0, left: 0}; if (parent !== $document[0].documentElement) { parentOffset = this.offset(parent); parentOffset.top += parent.clientTop - parent.scrollTop; parentOffset.left += parent.clientLeft - parent.scrollLeft; } return { width: Math.round(angular.isNumber(elemOffset.width) ? elemOffset.width : elem.offsetWidth), height: Math.round(angular.isNumber(elemOffset.height) ? elemOffset.height : elem.offsetHeight), top: Math.round(elemOffset.top - parentOffset.top), left: Math.round(elemOffset.left - parentOffset.left) }; }, /** * Provides read-only equivalent of jQuery's offset function: * http://api.jquery.com/offset/ - distance to viewport. Does * not account for borders, margins, or padding on the body * element. * * @param {element} elem - The element to calculate the offset on. * * @returns {object} An object with the following properties: *
    *
  • **width**: the width of the element
  • *
  • **height**: the height of the element
  • *
  • **top**: distance to top edge of viewport
  • *
  • **right**: distance to bottom edge of viewport
  • *
*/ offset: function(elem) { elem = this.getRawNode(elem); var elemBCR = elem.getBoundingClientRect(); return { width: Math.round(angular.isNumber(elemBCR.width) ? elemBCR.width : elem.offsetWidth), height: Math.round(angular.isNumber(elemBCR.height) ? elemBCR.height : elem.offsetHeight), top: Math.round(elemBCR.top + ($window.pageYOffset || $document[0].documentElement.scrollTop)), left: Math.round(elemBCR.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)) }; }, /** * Provides offset distance to the closest scrollable ancestor * or viewport. Accounts for border and scrollbar width. * * Right and bottom dimensions represent the distance to the * respective edge of the viewport element. If the element * edge extends beyond the viewport, a negative value will be * reported. * * @param {element} elem - The element to get the viewport offset for. * @param {boolean=} [useDocument=false] - Should the viewport be the document element instead * of the first scrollable element, default is false. * @param {boolean=} [includePadding=true] - Should the padding on the offset parent element * be accounted for, default is true. * * @returns {object} An object with the following properties: *
    *
  • **top**: distance to the top content edge of viewport element
  • *
  • **bottom**: distance to the bottom content edge of viewport element
  • *
  • **left**: distance to the left content edge of viewport element
  • *
  • **right**: distance to the right content edge of viewport element
  • *
*/ viewportOffset: function(elem, useDocument, includePadding) { elem = this.getRawNode(elem); includePadding = includePadding !== false ? true : false; var elemBCR = elem.getBoundingClientRect(); var offsetBCR = {top: 0, left: 0, bottom: 0, right: 0}; var offsetParent = useDocument ? $document[0].documentElement : this.scrollParent(elem); var offsetParentBCR = offsetParent.getBoundingClientRect(); offsetBCR.top = offsetParentBCR.top + offsetParent.clientTop; offsetBCR.left = offsetParentBCR.left + offsetParent.clientLeft; if (offsetParent === $document[0].documentElement) { offsetBCR.top += $window.pageYOffset; offsetBCR.left += $window.pageXOffset; } offsetBCR.bottom = offsetBCR.top + offsetParent.clientHeight; offsetBCR.right = offsetBCR.left + offsetParent.clientWidth; if (includePadding) { var offsetParentStyle = $window.getComputedStyle(offsetParent); offsetBCR.top += this.parseStyle(offsetParentStyle.paddingTop); offsetBCR.bottom -= this.parseStyle(offsetParentStyle.paddingBottom); offsetBCR.left += this.parseStyle(offsetParentStyle.paddingLeft); offsetBCR.right -= this.parseStyle(offsetParentStyle.paddingRight); } return { top: Math.round(elemBCR.top - offsetBCR.top), bottom: Math.round(offsetBCR.bottom - elemBCR.bottom), left: Math.round(elemBCR.left - offsetBCR.left), right: Math.round(offsetBCR.right - elemBCR.right) }; }, /** * Provides an array of placement values parsed from a placement string. * Along with the 'auto' indicator, supported placement strings are: *
    *
  • top: element on top, horizontally centered on host element.
  • *
  • top-left: element on top, left edge aligned with host element left edge.
  • *
  • top-right: element on top, lerightft edge aligned with host element right edge.
  • *
  • bottom: element on bottom, horizontally centered on host element.
  • *
  • bottom-left: element on bottom, left edge aligned with host element left edge.
  • *
  • bottom-right: element on bottom, right edge aligned with host element right edge.
  • *
  • left: element on left, vertically centered on host element.
  • *
  • left-top: element on left, top edge aligned with host element top edge.
  • *
  • left-bottom: element on left, bottom edge aligned with host element bottom edge.
  • *
  • right: element on right, vertically centered on host element.
  • *
  • right-top: element on right, top edge aligned with host element top edge.
  • *
  • right-bottom: element on right, bottom edge aligned with host element bottom edge.
  • *
* A placement string with an 'auto' indicator is expected to be * space separated from the placement, i.e: 'auto bottom-left' If * the primary and secondary placement values do not match 'top, * bottom, left, right' then 'top' will be the primary placement and * 'center' will be the secondary placement. If 'auto' is passed, true * will be returned as the 3rd value of the array. * * @param {string} placement - The placement string to parse. * * @returns {array} An array with the following values *
    *
  • **[0]**: The primary placement.
  • *
  • **[1]**: The secondary placement.
  • *
  • **[2]**: If auto is passed: true, else undefined.
  • *
*/ parsePlacement: function(placement) { var autoPlace = PLACEMENT_REGEX.auto.test(placement); if (autoPlace) { placement = placement.replace(PLACEMENT_REGEX.auto, ''); } placement = placement.split('-'); placement[0] = placement[0] || 'top'; if (!PLACEMENT_REGEX.primary.test(placement[0])) { placement[0] = 'top'; } placement[1] = placement[1] || 'center'; if (!PLACEMENT_REGEX.secondary.test(placement[1])) { placement[1] = 'center'; } if (autoPlace) { placement[2] = true; } else { placement[2] = false; } return placement; }, /** * Provides coordinates for an element to be positioned relative to * another element. Passing 'auto' as part of the placement parameter * will enable smart placement - where the element fits. i.e: * 'auto left-top' will check to see if there is enough space to the left * of the hostElem to fit the targetElem, if not place right (same for secondary * top placement). Available space is calculated using the viewportOffset * function. * * @param {element} hostElem - The element to position against. * @param {element} targetElem - The element to position. * @param {string=} [placement=top] - The placement for the targetElem, * default is 'top'. 'center' is assumed as secondary placement for * 'top', 'left', 'right', and 'bottom' placements. Available placements are: *
    *
  • top
  • *
  • top-right
  • *
  • top-left
  • *
  • bottom
  • *
  • bottom-left
  • *
  • bottom-right
  • *
  • left
  • *
  • left-top
  • *
  • left-bottom
  • *
  • right
  • *
  • right-top
  • *
  • right-bottom
  • *
* @param {boolean=} [appendToBody=false] - Should the top and left values returned * be calculated from the body element, default is false. * * @returns {object} An object with the following properties: *
    *
  • **top**: Value for targetElem top.
  • *
  • **left**: Value for targetElem left.
  • *
  • **placement**: The resolved placement.
  • *
*/ positionElements: function(hostElem, targetElem, placement, appendToBody) { hostElem = this.getRawNode(hostElem); targetElem = this.getRawNode(targetElem); // need to read from prop to support tests. var targetWidth = angular.isDefined(targetElem.offsetWidth) ? targetElem.offsetWidth : targetElem.prop('offsetWidth'); var targetHeight = angular.isDefined(targetElem.offsetHeight) ? targetElem.offsetHeight : targetElem.prop('offsetHeight'); placement = this.parsePlacement(placement); var hostElemPos = appendToBody ? this.offset(hostElem) : this.position(hostElem); var targetElemPos = {top: 0, left: 0, placement: ''}; if (placement[2]) { var viewportOffset = this.viewportOffset(hostElem, appendToBody); var targetElemStyle = $window.getComputedStyle(targetElem); var adjustedSize = { width: targetWidth + Math.round(Math.abs(this.parseStyle(targetElemStyle.marginLeft) + this.parseStyle(targetElemStyle.marginRight))), height: targetHeight + Math.round(Math.abs(this.parseStyle(targetElemStyle.marginTop) + this.parseStyle(targetElemStyle.marginBottom))) }; placement[0] = placement[0] === 'top' && adjustedSize.height > viewportOffset.top && adjustedSize.height <= viewportOffset.bottom ? 'bottom' : placement[0] === 'bottom' && adjustedSize.height > viewportOffset.bottom && adjustedSize.height <= viewportOffset.top ? 'top' : placement[0] === 'left' && adjustedSize.width > viewportOffset.left && adjustedSize.width <= viewportOffset.right ? 'right' : placement[0] === 'right' && adjustedSize.width > viewportOffset.right && adjustedSize.width <= viewportOffset.left ? 'left' : placement[0]; placement[1] = placement[1] === 'top' && adjustedSize.height - hostElemPos.height > viewportOffset.bottom && adjustedSize.height - hostElemPos.height <= viewportOffset.top ? 'bottom' : placement[1] === 'bottom' && adjustedSize.height - hostElemPos.height > viewportOffset.top && adjustedSize.height - hostElemPos.height <= viewportOffset.bottom ? 'top' : placement[1] === 'left' && adjustedSize.width - hostElemPos.width > viewportOffset.right && adjustedSize.width - hostElemPos.width <= viewportOffset.left ? 'right' : placement[1] === 'right' && adjustedSize.width - hostElemPos.width > viewportOffset.left && adjustedSize.width - hostElemPos.width <= viewportOffset.right ? 'left' : placement[1]; if (placement[1] === 'center') { if (PLACEMENT_REGEX.vertical.test(placement[0])) { var xOverflow = hostElemPos.width / 2 - targetWidth / 2; if (viewportOffset.left + xOverflow < 0 && adjustedSize.width - hostElemPos.width <= viewportOffset.right) { placement[1] = 'left'; } else if (viewportOffset.right + xOverflow < 0 && adjustedSize.width - hostElemPos.width <= viewportOffset.left) { placement[1] = 'right'; } } else { var yOverflow = hostElemPos.height / 2 - adjustedSize.height / 2; if (viewportOffset.top + yOverflow < 0 && adjustedSize.height - hostElemPos.height <= viewportOffset.bottom) { placement[1] = 'top'; } else if (viewportOffset.bottom + yOverflow < 0 && adjustedSize.height - hostElemPos.height <= viewportOffset.top) { placement[1] = 'bottom'; } } } } switch (placement[0]) { case 'top': targetElemPos.top = hostElemPos.top - targetHeight; break; case 'bottom': targetElemPos.top = hostElemPos.top + hostElemPos.height; break; case 'left': targetElemPos.left = hostElemPos.left - targetWidth; break; case 'right': targetElemPos.left = hostElemPos.left + hostElemPos.width; break; } switch (placement[1]) { case 'top': targetElemPos.top = hostElemPos.top; break; case 'bottom': targetElemPos.top = hostElemPos.top + hostElemPos.height - targetHeight; break; case 'left': targetElemPos.left = hostElemPos.left; break; case 'right': targetElemPos.left = hostElemPos.left + hostElemPos.width - targetWidth; break; case 'center': if (PLACEMENT_REGEX.vertical.test(placement[0])) { targetElemPos.left = hostElemPos.left + hostElemPos.width / 2 - targetWidth / 2; } else { targetElemPos.top = hostElemPos.top + hostElemPos.height / 2 - targetHeight / 2; } break; } targetElemPos.top = Math.round(targetElemPos.top); targetElemPos.left = Math.round(targetElemPos.left); targetElemPos.placement = placement[1] === 'center' ? placement[0] : placement[0] + '-' + placement[1]; return targetElemPos; }, /** * Provides a way to adjust the top positioning after first * render to correctly align element to top after content * rendering causes resized element height * * @param {array} placementClasses - The array of strings of classes * element should have. * @param {object} containerPosition - The object with container * position information * @param {number} initialHeight - The initial height for the elem. * @param {number} currentHeight - The current height for the elem. */ adjustTop: function(placementClasses, containerPosition, initialHeight, currentHeight) { if (placementClasses.indexOf('top') !== -1 && initialHeight !== currentHeight) { return { top: containerPosition.top - currentHeight + 'px' }; } }, /** * Provides a way for positioning tooltip & dropdown * arrows when using placement options beyond the standard * left, right, top, or bottom. * * @param {element} elem - The tooltip/dropdown element. * @param {string} placement - The placement for the elem. */ positionArrow: function(elem, placement) { elem = this.getRawNode(elem); var innerElem = elem.querySelector('.tooltip-inner, .popover-inner'); if (!innerElem) { return; } var isTooltip = angular.element(innerElem).hasClass('tooltip-inner'); var arrowElem = isTooltip ? elem.querySelector('.tooltip-arrow') : elem.querySelector('.arrow'); if (!arrowElem) { return; } var arrowCss = { top: '', bottom: '', left: '', right: '' }; placement = this.parsePlacement(placement); if (placement[1] === 'center') { // no adjustment necessary - just reset styles angular.element(arrowElem).css(arrowCss); return; } var borderProp = 'border-' + placement[0] + '-width'; var borderWidth = $window.getComputedStyle(arrowElem)[borderProp]; var borderRadiusProp = 'border-'; if (PLACEMENT_REGEX.vertical.test(placement[0])) { borderRadiusProp += placement[0] + '-' + placement[1]; } else { borderRadiusProp += placement[1] + '-' + placement[0]; } borderRadiusProp += '-radius'; var borderRadius = $window.getComputedStyle(isTooltip ? innerElem : elem)[borderRadiusProp]; switch (placement[0]) { case 'top': arrowCss.bottom = isTooltip ? '0' : '-' + borderWidth; break; case 'bottom': arrowCss.top = isTooltip ? '0' : '-' + borderWidth; break; case 'left': arrowCss.right = isTooltip ? '0' : '-' + borderWidth; break; case 'right': arrowCss.left = isTooltip ? '0' : '-' + borderWidth; break; } arrowCss[placement[1]] = borderRadius; angular.element(arrowElem).css(arrowCss); } }; }]); angular.module('ui.bootstrap.datepickerPopup', ['ui.bootstrap.datepicker', 'ui.bootstrap.position']) .value('$datepickerPopupLiteralWarning', true) .constant('uibDatepickerPopupConfig', { altInputFormats: [], appendToBody: false, clearText: 'Clear', closeOnDateSelection: true, closeText: 'Done', currentText: 'Today', datepickerPopup: 'yyyy-MM-dd', datepickerPopupTemplateUrl: 'uib/template/datepickerPopup/popup.html', datepickerTemplateUrl: 'uib/template/datepicker/datepicker.html', html5Types: { date: 'yyyy-MM-dd', 'datetime-local': 'yyyy-MM-ddTHH:mm:ss.sss', 'month': 'yyyy-MM' }, onOpenFocus: true, showButtonBar: true, placement: 'auto bottom-left' }) .controller('UibDatepickerPopupController', ['$scope', '$element', '$attrs', '$compile', '$log', '$parse', '$window', '$document', '$rootScope', '$uibPosition', 'dateFilter', 'uibDateParser', 'uibDatepickerPopupConfig', '$timeout', 'uibDatepickerConfig', '$datepickerPopupLiteralWarning', function($scope, $element, $attrs, $compile, $log, $parse, $window, $document, $rootScope, $position, dateFilter, dateParser, datepickerPopupConfig, $timeout, datepickerConfig, $datepickerPopupLiteralWarning) { var cache = {}, isHtml5DateInput = false; var dateFormat, closeOnDateSelection, appendToBody, onOpenFocus, datepickerPopupTemplateUrl, datepickerTemplateUrl, popupEl, datepickerEl, scrollParentEl, ngModel, ngModelOptions, $popup, altInputFormats, watchListeners = []; this.init = function(_ngModel_) { ngModel = _ngModel_; ngModelOptions = extractOptions(ngModel); closeOnDateSelection = angular.isDefined($attrs.closeOnDateSelection) ? $scope.$parent.$eval($attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection; appendToBody = angular.isDefined($attrs.datepickerAppendToBody) ? $scope.$parent.$eval($attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody; onOpenFocus = angular.isDefined($attrs.onOpenFocus) ? $scope.$parent.$eval($attrs.onOpenFocus) : datepickerPopupConfig.onOpenFocus; datepickerPopupTemplateUrl = angular.isDefined($attrs.datepickerPopupTemplateUrl) ? $attrs.datepickerPopupTemplateUrl : datepickerPopupConfig.datepickerPopupTemplateUrl; datepickerTemplateUrl = angular.isDefined($attrs.datepickerTemplateUrl) ? $attrs.datepickerTemplateUrl : datepickerPopupConfig.datepickerTemplateUrl; altInputFormats = angular.isDefined($attrs.altInputFormats) ? $scope.$parent.$eval($attrs.altInputFormats) : datepickerPopupConfig.altInputFormats; $scope.showButtonBar = angular.isDefined($attrs.showButtonBar) ? $scope.$parent.$eval($attrs.showButtonBar) : datepickerPopupConfig.showButtonBar; if (datepickerPopupConfig.html5Types[$attrs.type]) { dateFormat = datepickerPopupConfig.html5Types[$attrs.type]; isHtml5DateInput = true; } else { dateFormat = $attrs.uibDatepickerPopup || datepickerPopupConfig.datepickerPopup; $attrs.$observe('uibDatepickerPopup', function(value, oldValue) { var newDateFormat = value || datepickerPopupConfig.datepickerPopup; // Invalidate the $modelValue to ensure that formatters re-run // FIXME: Refactor when PR is merged: https://github.com/angular/angular.js/pull/10764 if (newDateFormat !== dateFormat) { dateFormat = newDateFormat; ngModel.$modelValue = null; if (!dateFormat) { throw new Error('uibDatepickerPopup must have a date format specified.'); } } }); } if (!dateFormat) { throw new Error('uibDatepickerPopup must have a date format specified.'); } if (isHtml5DateInput && $attrs.uibDatepickerPopup) { throw new Error('HTML5 date input types do not support custom formats.'); } // popup element used to display calendar popupEl = angular.element('
'); popupEl.attr({ 'ng-model': 'date', 'ng-change': 'dateSelection(date)', 'template-url': datepickerPopupTemplateUrl }); // datepicker element datepickerEl = angular.element(popupEl.children()[0]); datepickerEl.attr('template-url', datepickerTemplateUrl); if (!$scope.datepickerOptions) { $scope.datepickerOptions = {}; } if (isHtml5DateInput) { if ($attrs.type === 'month') { $scope.datepickerOptions.datepickerMode = 'month'; $scope.datepickerOptions.minMode = 'month'; } } datepickerEl.attr('datepicker-options', 'datepickerOptions'); if (!isHtml5DateInput) { // Internal API to maintain the correct ng-invalid-[key] class ngModel.$$parserName = 'date'; ngModel.$validators.date = validator; ngModel.$parsers.unshift(parseDate); ngModel.$formatters.push(function(value) { if (ngModel.$isEmpty(value)) { $scope.date = value; return value; } if (angular.isNumber(value)) { value = new Date(value); } $scope.date = dateParser.fromTimezone(value, ngModelOptions.getOption('timezone')); return dateParser.filter($scope.date, dateFormat); }); } else { ngModel.$formatters.push(function(value) { $scope.date = dateParser.fromTimezone(value, ngModelOptions.getOption('timezone')); return value; }); } // Detect changes in the view from the text box ngModel.$viewChangeListeners.push(function() { $scope.date = parseDateString(ngModel.$viewValue); }); $element.on('keydown', inputKeydownBind); $popup = $compile(popupEl)($scope); // Prevent jQuery cache memory leak (template is now redundant after linking) popupEl.remove(); if (appendToBody) { $document.find('body').append($popup); } else { $element.after($popup); } $scope.$on('$destroy', function() { if ($scope.isOpen === true) { if (!$rootScope.$$phase) { $scope.$apply(function() { $scope.isOpen = false; }); } } $popup.remove(); $element.off('keydown', inputKeydownBind); $document.off('click', documentClickBind); if (scrollParentEl) { scrollParentEl.off('scroll', positionPopup); } angular.element($window).off('resize', positionPopup); //Clear all watch listeners on destroy while (watchListeners.length) { watchListeners.shift()(); } }); }; $scope.getText = function(key) { return $scope[key + 'Text'] || datepickerPopupConfig[key + 'Text']; }; $scope.isDisabled = function(date) { if (date === 'today') { date = dateParser.fromTimezone(new Date(), ngModelOptions.getOption('timezone')); } var dates = {}; angular.forEach(['minDate', 'maxDate'], function(key) { if (!$scope.datepickerOptions[key]) { dates[key] = null; } else if (angular.isDate($scope.datepickerOptions[key])) { dates[key] = new Date($scope.datepickerOptions[key]); } else { if ($datepickerPopupLiteralWarning) { $log.warn('Literal date support has been deprecated, please switch to date object usage'); } dates[key] = new Date(dateFilter($scope.datepickerOptions[key], 'medium')); } }); return $scope.datepickerOptions && dates.minDate && $scope.compare(date, dates.minDate) < 0 || dates.maxDate && $scope.compare(date, dates.maxDate) > 0; }; $scope.compare = function(date1, date2) { return new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()); }; // Inner change $scope.dateSelection = function(dt) { $scope.date = dt; var date = $scope.date ? dateParser.filter($scope.date, dateFormat) : null; // Setting to NULL is necessary for form validators to function $element.val(date); ngModel.$setViewValue(date); if (closeOnDateSelection) { $scope.isOpen = false; $element[0].focus(); } }; $scope.keydown = function(evt) { if (evt.which === 27) { evt.stopPropagation(); $scope.isOpen = false; $element[0].focus(); } }; $scope.select = function(date, evt) { evt.stopPropagation(); if (date === 'today') { var today = new Date(); if (angular.isDate($scope.date)) { date = new Date($scope.date); date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate()); } else { date = dateParser.fromTimezone(today, ngModelOptions.getOption('timezone')); date.setHours(0, 0, 0, 0); } } $scope.dateSelection(date); }; $scope.close = function(evt) { evt.stopPropagation(); $scope.isOpen = false; $element[0].focus(); }; $scope.disabled = angular.isDefined($attrs.disabled) || false; if ($attrs.ngDisabled) { watchListeners.push($scope.$parent.$watch($parse($attrs.ngDisabled), function(disabled) { $scope.disabled = disabled; })); } $scope.$watch('isOpen', function(value) { if (value) { if (!$scope.disabled) { $timeout(function() { positionPopup(); if (onOpenFocus) { $scope.$broadcast('uib:datepicker.focus'); } $document.on('click', documentClickBind); var placement = $attrs.popupPlacement ? $attrs.popupPlacement : datepickerPopupConfig.placement; if (appendToBody || $position.parsePlacement(placement)[2]) { scrollParentEl = scrollParentEl || angular.element($position.scrollParent($element)); if (scrollParentEl) { scrollParentEl.on('scroll', positionPopup); } } else { scrollParentEl = null; } angular.element($window).on('resize', positionPopup); }, 0, false); } else { $scope.isOpen = false; } } else { $document.off('click', documentClickBind); if (scrollParentEl) { scrollParentEl.off('scroll', positionPopup); } angular.element($window).off('resize', positionPopup); } }); function cameltoDash(string) { return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); }); } function parseDateString(viewValue) { var date = dateParser.parse(viewValue, dateFormat, $scope.date); if (isNaN(date)) { for (var i = 0; i < altInputFormats.length; i++) { date = dateParser.parse(viewValue, altInputFormats[i], $scope.date); if (!isNaN(date)) { return date; } } } return date; } function parseDate(viewValue) { if (angular.isNumber(viewValue)) { // presumably timestamp to date object viewValue = new Date(viewValue); } if (!viewValue) { return null; } if (angular.isDate(viewValue) && !isNaN(viewValue)) { return viewValue; } if (angular.isString(viewValue)) { var date = parseDateString(viewValue); if (!isNaN(date)) { return dateParser.toTimezone(date, ngModelOptions.getOption('timezone')); } } return ngModelOptions.getOption('allowInvalid') ? viewValue : undefined; } function validator(modelValue, viewValue) { var value = modelValue || viewValue; if (!$attrs.ngRequired && !value) { return true; } if (angular.isNumber(value)) { value = new Date(value); } if (!value) { return true; } if (angular.isDate(value) && !isNaN(value)) { return true; } if (angular.isString(value)) { return !isNaN(parseDateString(value)); } return false; } function documentClickBind(event) { if (!$scope.isOpen && $scope.disabled) { return; } var popup = $popup[0]; var dpContainsTarget = $element[0].contains(event.target); // The popup node may not be an element node // In some browsers (IE) only element nodes have the 'contains' function var popupContainsTarget = popup.contains !== undefined && popup.contains(event.target); if ($scope.isOpen && !(dpContainsTarget || popupContainsTarget)) { $scope.$apply(function() { $scope.isOpen = false; }); } } function inputKeydownBind(evt) { if (evt.which === 27 && $scope.isOpen) { evt.preventDefault(); evt.stopPropagation(); $scope.$apply(function() { $scope.isOpen = false; }); $element[0].focus(); } else if (evt.which === 40 && !$scope.isOpen) { evt.preventDefault(); evt.stopPropagation(); $scope.$apply(function() { $scope.isOpen = true; }); } } function positionPopup() { if ($scope.isOpen) { var dpElement = angular.element($popup[0].querySelector('.uib-datepicker-popup')); var placement = $attrs.popupPlacement ? $attrs.popupPlacement : datepickerPopupConfig.placement; var position = $position.positionElements($element, dpElement, placement, appendToBody); dpElement.css({top: position.top + 'px', left: position.left + 'px'}); if (dpElement.hasClass('uib-position-measure')) { dpElement.removeClass('uib-position-measure'); } } } function extractOptions(ngModelCtrl) { var ngModelOptions; if (angular.version.minor < 6) { // in angular < 1.6 $options could be missing // guarantee a value ngModelOptions = angular.isObject(ngModelCtrl.$options) ? ngModelCtrl.$options : { timezone: null }; // mimic 1.6+ api ngModelOptions.getOption = function (key) { return ngModelOptions[key]; }; } else { // in angular >=1.6 $options is always present ngModelOptions = ngModelCtrl.$options; } return ngModelOptions; } $scope.$on('uib:datepicker.mode', function() { $timeout(positionPopup, 0, false); }); }]) .directive('uibDatepickerPopup', function() { return { require: ['ngModel', 'uibDatepickerPopup'], controller: 'UibDatepickerPopupController', scope: { datepickerOptions: '=?', isOpen: '=?', currentText: '@', clearText: '@', closeText: '@' }, link: function(scope, element, attrs, ctrls) { var ngModel = ctrls[0], ctrl = ctrls[1]; ctrl.init(ngModel); } }; }) .directive('uibDatepickerPopupWrap', function() { return { restrict: 'A', transclude: true, templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/datepickerPopup/popup.html'; } }; }); angular.module('ui.bootstrap.debounce', []) /** * A helper, internal service that debounces a function */ .factory('$$debounce', ['$timeout', function($timeout) { return function(callback, debounceTime) { var timeoutPromise; return function() { var self = this; var args = Array.prototype.slice.call(arguments); if (timeoutPromise) { $timeout.cancel(timeoutPromise); } timeoutPromise = $timeout(function() { callback.apply(self, args); }, debounceTime); }; }; }]); angular.module('ui.bootstrap.multiMap', []) /** * A helper, internal data structure that stores all references attached to key */ .factory('$$multiMap', function() { return { createNew: function() { var map = {}; return { entries: function() { return Object.keys(map).map(function(key) { return { key: key, value: map[key] }; }); }, get: function(key) { return map[key]; }, hasKey: function(key) { return !!map[key]; }, keys: function() { return Object.keys(map); }, put: function(key, value) { if (!map[key]) { map[key] = []; } map[key].push(value); }, remove: function(key, value) { var values = map[key]; if (!values) { return; } var idx = values.indexOf(value); if (idx !== -1) { values.splice(idx, 1); } if (!values.length) { delete map[key]; } } }; } }; }); angular.module('ui.bootstrap.dropdown', ['ui.bootstrap.multiMap', 'ui.bootstrap.position']) .constant('uibDropdownConfig', { appendToOpenClass: 'uib-dropdown-open', openClass: 'open' }) .service('uibDropdownService', ['$document', '$rootScope', '$$multiMap', function($document, $rootScope, $$multiMap) { var openScope = null; var openedContainers = $$multiMap.createNew(); this.isOnlyOpen = function(dropdownScope, appendTo) { var openedDropdowns = openedContainers.get(appendTo); if (openedDropdowns) { var openDropdown = openedDropdowns.reduce(function(toClose, dropdown) { if (dropdown.scope === dropdownScope) { return dropdown; } return toClose; }, {}); if (openDropdown) { return openedDropdowns.length === 1; } } return false; }; this.open = function(dropdownScope, element, appendTo) { if (!openScope) { $document.on('click', closeDropdown); } if (openScope && openScope !== dropdownScope) { openScope.isOpen = false; } openScope = dropdownScope; if (!appendTo) { return; } var openedDropdowns = openedContainers.get(appendTo); if (openedDropdowns) { var openedScopes = openedDropdowns.map(function(dropdown) { return dropdown.scope; }); if (openedScopes.indexOf(dropdownScope) === -1) { openedContainers.put(appendTo, { scope: dropdownScope }); } } else { openedContainers.put(appendTo, { scope: dropdownScope }); } }; this.close = function(dropdownScope, element, appendTo) { if (openScope === dropdownScope) { $document.off('click', closeDropdown); $document.off('keydown', this.keybindFilter); openScope = null; } if (!appendTo) { return; } var openedDropdowns = openedContainers.get(appendTo); if (openedDropdowns) { var dropdownToClose = openedDropdowns.reduce(function(toClose, dropdown) { if (dropdown.scope === dropdownScope) { return dropdown; } return toClose; }, {}); if (dropdownToClose) { openedContainers.remove(appendTo, dropdownToClose); } } }; var closeDropdown = function(evt) { // This method may still be called during the same mouse event that // unbound this event handler. So check openScope before proceeding. if (!openScope || !openScope.isOpen) { return; } if (evt && openScope.getAutoClose() === 'disabled') { return; } if (evt && evt.which === 3) { return; } var toggleElement = openScope.getToggleElement(); if (evt && toggleElement && toggleElement[0].contains(evt.target)) { return; } var dropdownElement = openScope.getDropdownElement(); if (evt && openScope.getAutoClose() === 'outsideClick' && dropdownElement && dropdownElement[0].contains(evt.target)) { return; } openScope.focusToggleElement(); openScope.isOpen = false; if (!$rootScope.$$phase) { openScope.$apply(); } }; this.keybindFilter = function(evt) { if (!openScope) { // see this.close as ESC could have been pressed which kills the scope so we can not proceed return; } var dropdownElement = openScope.getDropdownElement(); var toggleElement = openScope.getToggleElement(); var dropdownElementTargeted = dropdownElement && dropdownElement[0].contains(evt.target); var toggleElementTargeted = toggleElement && toggleElement[0].contains(evt.target); if (evt.which === 27) { evt.stopPropagation(); openScope.focusToggleElement(); closeDropdown(); } else if (openScope.isKeynavEnabled() && [38, 40].indexOf(evt.which) !== -1 && openScope.isOpen && (dropdownElementTargeted || toggleElementTargeted)) { evt.preventDefault(); evt.stopPropagation(); openScope.focusDropdownEntry(evt.which); } }; }]) .controller('UibDropdownController', ['$scope', '$element', '$attrs', '$parse', 'uibDropdownConfig', 'uibDropdownService', '$animate', '$uibPosition', '$document', '$compile', '$templateRequest', function($scope, $element, $attrs, $parse, dropdownConfig, uibDropdownService, $animate, $position, $document, $compile, $templateRequest) { var self = this, scope = $scope.$new(), // create a child scope so we are not polluting original one templateScope, appendToOpenClass = dropdownConfig.appendToOpenClass, openClass = dropdownConfig.openClass, getIsOpen, setIsOpen = angular.noop, toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop, keynavEnabled = false, selectedOption = null, body = $document.find('body'); $element.addClass('dropdown'); this.init = function() { if ($attrs.isOpen) { getIsOpen = $parse($attrs.isOpen); setIsOpen = getIsOpen.assign; $scope.$watch(getIsOpen, function(value) { scope.isOpen = !!value; }); } keynavEnabled = angular.isDefined($attrs.keyboardNav); }; this.toggle = function(open) { scope.isOpen = arguments.length ? !!open : !scope.isOpen; if (angular.isFunction(setIsOpen)) { setIsOpen(scope, scope.isOpen); } return scope.isOpen; }; // Allow other directives to watch status this.isOpen = function() { return scope.isOpen; }; scope.getToggleElement = function() { return self.toggleElement; }; scope.getAutoClose = function() { return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled' }; scope.getElement = function() { return $element; }; scope.isKeynavEnabled = function() { return keynavEnabled; }; scope.focusDropdownEntry = function(keyCode) { var elems = self.dropdownMenu ? //If append to body is used. angular.element(self.dropdownMenu).find('a') : $element.find('ul').eq(0).find('a'); switch (keyCode) { case 40: { if (!angular.isNumber(self.selectedOption)) { self.selectedOption = 0; } else { self.selectedOption = self.selectedOption === elems.length - 1 ? self.selectedOption : self.selectedOption + 1; } break; } case 38: { if (!angular.isNumber(self.selectedOption)) { self.selectedOption = elems.length - 1; } else { self.selectedOption = self.selectedOption === 0 ? 0 : self.selectedOption - 1; } break; } } elems[self.selectedOption].focus(); }; scope.getDropdownElement = function() { return self.dropdownMenu; }; scope.focusToggleElement = function() { if (self.toggleElement) { self.toggleElement[0].focus(); } }; function removeDropdownMenu() { $element.append(self.dropdownMenu); } scope.$watch('isOpen', function(isOpen, wasOpen) { var appendTo = null, appendToBody = false; if (angular.isDefined($attrs.dropdownAppendTo)) { var appendToEl = $parse($attrs.dropdownAppendTo)(scope); if (appendToEl) { appendTo = angular.element(appendToEl); } } if (angular.isDefined($attrs.dropdownAppendToBody)) { var appendToBodyValue = $parse($attrs.dropdownAppendToBody)(scope); if (appendToBodyValue !== false) { appendToBody = true; } } if (appendToBody && !appendTo) { appendTo = body; } if (appendTo && self.dropdownMenu) { if (isOpen) { appendTo.append(self.dropdownMenu); $element.on('$destroy', removeDropdownMenu); } else { $element.off('$destroy', removeDropdownMenu); removeDropdownMenu(); } } if (appendTo && self.dropdownMenu) { var pos = $position.positionElements($element, self.dropdownMenu, 'bottom-left', true), css, rightalign, scrollbarPadding, scrollbarWidth = 0; css = { top: pos.top + 'px', display: isOpen ? 'block' : 'none' }; rightalign = self.dropdownMenu.hasClass('dropdown-menu-right'); if (!rightalign) { css.left = pos.left + 'px'; css.right = 'auto'; } else { css.left = 'auto'; scrollbarPadding = $position.scrollbarPadding(appendTo); if (scrollbarPadding.heightOverflow && scrollbarPadding.scrollbarWidth) { scrollbarWidth = scrollbarPadding.scrollbarWidth; } css.right = window.innerWidth - scrollbarWidth - (pos.left + $element.prop('offsetWidth')) + 'px'; } // Need to adjust our positioning to be relative to the appendTo container // if it's not the body element if (!appendToBody) { var appendOffset = $position.offset(appendTo); css.top = pos.top - appendOffset.top + 'px'; if (!rightalign) { css.left = pos.left - appendOffset.left + 'px'; } else { css.right = window.innerWidth - (pos.left - appendOffset.left + $element.prop('offsetWidth')) + 'px'; } } self.dropdownMenu.css(css); } var openContainer = appendTo ? appendTo : $element; var dropdownOpenClass = appendTo ? appendToOpenClass : openClass; var hasOpenClass = openContainer.hasClass(dropdownOpenClass); var isOnlyOpen = uibDropdownService.isOnlyOpen($scope, appendTo); if (hasOpenClass === !isOpen) { var toggleClass; if (appendTo) { toggleClass = !isOnlyOpen ? 'addClass' : 'removeClass'; } else { toggleClass = isOpen ? 'addClass' : 'removeClass'; } $animate[toggleClass](openContainer, dropdownOpenClass).then(function() { if (angular.isDefined(isOpen) && isOpen !== wasOpen) { toggleInvoker($scope, { open: !!isOpen }); } }); } if (isOpen) { if (self.dropdownMenuTemplateUrl) { $templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) { templateScope = scope.$new(); $compile(tplContent.trim())(templateScope, function(dropdownElement) { var newEl = dropdownElement; self.dropdownMenu.replaceWith(newEl); self.dropdownMenu = newEl; $document.on('keydown', uibDropdownService.keybindFilter); }); }); } else { $document.on('keydown', uibDropdownService.keybindFilter); } scope.focusToggleElement(); uibDropdownService.open(scope, $element, appendTo); } else { uibDropdownService.close(scope, $element, appendTo); if (self.dropdownMenuTemplateUrl) { if (templateScope) { templateScope.$destroy(); } var newEl = angular.element(''); self.dropdownMenu.replaceWith(newEl); self.dropdownMenu = newEl; } self.selectedOption = null; } if (angular.isFunction(setIsOpen)) { setIsOpen($scope, isOpen); } }); }]) .directive('uibDropdown', function() { return { controller: 'UibDropdownController', link: function(scope, element, attrs, dropdownCtrl) { dropdownCtrl.init(); } }; }) .directive('uibDropdownMenu', function() { return { restrict: 'A', require: '?^uibDropdown', link: function(scope, element, attrs, dropdownCtrl) { if (!dropdownCtrl || angular.isDefined(attrs.dropdownNested)) { return; } element.addClass('dropdown-menu'); var tplUrl = attrs.templateUrl; if (tplUrl) { dropdownCtrl.dropdownMenuTemplateUrl = tplUrl; } if (!dropdownCtrl.dropdownMenu) { dropdownCtrl.dropdownMenu = element; } } }; }) .directive('uibDropdownToggle', function() { return { require: '?^uibDropdown', link: function(scope, element, attrs, dropdownCtrl) { if (!dropdownCtrl) { return; } element.addClass('dropdown-toggle'); dropdownCtrl.toggleElement = element; var toggleDropdown = function(event) { event.preventDefault(); if (!element.hasClass('disabled') && !attrs.disabled) { scope.$apply(function() { dropdownCtrl.toggle(); }); } }; element.on('click', toggleDropdown); // WAI-ARIA element.attr({ 'aria-haspopup': true, 'aria-expanded': false }); scope.$watch(dropdownCtrl.isOpen, function(isOpen) { element.attr('aria-expanded', !!isOpen); }); scope.$on('$destroy', function() { element.off('click', toggleDropdown); }); } }; }); angular.module('ui.bootstrap.stackedMap', []) /** * A helper, internal data structure that acts as a map but also allows getting / removing * elements in the LIFO order */ .factory('$$stackedMap', function() { return { createNew: function() { var stack = []; return { add: function(key, value) { stack.push({ key: key, value: value }); }, get: function(key) { for (var i = 0; i < stack.length; i++) { if (key === stack[i].key) { return stack[i]; } } }, keys: function() { var keys = []; for (var i = 0; i < stack.length; i++) { keys.push(stack[i].key); } return keys; }, top: function() { return stack[stack.length - 1]; }, remove: function(key) { var idx = -1; for (var i = 0; i < stack.length; i++) { if (key === stack[i].key) { idx = i; break; } } return stack.splice(idx, 1)[0]; }, removeTop: function() { return stack.pop(); }, length: function() { return stack.length; } }; } }; }); angular.module('ui.bootstrap.modal', ['ui.bootstrap.multiMap', 'ui.bootstrap.stackedMap', 'ui.bootstrap.position']) /** * Pluggable resolve mechanism for the modal resolve resolution * Supports UI Router's $resolve service */ .provider('$uibResolve', function() { var resolve = this; this.resolver = null; this.setResolver = function(resolver) { this.resolver = resolver; }; this.$get = ['$injector', '$q', function($injector, $q) { var resolver = resolve.resolver ? $injector.get(resolve.resolver) : null; return { resolve: function(invocables, locals, parent, self) { if (resolver) { return resolver.resolve(invocables, locals, parent, self); } var promises = []; angular.forEach(invocables, function(value) { if (angular.isFunction(value) || angular.isArray(value)) { promises.push($q.resolve($injector.invoke(value))); } else if (angular.isString(value)) { promises.push($q.resolve($injector.get(value))); } else { promises.push($q.resolve(value)); } }); return $q.all(promises).then(function(resolves) { var resolveObj = {}; var resolveIter = 0; angular.forEach(invocables, function(value, key) { resolveObj[key] = resolves[resolveIter++]; }); return resolveObj; }); } }; }]; }) /** * A helper directive for the $modal service. It creates a backdrop element. */ .directive('uibModalBackdrop', ['$animate', '$injector', '$uibModalStack', function($animate, $injector, $modalStack) { return { restrict: 'A', compile: function(tElement, tAttrs) { tElement.addClass(tAttrs.backdropClass); return linkFn; } }; function linkFn(scope, element, attrs) { if (attrs.modalInClass) { $animate.addClass(element, attrs.modalInClass); scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) { var done = setIsAsync(); if (scope.modalOptions.animation) { $animate.removeClass(element, attrs.modalInClass).then(done); } else { done(); } }); } } }]) .directive('uibModalWindow', ['$uibModalStack', '$q', '$animateCss', '$document', function($modalStack, $q, $animateCss, $document) { return { scope: { index: '@' }, restrict: 'A', transclude: true, templateUrl: function(tElement, tAttrs) { return tAttrs.templateUrl || 'uib/template/modal/window.html'; }, link: function(scope, element, attrs) { element.addClass(attrs.windowTopClass || ''); scope.size = attrs.size; scope.close = function(evt) { var modal = $modalStack.getTop(); if (modal && modal.value.backdrop && modal.value.backdrop !== 'static' && evt.target === evt.currentTarget) { evt.preventDefault(); evt.stopPropagation(); $modalStack.dismiss(modal.key, 'backdrop click'); } }; // moved from template to fix issue #2280 element.on('click', scope.close); // This property is only added to the scope for the purpose of detecting when this directive is rendered. // We can detect that by using this property in the template associated with this directive and then use // {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}. scope.$isRendered = true; // Deferred object that will be resolved when this modal is rendered. var modalRenderDeferObj = $q.defer(); // Resolve render promise post-digest scope.$$postDigest(function() { modalRenderDeferObj.resolve(); }); modalRenderDeferObj.promise.then(function() { var animationPromise = null; if (attrs.modalInClass) { animationPromise = $animateCss(element, { addClass: attrs.modalInClass }).start(); scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) { var done = setIsAsync(); $animateCss(element, { removeClass: attrs.modalInClass }).start().then(done); }); } $q.when(animationPromise).then(function() { // Notify {@link $modalStack} that modal is rendered. var modal = $modalStack.getTop(); if (modal) { $modalStack.modalRendered(modal.key); } /** * If something within the freshly-opened modal already has focus (perhaps via a * directive that causes focus) then there's no need to try to focus anything. */ if (!($document[0].activeElement && element[0].contains($document[0].activeElement))) { var inputWithAutofocus = element[0].querySelector('[autofocus]'); /** * Auto-focusing of a freshly-opened modal element causes any child elements * with the autofocus attribute to lose focus. This is an issue on touch * based devices which will show and then hide the onscreen keyboard. * Attempts to refocus the autofocus element via JavaScript will not reopen * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus * the modal element if the modal does not contain an autofocus element. */ if (inputWithAutofocus) { inputWithAutofocus.focus(); } else { element[0].focus(); } } }); }); } }; }]) .directive('uibModalAnimationClass', function() { return { compile: function(tElement, tAttrs) { if (tAttrs.modalAnimation) { tElement.addClass(tAttrs.uibModalAnimationClass); } } }; }) .directive('uibModalTransclude', ['$animate', function($animate) { return { link: function(scope, element, attrs, controller, transclude) { transclude(scope.$parent, function(clone) { element.empty(); $animate.enter(clone, element); }); } }; }]) .factory('$uibModalStack', ['$animate', '$animateCss', '$document', '$compile', '$rootScope', '$q', '$$multiMap', '$$stackedMap', '$uibPosition', function($animate, $animateCss, $document, $compile, $rootScope, $q, $$multiMap, $$stackedMap, $uibPosition) { var OPENED_MODAL_CLASS = 'modal-open'; var backdropDomEl, backdropScope; var openedWindows = $$stackedMap.createNew(); var openedClasses = $$multiMap.createNew(); var $modalStack = { NOW_CLOSING_EVENT: 'modal.stack.now-closing' }; var topModalIndex = 0; var previousTopOpenedModal = null; var ARIA_HIDDEN_ATTRIBUTE_NAME = 'data-bootstrap-modal-aria-hidden-count'; //Modal focus behavior var tabbableSelector = 'a[href], area[href], input:not([disabled]):not([tabindex=\'-1\']), ' + 'button:not([disabled]):not([tabindex=\'-1\']),select:not([disabled]):not([tabindex=\'-1\']), textarea:not([disabled]):not([tabindex=\'-1\']), ' + 'iframe, object, embed, *[tabindex]:not([tabindex=\'-1\']), *[contenteditable=true]'; var scrollbarPadding; var SNAKE_CASE_REGEXP = /[A-Z]/g; // TODO: extract into common dependency with tooltip function snake_case(name) { var separator = '-'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } function isVisible(element) { return !!(element.offsetWidth || element.offsetHeight || element.getClientRects().length); } function backdropIndex() { var topBackdropIndex = -1; var opened = openedWindows.keys(); for (var i = 0; i < opened.length; i++) { if (openedWindows.get(opened[i]).value.backdrop) { topBackdropIndex = i; } } // If any backdrop exist, ensure that it's index is always // right below the top modal if (topBackdropIndex > -1 && topBackdropIndex < topModalIndex) { topBackdropIndex = topModalIndex; } return topBackdropIndex; } $rootScope.$watch(backdropIndex, function(newBackdropIndex) { if (backdropScope) { backdropScope.index = newBackdropIndex; } }); function removeModalWindow(modalInstance, elementToReceiveFocus) { var modalWindow = openedWindows.get(modalInstance).value; var appendToElement = modalWindow.appendTo; //clean up the stack openedWindows.remove(modalInstance); previousTopOpenedModal = openedWindows.top(); if (previousTopOpenedModal) { topModalIndex = parseInt(previousTopOpenedModal.value.modalDomEl.attr('index'), 10); } removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, function() { var modalBodyClass = modalWindow.openedClass || OPENED_MODAL_CLASS; openedClasses.remove(modalBodyClass, modalInstance); var areAnyOpen = openedClasses.hasKey(modalBodyClass); appendToElement.toggleClass(modalBodyClass, areAnyOpen); if (!areAnyOpen && scrollbarPadding && scrollbarPadding.heightOverflow && scrollbarPadding.scrollbarWidth) { if (scrollbarPadding.originalRight) { appendToElement.css({paddingRight: scrollbarPadding.originalRight + 'px'}); } else { appendToElement.css({paddingRight: ''}); } scrollbarPadding = null; } toggleTopWindowClass(true); }, modalWindow.closedDeferred); checkRemoveBackdrop(); //move focus to specified element if available, or else to body if (elementToReceiveFocus && elementToReceiveFocus.focus) { elementToReceiveFocus.focus(); } else if (appendToElement.focus) { appendToElement.focus(); } } // Add or remove "windowTopClass" from the top window in the stack function toggleTopWindowClass(toggleSwitch) { var modalWindow; if (openedWindows.length() > 0) { modalWindow = openedWindows.top().value; modalWindow.modalDomEl.toggleClass(modalWindow.windowTopClass || '', toggleSwitch); } } function checkRemoveBackdrop() { //remove backdrop if no longer needed if (backdropDomEl && backdropIndex() === -1) { var backdropScopeRef = backdropScope; removeAfterAnimate(backdropDomEl, backdropScope, function() { backdropScopeRef = null; }); backdropDomEl = undefined; backdropScope = undefined; } } function removeAfterAnimate(domEl, scope, done, closedDeferred) { var asyncDeferred; var asyncPromise = null; var setIsAsync = function() { if (!asyncDeferred) { asyncDeferred = $q.defer(); asyncPromise = asyncDeferred.promise; } return function asyncDone() { asyncDeferred.resolve(); }; }; scope.$broadcast($modalStack.NOW_CLOSING_EVENT, setIsAsync); // Note that it's intentional that asyncPromise might be null. // That's when setIsAsync has not been called during the // NOW_CLOSING_EVENT broadcast. return $q.when(asyncPromise).then(afterAnimating); function afterAnimating() { if (afterAnimating.done) { return; } afterAnimating.done = true; $animate.leave(domEl).then(function() { if (done) { done(); } domEl.remove(); if (closedDeferred) { closedDeferred.resolve(); } }); scope.$destroy(); } } $document.on('keydown', keydownListener); $rootScope.$on('$destroy', function() { $document.off('keydown', keydownListener); }); function keydownListener(evt) { if (evt.isDefaultPrevented()) { return evt; } var modal = openedWindows.top(); if (modal) { switch (evt.which) { case 27: { if (modal.value.keyboard) { evt.preventDefault(); $rootScope.$apply(function() { $modalStack.dismiss(modal.key, 'escape key press'); }); } break; } case 9: { var list = $modalStack.loadFocusElementList(modal); var focusChanged = false; if (evt.shiftKey) { if ($modalStack.isFocusInFirstItem(evt, list) || $modalStack.isModalFocused(evt, modal)) { focusChanged = $modalStack.focusLastFocusableElement(list); } } else { if ($modalStack.isFocusInLastItem(evt, list)) { focusChanged = $modalStack.focusFirstFocusableElement(list); } } if (focusChanged) { evt.preventDefault(); evt.stopPropagation(); } break; } } } } $modalStack.open = function(modalInstance, modal) { var modalOpener = $document[0].activeElement, modalBodyClass = modal.openedClass || OPENED_MODAL_CLASS; toggleTopWindowClass(false); // Store the current top first, to determine what index we ought to use // for the current top modal previousTopOpenedModal = openedWindows.top(); openedWindows.add(modalInstance, { deferred: modal.deferred, renderDeferred: modal.renderDeferred, closedDeferred: modal.closedDeferred, modalScope: modal.scope, backdrop: modal.backdrop, keyboard: modal.keyboard, openedClass: modal.openedClass, windowTopClass: modal.windowTopClass, animation: modal.animation, appendTo: modal.appendTo }); openedClasses.put(modalBodyClass, modalInstance); var appendToElement = modal.appendTo, currBackdropIndex = backdropIndex(); if (currBackdropIndex >= 0 && !backdropDomEl) { backdropScope = $rootScope.$new(true); backdropScope.modalOptions = modal; backdropScope.index = currBackdropIndex; backdropDomEl = angular.element('
'); backdropDomEl.attr({ 'class': 'modal-backdrop', 'ng-style': '{\'z-index\': 1040 + (index && 1 || 0) + index*10}', 'uib-modal-animation-class': 'fade', 'modal-in-class': 'in' }); if (modal.backdropClass) { backdropDomEl.addClass(modal.backdropClass); } if (modal.animation) { backdropDomEl.attr('modal-animation', 'true'); } $compile(backdropDomEl)(backdropScope); $animate.enter(backdropDomEl, appendToElement); if ($uibPosition.isScrollable(appendToElement)) { scrollbarPadding = $uibPosition.scrollbarPadding(appendToElement); if (scrollbarPadding.heightOverflow && scrollbarPadding.scrollbarWidth) { appendToElement.css({paddingRight: scrollbarPadding.right + 'px'}); } } } var content; if (modal.component) { content = document.createElement(snake_case(modal.component.name)); content = angular.element(content); content.attr({ resolve: '$resolve', 'modal-instance': '$uibModalInstance', close: '$close($value)', dismiss: '$dismiss($value)' }); } else { content = modal.content; } // Set the top modal index based on the index of the previous top modal topModalIndex = previousTopOpenedModal ? parseInt(previousTopOpenedModal.value.modalDomEl.attr('index'), 10) + 1 : 0; var angularDomEl = angular.element('
'); angularDomEl.attr({ 'class': 'modal', 'template-url': modal.windowTemplateUrl, 'window-top-class': modal.windowTopClass, 'role': 'dialog', 'aria-labelledby': modal.ariaLabelledBy, 'aria-describedby': modal.ariaDescribedBy, 'size': modal.size, 'index': topModalIndex, 'animate': 'animate', 'ng-style': '{\'z-index\': 1050 + $$topModalIndex*10, display: \'block\'}', 'tabindex': -1, 'uib-modal-animation-class': 'fade', 'modal-in-class': 'in' }).append(content); if (modal.windowClass) { angularDomEl.addClass(modal.windowClass); } if (modal.animation) { angularDomEl.attr('modal-animation', 'true'); } appendToElement.addClass(modalBodyClass); if (modal.scope) { // we need to explicitly add the modal index to the modal scope // because it is needed by ngStyle to compute the zIndex property. modal.scope.$$topModalIndex = topModalIndex; } $animate.enter($compile(angularDomEl)(modal.scope), appendToElement); openedWindows.top().value.modalDomEl = angularDomEl; openedWindows.top().value.modalOpener = modalOpener; applyAriaHidden(angularDomEl); function applyAriaHidden(el) { if (!el || el[0].tagName === 'BODY') { return; } getSiblings(el).forEach(function(sibling) { var elemIsAlreadyHidden = sibling.getAttribute('aria-hidden') === 'true', ariaHiddenCount = parseInt(sibling.getAttribute(ARIA_HIDDEN_ATTRIBUTE_NAME), 10); if (!ariaHiddenCount) { ariaHiddenCount = elemIsAlreadyHidden ? 1 : 0; } sibling.setAttribute(ARIA_HIDDEN_ATTRIBUTE_NAME, ariaHiddenCount + 1); sibling.setAttribute('aria-hidden', 'true'); }); return applyAriaHidden(el.parent()); function getSiblings(el) { var children = el.parent() ? el.parent().children() : []; return Array.prototype.filter.call(children, function(child) { return child !== el[0]; }); } } }; function broadcastClosing(modalWindow, resultOrReason, closing) { return !modalWindow.value.modalScope.$broadcast('modal.closing', resultOrReason, closing).defaultPrevented; } function unhideBackgroundElements() { Array.prototype.forEach.call( document.querySelectorAll('[' + ARIA_HIDDEN_ATTRIBUTE_NAME + ']'), function(hiddenEl) { var ariaHiddenCount = parseInt(hiddenEl.getAttribute(ARIA_HIDDEN_ATTRIBUTE_NAME), 10), newHiddenCount = ariaHiddenCount - 1; hiddenEl.setAttribute(ARIA_HIDDEN_ATTRIBUTE_NAME, newHiddenCount); if (!newHiddenCount) { hiddenEl.removeAttribute(ARIA_HIDDEN_ATTRIBUTE_NAME); hiddenEl.removeAttribute('aria-hidden'); } } ); } $modalStack.close = function(modalInstance, result) { var modalWindow = openedWindows.get(modalInstance); unhideBackgroundElements(); if (modalWindow && broadcastClosing(modalWindow, result, true)) { modalWindow.value.modalScope.$$uibDestructionScheduled = true; modalWindow.value.deferred.resolve(result); removeModalWindow(modalInstance, modalWindow.value.modalOpener); return true; } return !modalWindow; }; $modalStack.dismiss = function(modalInstance, reason) { var modalWindow = openedWindows.get(modalInstance); unhideBackgroundElements(); if (modalWindow && broadcastClosing(modalWindow, reason, false)) { modalWindow.value.modalScope.$$uibDestructionScheduled = true; modalWindow.value.deferred.reject(reason); removeModalWindow(modalInstance, modalWindow.value.modalOpener); return true; } return !modalWindow; }; $modalStack.dismissAll = function(reason) { var topModal = this.getTop(); while (topModal && this.dismiss(topModal.key, reason)) { topModal = this.getTop(); } }; $modalStack.getTop = function() { return openedWindows.top(); }; $modalStack.modalRendered = function(modalInstance) { var modalWindow = openedWindows.get(modalInstance); if (modalWindow) { modalWindow.value.renderDeferred.resolve(); } }; $modalStack.focusFirstFocusableElement = function(list) { if (list.length > 0) { list[0].focus(); return true; } return false; }; $modalStack.focusLastFocusableElement = function(list) { if (list.length > 0) { list[list.length - 1].focus(); return true; } return false; }; $modalStack.isModalFocused = function(evt, modalWindow) { if (evt && modalWindow) { var modalDomEl = modalWindow.value.modalDomEl; if (modalDomEl && modalDomEl.length) { return (evt.target || evt.srcElement) === modalDomEl[0]; } } return false; }; $modalStack.isFocusInFirstItem = function(evt, list) { if (list.length > 0) { return (evt.target || evt.srcElement) === list[0]; } return false; }; $modalStack.isFocusInLastItem = function(evt, list) { if (list.length > 0) { return (evt.target || evt.srcElement) === list[list.length - 1]; } return false; }; $modalStack.loadFocusElementList = function(modalWindow) { if (modalWindow) { var modalDomE1 = modalWindow.value.modalDomEl; if (modalDomE1 && modalDomE1.length) { var elements = modalDomE1[0].querySelectorAll(tabbableSelector); return elements ? Array.prototype.filter.call(elements, function(element) { return isVisible(element); }) : elements; } } }; return $modalStack; }]) .provider('$uibModal', function() { var $modalProvider = { options: { animation: true, backdrop: true, //can also be false or 'static' keyboard: true }, $get: ['$rootScope', '$q', '$document', '$templateRequest', '$controller', '$uibResolve', '$uibModalStack', function ($rootScope, $q, $document, $templateRequest, $controller, $uibResolve, $modalStack) { var $modal = {}; function getTemplatePromise(options) { return options.template ? $q.when(options.template) : $templateRequest(angular.isFunction(options.templateUrl) ? options.templateUrl() : options.templateUrl); } var promiseChain = null; $modal.getPromiseChain = function() { return promiseChain; }; $modal.open = function(modalOptions) { var modalResultDeferred = $q.defer(); var modalOpenedDeferred = $q.defer(); var modalClosedDeferred = $q.defer(); var modalRenderDeferred = $q.defer(); //prepare an instance of a modal to be injected into controllers and returned to a caller var modalInstance = { result: modalResultDeferred.promise, opened: modalOpenedDeferred.promise, closed: modalClosedDeferred.promise, rendered: modalRenderDeferred.promise, close: function (result) { return $modalStack.close(modalInstance, result); }, dismiss: function (reason) { return $modalStack.dismiss(modalInstance, reason); } }; //merge and clean up options modalOptions = angular.extend({}, $modalProvider.options, modalOptions); modalOptions.resolve = modalOptions.resolve || {}; modalOptions.appendTo = modalOptions.appendTo || $document.find('body').eq(0); if (!modalOptions.appendTo.length) { throw new Error('appendTo element not found. Make sure that the element passed is in DOM.'); } //verify options if (!modalOptions.component && !modalOptions.template && !modalOptions.templateUrl) { throw new Error('One of component or template or templateUrl options is required.'); } var templateAndResolvePromise; if (modalOptions.component) { templateAndResolvePromise = $q.when($uibResolve.resolve(modalOptions.resolve, {}, null, null)); } else { templateAndResolvePromise = $q.all([getTemplatePromise(modalOptions), $uibResolve.resolve(modalOptions.resolve, {}, null, null)]); } function resolveWithTemplate() { return templateAndResolvePromise; } // Wait for the resolution of the existing promise chain. // Then switch to our own combined promise dependency (regardless of how the previous modal fared). // Then add to $modalStack and resolve opened. // Finally clean up the chain variable if no subsequent modal has overwritten it. var samePromise; samePromise = promiseChain = $q.all([promiseChain]) .then(resolveWithTemplate, resolveWithTemplate) .then(function resolveSuccess(tplAndVars) { var providedScope = modalOptions.scope || $rootScope; var modalScope = providedScope.$new(); modalScope.$close = modalInstance.close; modalScope.$dismiss = modalInstance.dismiss; modalScope.$on('$destroy', function() { if (!modalScope.$$uibDestructionScheduled) { modalScope.$dismiss('$uibUnscheduledDestruction'); } }); var modal = { scope: modalScope, deferred: modalResultDeferred, renderDeferred: modalRenderDeferred, closedDeferred: modalClosedDeferred, animation: modalOptions.animation, backdrop: modalOptions.backdrop, keyboard: modalOptions.keyboard, backdropClass: modalOptions.backdropClass, windowTopClass: modalOptions.windowTopClass, windowClass: modalOptions.windowClass, windowTemplateUrl: modalOptions.windowTemplateUrl, ariaLabelledBy: modalOptions.ariaLabelledBy, ariaDescribedBy: modalOptions.ariaDescribedBy, size: modalOptions.size, openedClass: modalOptions.openedClass, appendTo: modalOptions.appendTo }; var component = {}; var ctrlInstance, ctrlInstantiate, ctrlLocals = {}; if (modalOptions.component) { constructLocals(component, false, true, false); component.name = modalOptions.component; modal.component = component; } else if (modalOptions.controller) { constructLocals(ctrlLocals, true, false, true); // the third param will make the controller instantiate later,private api // @see https://github.com/angular/angular.js/blob/master/src/ng/controller.js#L126 ctrlInstantiate = $controller(modalOptions.controller, ctrlLocals, true, modalOptions.controllerAs); if (modalOptions.controllerAs && modalOptions.bindToController) { ctrlInstance = ctrlInstantiate.instance; ctrlInstance.$close = modalScope.$close; ctrlInstance.$dismiss = modalScope.$dismiss; angular.extend(ctrlInstance, { $resolve: ctrlLocals.$scope.$resolve }, providedScope); } ctrlInstance = ctrlInstantiate(); if (angular.isFunction(ctrlInstance.$onInit)) { ctrlInstance.$onInit(); } } if (!modalOptions.component) { modal.content = tplAndVars[0]; } $modalStack.open(modalInstance, modal); modalOpenedDeferred.resolve(true); function constructLocals(obj, template, instanceOnScope, injectable) { obj.$scope = modalScope; obj.$scope.$resolve = {}; if (instanceOnScope) { obj.$scope.$uibModalInstance = modalInstance; } else { obj.$uibModalInstance = modalInstance; } var resolves = template ? tplAndVars[1] : tplAndVars; angular.forEach(resolves, function(value, key) { if (injectable) { obj[key] = value; } obj.$scope.$resolve[key] = value; }); } }, function resolveError(reason) { modalOpenedDeferred.reject(reason); modalResultDeferred.reject(reason); })['finally'](function() { if (promiseChain === samePromise) { promiseChain = null; } }); return modalInstance; }; return $modal; } ] }; return $modalProvider; }); angular.module('ui.bootstrap.paging', []) /** * Helper internal service for generating common controller code between the * pager and pagination components */ .factory('uibPaging', ['$parse', function($parse) { return { create: function(ctrl, $scope, $attrs) { ctrl.setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop; ctrl.ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl ctrl._watchers = []; ctrl.init = function(ngModelCtrl, config) { ctrl.ngModelCtrl = ngModelCtrl; ctrl.config = config; ngModelCtrl.$render = function() { ctrl.render(); }; if ($attrs.itemsPerPage) { ctrl._watchers.push($scope.$parent.$watch($attrs.itemsPerPage, function(value) { ctrl.itemsPerPage = parseInt(value, 10); $scope.totalPages = ctrl.calculateTotalPages(); ctrl.updatePage(); })); } else { ctrl.itemsPerPage = config.itemsPerPage; } $scope.$watch('totalItems', function(newTotal, oldTotal) { if (angular.isDefined(newTotal) || newTotal !== oldTotal) { $scope.totalPages = ctrl.calculateTotalPages(); ctrl.updatePage(); } }); }; ctrl.calculateTotalPages = function() { var totalPages = ctrl.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / ctrl.itemsPerPage); return Math.max(totalPages || 0, 1); }; ctrl.render = function() { $scope.page = parseInt(ctrl.ngModelCtrl.$viewValue, 10) || 1; }; $scope.selectPage = function(page, evt) { if (evt) { evt.preventDefault(); } var clickAllowed = !$scope.ngDisabled || !evt; if (clickAllowed && $scope.page !== page && page > 0 && page <= $scope.totalPages) { if (evt && evt.target) { evt.target.blur(); } ctrl.ngModelCtrl.$setViewValue(page); ctrl.ngModelCtrl.$render(); } }; $scope.getText = function(key) { return $scope[key + 'Text'] || ctrl.config[key + 'Text']; }; $scope.noPrevious = function() { return $scope.page === 1; }; $scope.noNext = function() { return $scope.page === $scope.totalPages; }; ctrl.updatePage = function() { ctrl.setNumPages($scope.$parent, $scope.totalPages); // Readonly variable if ($scope.page > $scope.totalPages) { $scope.selectPage($scope.totalPages); } else { ctrl.ngModelCtrl.$render(); } }; $scope.$on('$destroy', function() { while (ctrl._watchers.length) { ctrl._watchers.shift()(); } }); } }; }]); angular.module('ui.bootstrap.pager', ['ui.bootstrap.paging', 'ui.bootstrap.tabindex']) .controller('UibPagerController', ['$scope', '$attrs', 'uibPaging', 'uibPagerConfig', function($scope, $attrs, uibPaging, uibPagerConfig) { $scope.align = angular.isDefined($attrs.align) ? $scope.$parent.$eval($attrs.align) : uibPagerConfig.align; uibPaging.create(this, $scope, $attrs); }]) .constant('uibPagerConfig', { itemsPerPage: 10, previousText: '« Previous', nextText: 'Next »', align: true }) .directive('uibPager', ['uibPagerConfig', function(uibPagerConfig) { return { scope: { totalItems: '=', previousText: '@', nextText: '@', ngDisabled: '=' }, require: ['uibPager', '?ngModel'], restrict: 'A', controller: 'UibPagerController', controllerAs: 'pager', templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/pager/pager.html'; }, link: function(scope, element, attrs, ctrls) { element.addClass('pager'); var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; if (!ngModelCtrl) { return; // do nothing if no ng-model } paginationCtrl.init(ngModelCtrl, uibPagerConfig); } }; }]); angular.module('ui.bootstrap.pagination', ['ui.bootstrap.paging', 'ui.bootstrap.tabindex']) .controller('UibPaginationController', ['$scope', '$attrs', '$parse', 'uibPaging', 'uibPaginationConfig', function($scope, $attrs, $parse, uibPaging, uibPaginationConfig) { var ctrl = this; // Setup configuration parameters var maxSize = angular.isDefined($attrs.maxSize) ? $scope.$parent.$eval($attrs.maxSize) : uibPaginationConfig.maxSize, rotate = angular.isDefined($attrs.rotate) ? $scope.$parent.$eval($attrs.rotate) : uibPaginationConfig.rotate, forceEllipses = angular.isDefined($attrs.forceEllipses) ? $scope.$parent.$eval($attrs.forceEllipses) : uibPaginationConfig.forceEllipses, boundaryLinkNumbers = angular.isDefined($attrs.boundaryLinkNumbers) ? $scope.$parent.$eval($attrs.boundaryLinkNumbers) : uibPaginationConfig.boundaryLinkNumbers, pageLabel = angular.isDefined($attrs.pageLabel) ? function(idx) { return $scope.$parent.$eval($attrs.pageLabel, {$page: idx}); } : angular.identity; $scope.boundaryLinks = angular.isDefined($attrs.boundaryLinks) ? $scope.$parent.$eval($attrs.boundaryLinks) : uibPaginationConfig.boundaryLinks; $scope.directionLinks = angular.isDefined($attrs.directionLinks) ? $scope.$parent.$eval($attrs.directionLinks) : uibPaginationConfig.directionLinks; $attrs.$set('role', 'menu'); uibPaging.create(this, $scope, $attrs); if ($attrs.maxSize) { ctrl._watchers.push($scope.$parent.$watch($parse($attrs.maxSize), function(value) { maxSize = parseInt(value, 10); ctrl.render(); })); } // Create page object used in template function makePage(number, text, isActive) { return { number: number, text: text, active: isActive }; } function getPages(currentPage, totalPages) { var pages = []; // Default page limits var startPage = 1, endPage = totalPages; var isMaxSized = angular.isDefined(maxSize) && maxSize < totalPages; // recompute if maxSize if (isMaxSized) { if (rotate) { // Current page is displayed in the middle of the visible ones startPage = Math.max(currentPage - Math.floor(maxSize / 2), 1); endPage = startPage + maxSize - 1; // Adjust if limit is exceeded if (endPage > totalPages) { endPage = totalPages; startPage = endPage - maxSize + 1; } } else { // Visible pages are paginated with maxSize startPage = (Math.ceil(currentPage / maxSize) - 1) * maxSize + 1; // Adjust last page if limit is exceeded endPage = Math.min(startPage + maxSize - 1, totalPages); } } // Add page number links for (var number = startPage; number <= endPage; number++) { var page = makePage(number, pageLabel(number), number === currentPage); pages.push(page); } // Add links to move between page sets if (isMaxSized && maxSize > 0 && (!rotate || forceEllipses || boundaryLinkNumbers)) { if (startPage > 1) { if (!boundaryLinkNumbers || startPage > 3) { //need ellipsis for all options unless range is too close to beginning var previousPageSet = makePage(startPage - 1, '...', false); pages.unshift(previousPageSet); } if (boundaryLinkNumbers) { if (startPage === 3) { //need to replace ellipsis when the buttons would be sequential var secondPageLink = makePage(2, '2', false); pages.unshift(secondPageLink); } //add the first page var firstPageLink = makePage(1, '1', false); pages.unshift(firstPageLink); } } if (endPage < totalPages) { if (!boundaryLinkNumbers || endPage < totalPages - 2) { //need ellipsis for all options unless range is too close to end var nextPageSet = makePage(endPage + 1, '...', false); pages.push(nextPageSet); } if (boundaryLinkNumbers) { if (endPage === totalPages - 2) { //need to replace ellipsis when the buttons would be sequential var secondToLastPageLink = makePage(totalPages - 1, totalPages - 1, false); pages.push(secondToLastPageLink); } //add the last page var lastPageLink = makePage(totalPages, totalPages, false); pages.push(lastPageLink); } } } return pages; } var originalRender = this.render; this.render = function() { originalRender(); if ($scope.page > 0 && $scope.page <= $scope.totalPages) { $scope.pages = getPages($scope.page, $scope.totalPages); } }; }]) .constant('uibPaginationConfig', { itemsPerPage: 10, boundaryLinks: false, boundaryLinkNumbers: false, directionLinks: true, firstText: 'First', previousText: 'Previous', nextText: 'Next', lastText: 'Last', rotate: true, forceEllipses: false }) .directive('uibPagination', ['$parse', 'uibPaginationConfig', function($parse, uibPaginationConfig) { return { scope: { totalItems: '=', firstText: '@', previousText: '@', nextText: '@', lastText: '@', ngDisabled:'=' }, require: ['uibPagination', '?ngModel'], restrict: 'A', controller: 'UibPaginationController', controllerAs: 'pagination', templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/pagination/pagination.html'; }, link: function(scope, element, attrs, ctrls) { element.addClass('pagination'); var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; if (!ngModelCtrl) { return; // do nothing if no ng-model } paginationCtrl.init(ngModelCtrl, uibPaginationConfig); } }; }]); /** * The following features are still outstanding: animation as a * function, placement as a function, inside, support for more triggers than * just mouse enter/leave, html tooltips, and selector delegation. */ angular.module('ui.bootstrap.tooltip', ['ui.bootstrap.position', 'ui.bootstrap.stackedMap']) /** * The $tooltip service creates tooltip- and popover-like directives as well as * houses global options for them. */ .provider('$uibTooltip', function() { // The default options tooltip and popover. var defaultOptions = { placement: 'top', placementClassPrefix: '', animation: true, popupDelay: 0, popupCloseDelay: 0, useContentExp: false }; // Default hide triggers for each show trigger var triggerMap = { 'mouseenter': 'mouseleave', 'click': 'click', 'outsideClick': 'outsideClick', 'focus': 'blur', 'none': '' }; // The options specified to the provider globally. var globalOptions = {}; /** * `options({})` allows global configuration of all tooltips in the * application. * * var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) { * // place tooltips left instead of top by default * $tooltipProvider.options( { placement: 'left' } ); * }); */ this.options = function(value) { angular.extend(globalOptions, value); }; /** * This allows you to extend the set of trigger mappings available. E.g.: * * $tooltipProvider.setTriggers( { 'openTrigger': 'closeTrigger' } ); */ this.setTriggers = function setTriggers(triggers) { angular.extend(triggerMap, triggers); }; /** * This is a helper function for translating camel-case to snake_case. */ function snake_case(name) { var regexp = /[A-Z]/g; var separator = '-'; return name.replace(regexp, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } /** * Returns the actual instance of the $tooltip service. * TODO support multiple triggers */ this.$get = ['$window', '$compile', '$timeout', '$document', '$uibPosition', '$interpolate', '$rootScope', '$parse', '$$stackedMap', function($window, $compile, $timeout, $document, $position, $interpolate, $rootScope, $parse, $$stackedMap) { var openedTooltips = $$stackedMap.createNew(); $document.on('keyup', keypressListener); $rootScope.$on('$destroy', function() { $document.off('keyup', keypressListener); }); function keypressListener(e) { if (e.which === 27) { var last = openedTooltips.top(); if (last) { last.value.close(); last = null; } } } return function $tooltip(ttType, prefix, defaultTriggerShow, options) { options = angular.extend({}, defaultOptions, globalOptions, options); /** * Returns an object of show and hide triggers. * * If a trigger is supplied, * it is used to show the tooltip; otherwise, it will use the `trigger` * option passed to the `$tooltipProvider.options` method; else it will * default to the trigger supplied to this directive factory. * * The hide trigger is based on the show trigger. If the `trigger` option * was passed to the `$tooltipProvider.options` method, it will use the * mapped trigger from `triggerMap` or the passed trigger if the map is * undefined; otherwise, it uses the `triggerMap` value of the show * trigger; else it will just use the show trigger. */ function getTriggers(trigger) { var show = (trigger || options.trigger || defaultTriggerShow).split(' '); var hide = show.map(function(trigger) { return triggerMap[trigger] || trigger; }); return { show: show, hide: hide }; } var directiveName = snake_case(ttType); var startSym = $interpolate.startSymbol(); var endSym = $interpolate.endSymbol(); var template = '
' + '
'; return { compile: function(tElem, tAttrs) { var tooltipLinker = $compile(template); return function link(scope, element, attrs, tooltipCtrl) { var tooltip; var tooltipLinkedScope; var transitionTimeout; var showTimeout; var hideTimeout; var positionTimeout; var adjustmentTimeout; var appendToBody = angular.isDefined(options.appendToBody) ? options.appendToBody : false; var triggers = getTriggers(undefined); var hasEnableExp = angular.isDefined(attrs[prefix + 'Enable']); var ttScope = scope.$new(true); var repositionScheduled = false; var isOpenParse = angular.isDefined(attrs[prefix + 'IsOpen']) ? $parse(attrs[prefix + 'IsOpen']) : false; var contentParse = options.useContentExp ? $parse(attrs[ttType]) : false; var observers = []; var lastPlacement; var positionTooltip = function() { // check if tooltip exists and is not empty if (!tooltip || !tooltip.html()) { return; } if (!positionTimeout) { positionTimeout = $timeout(function() { var ttPosition = $position.positionElements(element, tooltip, ttScope.placement, appendToBody); var initialHeight = angular.isDefined(tooltip.offsetHeight) ? tooltip.offsetHeight : tooltip.prop('offsetHeight'); var elementPos = appendToBody ? $position.offset(element) : $position.position(element); tooltip.css({ top: ttPosition.top + 'px', left: ttPosition.left + 'px' }); var placementClasses = ttPosition.placement.split('-'); if (!tooltip.hasClass(placementClasses[0])) { tooltip.removeClass(lastPlacement.split('-')[0]); tooltip.addClass(placementClasses[0]); } if (!tooltip.hasClass(options.placementClassPrefix + ttPosition.placement)) { tooltip.removeClass(options.placementClassPrefix + lastPlacement); tooltip.addClass(options.placementClassPrefix + ttPosition.placement); } adjustmentTimeout = $timeout(function() { var currentHeight = angular.isDefined(tooltip.offsetHeight) ? tooltip.offsetHeight : tooltip.prop('offsetHeight'); var adjustment = $position.adjustTop(placementClasses, elementPos, initialHeight, currentHeight); if (adjustment) { tooltip.css(adjustment); } adjustmentTimeout = null; }, 0, false); // first time through tt element will have the // uib-position-measure class or if the placement // has changed we need to position the arrow. if (tooltip.hasClass('uib-position-measure')) { $position.positionArrow(tooltip, ttPosition.placement); tooltip.removeClass('uib-position-measure'); } else if (lastPlacement !== ttPosition.placement) { $position.positionArrow(tooltip, ttPosition.placement); } lastPlacement = ttPosition.placement; positionTimeout = null; }, 0, false); } }; // Set up the correct scope to allow transclusion later ttScope.origScope = scope; // By default, the tooltip is not open. // TODO add ability to start tooltip opened ttScope.isOpen = false; function toggleTooltipBind() { if (!ttScope.isOpen) { showTooltipBind(); } else { hideTooltipBind(); } } // Show the tooltip with delay if specified, otherwise show it immediately function showTooltipBind() { if (hasEnableExp && !scope.$eval(attrs[prefix + 'Enable'])) { return; } cancelHide(); prepareTooltip(); if (ttScope.popupDelay) { // Do nothing if the tooltip was already scheduled to pop-up. // This happens if show is triggered multiple times before any hide is triggered. if (!showTimeout) { showTimeout = $timeout(show, ttScope.popupDelay, false); } } else { show(); } } function hideTooltipBind() { cancelShow(); if (ttScope.popupCloseDelay) { if (!hideTimeout) { hideTimeout = $timeout(hide, ttScope.popupCloseDelay, false); } } else { hide(); } } // Show the tooltip popup element. function show() { cancelShow(); cancelHide(); // Don't show empty tooltips. if (!ttScope.content) { return angular.noop; } createTooltip(); // And show the tooltip. ttScope.$evalAsync(function() { ttScope.isOpen = true; assignIsOpen(true); positionTooltip(); }); } function cancelShow() { if (showTimeout) { $timeout.cancel(showTimeout); showTimeout = null; } if (positionTimeout) { $timeout.cancel(positionTimeout); positionTimeout = null; } } // Hide the tooltip popup element. function hide() { if (!ttScope) { return; } // First things first: we don't show it anymore. ttScope.$evalAsync(function() { if (ttScope) { ttScope.isOpen = false; assignIsOpen(false); // And now we remove it from the DOM. However, if we have animation, we // need to wait for it to expire beforehand. // FIXME: this is a placeholder for a port of the transitions library. // The fade transition in TWBS is 150ms. if (ttScope.animation) { if (!transitionTimeout) { transitionTimeout = $timeout(removeTooltip, 150, false); } } else { removeTooltip(); } } }); } function cancelHide() { if (hideTimeout) { $timeout.cancel(hideTimeout); hideTimeout = null; } if (transitionTimeout) { $timeout.cancel(transitionTimeout); transitionTimeout = null; } } function createTooltip() { // There can only be one tooltip element per directive shown at once. if (tooltip) { return; } tooltipLinkedScope = ttScope.$new(); tooltip = tooltipLinker(tooltipLinkedScope, function(tooltip) { if (appendToBody) { $document.find('body').append(tooltip); } else { element.after(tooltip); } }); openedTooltips.add(ttScope, { close: hide }); prepObservers(); } function removeTooltip() { cancelShow(); cancelHide(); unregisterObservers(); if (tooltip) { tooltip.remove(); tooltip = null; if (adjustmentTimeout) { $timeout.cancel(adjustmentTimeout); } } openedTooltips.remove(ttScope); if (tooltipLinkedScope) { tooltipLinkedScope.$destroy(); tooltipLinkedScope = null; } } /** * Set the initial scope values. Once * the tooltip is created, the observers * will be added to keep things in sync. */ function prepareTooltip() { ttScope.title = attrs[prefix + 'Title']; if (contentParse) { ttScope.content = contentParse(scope); } else { ttScope.content = attrs[ttType]; } ttScope.popupClass = attrs[prefix + 'Class']; ttScope.placement = angular.isDefined(attrs[prefix + 'Placement']) ? attrs[prefix + 'Placement'] : options.placement; var placement = $position.parsePlacement(ttScope.placement); lastPlacement = placement[1] ? placement[0] + '-' + placement[1] : placement[0]; var delay = parseInt(attrs[prefix + 'PopupDelay'], 10); var closeDelay = parseInt(attrs[prefix + 'PopupCloseDelay'], 10); ttScope.popupDelay = !isNaN(delay) ? delay : options.popupDelay; ttScope.popupCloseDelay = !isNaN(closeDelay) ? closeDelay : options.popupCloseDelay; } function assignIsOpen(isOpen) { if (isOpenParse && angular.isFunction(isOpenParse.assign)) { isOpenParse.assign(scope, isOpen); } } ttScope.contentExp = function() { return ttScope.content; }; /** * Observe the relevant attributes. */ attrs.$observe('disabled', function(val) { if (val) { cancelShow(); } if (val && ttScope.isOpen) { hide(); } }); if (isOpenParse) { scope.$watch(isOpenParse, function(val) { if (ttScope && !val === ttScope.isOpen) { toggleTooltipBind(); } }); } function prepObservers() { observers.length = 0; if (contentParse) { observers.push( scope.$watch(contentParse, function(val) { ttScope.content = val; if (!val && ttScope.isOpen) { hide(); } }) ); observers.push( tooltipLinkedScope.$watch(function() { if (!repositionScheduled) { repositionScheduled = true; tooltipLinkedScope.$$postDigest(function() { repositionScheduled = false; if (ttScope && ttScope.isOpen) { positionTooltip(); } }); } }) ); } else { observers.push( attrs.$observe(ttType, function(val) { ttScope.content = val; if (!val && ttScope.isOpen) { hide(); } else { positionTooltip(); } }) ); } observers.push( attrs.$observe(prefix + 'Title', function(val) { ttScope.title = val; if (ttScope.isOpen) { positionTooltip(); } }) ); observers.push( attrs.$observe(prefix + 'Placement', function(val) { ttScope.placement = val ? val : options.placement; if (ttScope.isOpen) { positionTooltip(); } }) ); } function unregisterObservers() { if (observers.length) { angular.forEach(observers, function(observer) { observer(); }); observers.length = 0; } } // hide tooltips/popovers for outsideClick trigger function bodyHideTooltipBind(e) { if (!ttScope || !ttScope.isOpen || !tooltip) { return; } // make sure the tooltip/popover link or tool tooltip/popover itself were not clicked if (!element[0].contains(e.target) && !tooltip[0].contains(e.target)) { hideTooltipBind(); } } // KeyboardEvent handler to hide the tooltip on Escape key press function hideOnEscapeKey(e) { if (e.which === 27) { hideTooltipBind(); } } var unregisterTriggers = function() { triggers.show.forEach(function(trigger) { if (trigger === 'outsideClick') { element.off('click', toggleTooltipBind); } else { element.off(trigger, showTooltipBind); element.off(trigger, toggleTooltipBind); } element.off('keypress', hideOnEscapeKey); }); triggers.hide.forEach(function(trigger) { if (trigger === 'outsideClick') { $document.off('click', bodyHideTooltipBind); } else { element.off(trigger, hideTooltipBind); } }); }; function prepTriggers() { var showTriggers = [], hideTriggers = []; var val = scope.$eval(attrs[prefix + 'Trigger']); unregisterTriggers(); if (angular.isObject(val)) { Object.keys(val).forEach(function(key) { showTriggers.push(key); hideTriggers.push(val[key]); }); triggers = { show: showTriggers, hide: hideTriggers }; } else { triggers = getTriggers(val); } if (triggers.show !== 'none') { triggers.show.forEach(function(trigger, idx) { if (trigger === 'outsideClick') { element.on('click', toggleTooltipBind); $document.on('click', bodyHideTooltipBind); } else if (trigger === triggers.hide[idx]) { element.on(trigger, toggleTooltipBind); } else if (trigger) { element.on(trigger, showTooltipBind); element.on(triggers.hide[idx], hideTooltipBind); } element.on('keypress', hideOnEscapeKey); }); } } prepTriggers(); var animation = scope.$eval(attrs[prefix + 'Animation']); ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation; var appendToBodyVal; var appendKey = prefix + 'AppendToBody'; if (appendKey in attrs && attrs[appendKey] === undefined) { appendToBodyVal = true; } else { appendToBodyVal = scope.$eval(attrs[appendKey]); } appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody; // Make sure tooltip is destroyed and removed. scope.$on('$destroy', function onDestroyTooltip() { unregisterTriggers(); removeTooltip(); ttScope = null; }); }; } }; }; }]; }) // This is mostly ngInclude code but with a custom scope .directive('uibTooltipTemplateTransclude', [ '$animate', '$sce', '$compile', '$templateRequest', function ($animate, $sce, $compile, $templateRequest) { return { link: function(scope, elem, attrs) { var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope); var changeCounter = 0, currentScope, previousElement, currentElement; var cleanupLastIncludeContent = function() { if (previousElement) { previousElement.remove(); previousElement = null; } if (currentScope) { currentScope.$destroy(); currentScope = null; } if (currentElement) { $animate.leave(currentElement).then(function() { previousElement = null; }); previousElement = currentElement; currentElement = null; } }; scope.$watch($sce.parseAsResourceUrl(attrs.uibTooltipTemplateTransclude), function(src) { var thisChangeId = ++changeCounter; if (src) { //set the 2nd param to true to ignore the template request error so that the inner //contents and scope can be cleaned up. $templateRequest(src, true).then(function(response) { if (thisChangeId !== changeCounter) { return; } var newScope = origScope.$new(); var template = response; var clone = $compile(template)(newScope, function(clone) { cleanupLastIncludeContent(); $animate.enter(clone, elem); }); currentScope = newScope; currentElement = clone; currentScope.$emit('$includeContentLoaded', src); }, function() { if (thisChangeId === changeCounter) { cleanupLastIncludeContent(); scope.$emit('$includeContentError', src); } }); scope.$emit('$includeContentRequested', src); } else { cleanupLastIncludeContent(); } }); scope.$on('$destroy', cleanupLastIncludeContent); } }; }]) /** * Note that it's intentional that these classes are *not* applied through $animate. * They must not be animated as they're expected to be present on the tooltip on * initialization. */ .directive('uibTooltipClasses', ['$uibPosition', function($uibPosition) { return { restrict: 'A', link: function(scope, element, attrs) { // need to set the primary position so the // arrow has space during position measure. // tooltip.positionTooltip() if (scope.placement) { // // There are no top-left etc... classes // // in TWBS, so we need the primary position. var position = $uibPosition.parsePlacement(scope.placement); element.addClass(position[0]); } if (scope.popupClass) { element.addClass(scope.popupClass); } if (scope.animation) { element.addClass(attrs.tooltipAnimationClass); } } }; }]) .directive('uibTooltipPopup', function() { return { restrict: 'A', scope: { content: '@' }, templateUrl: 'uib/template/tooltip/tooltip-popup.html' }; }) .directive('uibTooltip', [ '$uibTooltip', function($uibTooltip) { return $uibTooltip('uibTooltip', 'tooltip', 'mouseenter'); }]) .directive('uibTooltipTemplatePopup', function() { return { restrict: 'A', scope: { contentExp: '&', originScope: '&' }, templateUrl: 'uib/template/tooltip/tooltip-template-popup.html' }; }) .directive('uibTooltipTemplate', ['$uibTooltip', function($uibTooltip) { return $uibTooltip('uibTooltipTemplate', 'tooltip', 'mouseenter', { useContentExp: true }); }]) .directive('uibTooltipHtmlPopup', function() { return { restrict: 'A', scope: { contentExp: '&' }, templateUrl: 'uib/template/tooltip/tooltip-html-popup.html' }; }) .directive('uibTooltipHtml', ['$uibTooltip', function($uibTooltip) { return $uibTooltip('uibTooltipHtml', 'tooltip', 'mouseenter', { useContentExp: true }); }]); /** * The following features are still outstanding: popup delay, animation as a * function, placement as a function, inside, support for more triggers than * just mouse enter/leave, and selector delegatation. */ angular.module('ui.bootstrap.popover', ['ui.bootstrap.tooltip']) .directive('uibPopoverTemplatePopup', function() { return { restrict: 'A', scope: { uibTitle: '@', contentExp: '&', originScope: '&' }, templateUrl: 'uib/template/popover/popover-template.html' }; }) .directive('uibPopoverTemplate', ['$uibTooltip', function($uibTooltip) { return $uibTooltip('uibPopoverTemplate', 'popover', 'click', { useContentExp: true }); }]) .directive('uibPopoverHtmlPopup', function() { return { restrict: 'A', scope: { contentExp: '&', uibTitle: '@' }, templateUrl: 'uib/template/popover/popover-html.html' }; }) .directive('uibPopoverHtml', ['$uibTooltip', function($uibTooltip) { return $uibTooltip('uibPopoverHtml', 'popover', 'click', { useContentExp: true }); }]) .directive('uibPopoverPopup', function() { return { restrict: 'A', scope: { uibTitle: '@', content: '@' }, templateUrl: 'uib/template/popover/popover.html' }; }) .directive('uibPopover', ['$uibTooltip', function($uibTooltip) { return $uibTooltip('uibPopover', 'popover', 'click'); }]); angular.module('ui.bootstrap.progressbar', []) .constant('uibProgressConfig', { animate: true, max: 100 }) .controller('UibProgressController', ['$scope', '$attrs', 'uibProgressConfig', function($scope, $attrs, progressConfig) { var self = this, animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate; this.bars = []; $scope.max = getMaxOrDefault(); this.addBar = function(bar, element, attrs) { if (!animate) { element.css({'transition': 'none'}); } this.bars.push(bar); bar.max = getMaxOrDefault(); bar.title = attrs && angular.isDefined(attrs.title) ? attrs.title : 'progressbar'; bar.$watch('value', function(value) { bar.recalculatePercentage(); }); bar.recalculatePercentage = function() { var totalPercentage = self.bars.reduce(function(total, bar) { bar.percent = +(100 * bar.value / bar.max).toFixed(2); return total + bar.percent; }, 0); if (totalPercentage > 100) { bar.percent -= totalPercentage - 100; } }; bar.$on('$destroy', function() { element = null; self.removeBar(bar); }); }; this.removeBar = function(bar) { this.bars.splice(this.bars.indexOf(bar), 1); this.bars.forEach(function (bar) { bar.recalculatePercentage(); }); }; //$attrs.$observe('maxParam', function(maxParam) { $scope.$watch('maxParam', function(maxParam) { self.bars.forEach(function(bar) { bar.max = getMaxOrDefault(); bar.recalculatePercentage(); }); }); function getMaxOrDefault () { return angular.isDefined($scope.maxParam) ? $scope.maxParam : progressConfig.max; } }]) .directive('uibProgress', function() { return { replace: true, transclude: true, controller: 'UibProgressController', require: 'uibProgress', scope: { maxParam: '=?max' }, templateUrl: 'uib/template/progressbar/progress.html' }; }) .directive('uibBar', function() { return { replace: true, transclude: true, require: '^uibProgress', scope: { value: '=', type: '@' }, templateUrl: 'uib/template/progressbar/bar.html', link: function(scope, element, attrs, progressCtrl) { progressCtrl.addBar(scope, element, attrs); } }; }) .directive('uibProgressbar', function() { return { replace: true, transclude: true, controller: 'UibProgressController', scope: { value: '=', maxParam: '=?max', type: '@' }, templateUrl: 'uib/template/progressbar/progressbar.html', link: function(scope, element, attrs, progressCtrl) { progressCtrl.addBar(scope, angular.element(element.children()[0]), {title: attrs.title}); } }; }); angular.module('ui.bootstrap.rating', []) .constant('uibRatingConfig', { max: 5, stateOn: null, stateOff: null, enableReset: true, titles: ['one', 'two', 'three', 'four', 'five'] }) .controller('UibRatingController', ['$scope', '$attrs', 'uibRatingConfig', function($scope, $attrs, ratingConfig) { var ngModelCtrl = { $setViewValue: angular.noop }, self = this; this.init = function(ngModelCtrl_) { ngModelCtrl = ngModelCtrl_; ngModelCtrl.$render = this.render; ngModelCtrl.$formatters.push(function(value) { if (angular.isNumber(value) && value << 0 !== value) { value = Math.round(value); } return value; }); this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn; this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff; this.enableReset = angular.isDefined($attrs.enableReset) ? $scope.$parent.$eval($attrs.enableReset) : ratingConfig.enableReset; var tmpTitles = angular.isDefined($attrs.titles) ? $scope.$parent.$eval($attrs.titles) : ratingConfig.titles; this.titles = angular.isArray(tmpTitles) && tmpTitles.length > 0 ? tmpTitles : ratingConfig.titles; var ratingStates = angular.isDefined($attrs.ratingStates) ? $scope.$parent.$eval($attrs.ratingStates) : new Array(angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max); $scope.range = this.buildTemplateObjects(ratingStates); }; this.buildTemplateObjects = function(states) { for (var i = 0, n = states.length; i < n; i++) { states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff, title: this.getTitle(i) }, states[i]); } return states; }; this.getTitle = function(index) { if (index >= this.titles.length) { return index + 1; } return this.titles[index]; }; $scope.rate = function(value) { if (!$scope.readonly && value >= 0 && value <= $scope.range.length) { var newViewValue = self.enableReset && ngModelCtrl.$viewValue === value ? 0 : value; ngModelCtrl.$setViewValue(newViewValue); ngModelCtrl.$render(); } }; $scope.enter = function(value) { if (!$scope.readonly) { $scope.value = value; } $scope.onHover({value: value}); }; $scope.reset = function() { $scope.value = ngModelCtrl.$viewValue; $scope.onLeave(); }; $scope.onKeydown = function(evt) { if (/(37|38|39|40)/.test(evt.which)) { evt.preventDefault(); evt.stopPropagation(); $scope.rate($scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1)); } }; this.render = function() { $scope.value = ngModelCtrl.$viewValue; $scope.title = self.getTitle($scope.value - 1); }; }]) .directive('uibRating', function() { return { require: ['uibRating', 'ngModel'], restrict: 'A', scope: { readonly: '=?readOnly', onHover: '&', onLeave: '&' }, controller: 'UibRatingController', templateUrl: 'uib/template/rating/rating.html', link: function(scope, element, attrs, ctrls) { var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1]; ratingCtrl.init(ngModelCtrl); } }; }); angular.module('ui.bootstrap.tabs', []) .controller('UibTabsetController', ['$scope', function ($scope) { var ctrl = this, oldIndex; ctrl.tabs = []; ctrl.select = function(index, evt) { if (!destroyed) { var previousIndex = findTabIndex(oldIndex); var previousSelected = ctrl.tabs[previousIndex]; if (previousSelected) { previousSelected.tab.onDeselect({ $event: evt, $selectedIndex: index }); if (evt && evt.isDefaultPrevented()) { return; } previousSelected.tab.active = false; } var selected = ctrl.tabs[index]; if (selected) { selected.tab.onSelect({ $event: evt }); selected.tab.active = true; ctrl.active = selected.index; oldIndex = selected.index; } else if (!selected && angular.isDefined(oldIndex)) { ctrl.active = null; oldIndex = null; } } }; ctrl.addTab = function addTab(tab) { ctrl.tabs.push({ tab: tab, index: tab.index }); ctrl.tabs.sort(function(t1, t2) { if (t1.index > t2.index) { return 1; } if (t1.index < t2.index) { return -1; } return 0; }); if (tab.index === ctrl.active || !angular.isDefined(ctrl.active) && ctrl.tabs.length === 1) { var newActiveIndex = findTabIndex(tab.index); ctrl.select(newActiveIndex); } }; ctrl.removeTab = function removeTab(tab) { var index; for (var i = 0; i < ctrl.tabs.length; i++) { if (ctrl.tabs[i].tab === tab) { index = i; break; } } if (ctrl.tabs[index].index === ctrl.active) { var newActiveTabIndex = index === ctrl.tabs.length - 1 ? index - 1 : index + 1 % ctrl.tabs.length; ctrl.select(newActiveTabIndex); } ctrl.tabs.splice(index, 1); }; $scope.$watch('tabset.active', function(val) { if (angular.isDefined(val) && val !== oldIndex) { ctrl.select(findTabIndex(val)); } }); var destroyed; $scope.$on('$destroy', function() { destroyed = true; }); function findTabIndex(index) { for (var i = 0; i < ctrl.tabs.length; i++) { if (ctrl.tabs[i].index === index) { return i; } } } }]) .directive('uibTabset', function() { return { transclude: true, replace: true, scope: {}, bindToController: { active: '=?', type: '@' }, controller: 'UibTabsetController', controllerAs: 'tabset', templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/tabs/tabset.html'; }, link: function(scope, element, attrs) { scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false; scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false; } }; }) .directive('uibTab', ['$parse', function($parse) { return { require: '^uibTabset', replace: true, templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/tabs/tab.html'; }, transclude: true, scope: { heading: '@', index: '=?', classes: '@?', onSelect: '&select', //This callback is called in contentHeadingTransclude //once it inserts the tab's content into the dom onDeselect: '&deselect' }, controller: function() { //Empty controller so other directives can require being 'under' a tab }, controllerAs: 'tab', link: function(scope, elm, attrs, tabsetCtrl, transclude) { scope.disabled = false; if (attrs.disable) { scope.$parent.$watch($parse(attrs.disable), function(value) { scope.disabled = !! value; }); } if (angular.isUndefined(attrs.index)) { if (tabsetCtrl.tabs && tabsetCtrl.tabs.length) { scope.index = Math.max.apply(null, tabsetCtrl.tabs.map(function(t) { return t.index; })) + 1; } else { scope.index = 0; } } if (angular.isUndefined(attrs.classes)) { scope.classes = ''; } scope.select = function(evt) { if (!scope.disabled) { var index; for (var i = 0; i < tabsetCtrl.tabs.length; i++) { if (tabsetCtrl.tabs[i].tab === scope) { index = i; break; } } tabsetCtrl.select(index, evt); } }; tabsetCtrl.addTab(scope); scope.$on('$destroy', function() { tabsetCtrl.removeTab(scope); }); //We need to transclude later, once the content container is ready. //when this link happens, we're inside a tab heading. scope.$transcludeFn = transclude; } }; }]) .directive('uibTabHeadingTransclude', function() { return { restrict: 'A', require: '^uibTab', link: function(scope, elm) { scope.$watch('headingElement', function updateHeadingElement(heading) { if (heading) { elm.html(''); elm.append(heading); } }); } }; }) .directive('uibTabContentTransclude', function() { return { restrict: 'A', require: '^uibTabset', link: function(scope, elm, attrs) { var tab = scope.$eval(attrs.uibTabContentTransclude).tab; //Now our tab is ready to be transcluded: both the tab heading area //and the tab content area are loaded. Transclude 'em both. tab.$transcludeFn(tab.$parent, function(contents) { angular.forEach(contents, function(node) { if (isTabHeading(node)) { //Let tabHeadingTransclude know. tab.headingElement = node; } else { elm.append(node); } }); }); } }; function isTabHeading(node) { return node.tagName && ( node.hasAttribute('uib-tab-heading') || node.hasAttribute('data-uib-tab-heading') || node.hasAttribute('x-uib-tab-heading') || node.tagName.toLowerCase() === 'uib-tab-heading' || node.tagName.toLowerCase() === 'data-uib-tab-heading' || node.tagName.toLowerCase() === 'x-uib-tab-heading' || node.tagName.toLowerCase() === 'uib:tab-heading' ); } }); angular.module('ui.bootstrap.timepicker', []) .constant('uibTimepickerConfig', { hourStep: 1, minuteStep: 1, secondStep: 1, showMeridian: true, showSeconds: false, meridians: null, readonlyInput: false, mousewheel: true, arrowkeys: true, showSpinners: true, templateUrl: 'uib/template/timepicker/timepicker.html' }) .controller('UibTimepickerController', ['$scope', '$element', '$attrs', '$parse', '$log', '$locale', 'uibTimepickerConfig', function($scope, $element, $attrs, $parse, $log, $locale, timepickerConfig) { var hoursModelCtrl, minutesModelCtrl, secondsModelCtrl; var selected = new Date(), watchers = [], ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS, padHours = angular.isDefined($attrs.padHours) ? $scope.$parent.$eval($attrs.padHours) : true; $scope.tabindex = angular.isDefined($attrs.tabindex) ? $attrs.tabindex : 0; $element.removeAttr('tabindex'); this.init = function(ngModelCtrl_, inputs) { ngModelCtrl = ngModelCtrl_; ngModelCtrl.$render = this.render; ngModelCtrl.$formatters.unshift(function(modelValue) { return modelValue ? new Date(modelValue) : null; }); var hoursInputEl = inputs.eq(0), minutesInputEl = inputs.eq(1), secondsInputEl = inputs.eq(2); hoursModelCtrl = hoursInputEl.controller('ngModel'); minutesModelCtrl = minutesInputEl.controller('ngModel'); secondsModelCtrl = secondsInputEl.controller('ngModel'); var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel; if (mousewheel) { this.setupMousewheelEvents(hoursInputEl, minutesInputEl, secondsInputEl); } var arrowkeys = angular.isDefined($attrs.arrowkeys) ? $scope.$parent.$eval($attrs.arrowkeys) : timepickerConfig.arrowkeys; if (arrowkeys) { this.setupArrowkeyEvents(hoursInputEl, minutesInputEl, secondsInputEl); } $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput; this.setupInputEvents(hoursInputEl, minutesInputEl, secondsInputEl); }; var hourStep = timepickerConfig.hourStep; if ($attrs.hourStep) { watchers.push($scope.$parent.$watch($parse($attrs.hourStep), function(value) { hourStep = +value; })); } var minuteStep = timepickerConfig.minuteStep; if ($attrs.minuteStep) { watchers.push($scope.$parent.$watch($parse($attrs.minuteStep), function(value) { minuteStep = +value; })); } var min; watchers.push($scope.$parent.$watch($parse($attrs.min), function(value) { var dt = new Date(value); min = isNaN(dt) ? undefined : dt; })); var max; watchers.push($scope.$parent.$watch($parse($attrs.max), function(value) { var dt = new Date(value); max = isNaN(dt) ? undefined : dt; })); var disabled = false; if ($attrs.ngDisabled) { watchers.push($scope.$parent.$watch($parse($attrs.ngDisabled), function(value) { disabled = value; })); } $scope.noIncrementHours = function() { var incrementedSelected = addMinutes(selected, hourStep * 60); return disabled || incrementedSelected > max || incrementedSelected < selected && incrementedSelected < min; }; $scope.noDecrementHours = function() { var decrementedSelected = addMinutes(selected, -hourStep * 60); return disabled || decrementedSelected < min || decrementedSelected > selected && decrementedSelected > max; }; $scope.noIncrementMinutes = function() { var incrementedSelected = addMinutes(selected, minuteStep); return disabled || incrementedSelected > max || incrementedSelected < selected && incrementedSelected < min; }; $scope.noDecrementMinutes = function() { var decrementedSelected = addMinutes(selected, -minuteStep); return disabled || decrementedSelected < min || decrementedSelected > selected && decrementedSelected > max; }; $scope.noIncrementSeconds = function() { var incrementedSelected = addSeconds(selected, secondStep); return disabled || incrementedSelected > max || incrementedSelected < selected && incrementedSelected < min; }; $scope.noDecrementSeconds = function() { var decrementedSelected = addSeconds(selected, -secondStep); return disabled || decrementedSelected < min || decrementedSelected > selected && decrementedSelected > max; }; $scope.noToggleMeridian = function() { if (selected.getHours() < 12) { return disabled || addMinutes(selected, 12 * 60) > max; } return disabled || addMinutes(selected, -12 * 60) < min; }; var secondStep = timepickerConfig.secondStep; if ($attrs.secondStep) { watchers.push($scope.$parent.$watch($parse($attrs.secondStep), function(value) { secondStep = +value; })); } $scope.showSeconds = timepickerConfig.showSeconds; if ($attrs.showSeconds) { watchers.push($scope.$parent.$watch($parse($attrs.showSeconds), function(value) { $scope.showSeconds = !!value; })); } // 12H / 24H mode $scope.showMeridian = timepickerConfig.showMeridian; if ($attrs.showMeridian) { watchers.push($scope.$parent.$watch($parse($attrs.showMeridian), function(value) { $scope.showMeridian = !!value; if (ngModelCtrl.$error.time) { // Evaluate from template var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate(); if (angular.isDefined(hours) && angular.isDefined(minutes)) { selected.setHours(hours); refresh(); } } else { updateTemplate(); } })); } // Get $scope.hours in 24H mode if valid function getHoursFromTemplate() { var hours = +$scope.hours; var valid = $scope.showMeridian ? hours > 0 && hours < 13 : hours >= 0 && hours < 24; if (!valid || $scope.hours === '') { return undefined; } if ($scope.showMeridian) { if (hours === 12) { hours = 0; } if ($scope.meridian === meridians[1]) { hours = hours + 12; } } return hours; } function getMinutesFromTemplate() { var minutes = +$scope.minutes; var valid = minutes >= 0 && minutes < 60; if (!valid || $scope.minutes === '') { return undefined; } return minutes; } function getSecondsFromTemplate() { var seconds = +$scope.seconds; return seconds >= 0 && seconds < 60 ? seconds : undefined; } function pad(value, noPad) { if (value === null) { return ''; } return angular.isDefined(value) && value.toString().length < 2 && !noPad ? '0' + value : value.toString(); } // Respond on mousewheel spin this.setupMousewheelEvents = function(hoursInputEl, minutesInputEl, secondsInputEl) { var isScrollingUp = function(e) { if (e.originalEvent) { e = e.originalEvent; } //pick correct delta variable depending on event var delta = e.wheelDelta ? e.wheelDelta : -e.deltaY; return e.detail || delta > 0; }; hoursInputEl.on('mousewheel wheel', function(e) { if (!disabled) { $scope.$apply(isScrollingUp(e) ? $scope.incrementHours() : $scope.decrementHours()); } e.preventDefault(); }); minutesInputEl.on('mousewheel wheel', function(e) { if (!disabled) { $scope.$apply(isScrollingUp(e) ? $scope.incrementMinutes() : $scope.decrementMinutes()); } e.preventDefault(); }); secondsInputEl.on('mousewheel wheel', function(e) { if (!disabled) { $scope.$apply(isScrollingUp(e) ? $scope.incrementSeconds() : $scope.decrementSeconds()); } e.preventDefault(); }); }; // Respond on up/down arrowkeys this.setupArrowkeyEvents = function(hoursInputEl, minutesInputEl, secondsInputEl) { hoursInputEl.on('keydown', function(e) { if (!disabled) { if (e.which === 38) { // up e.preventDefault(); $scope.incrementHours(); $scope.$apply(); } else if (e.which === 40) { // down e.preventDefault(); $scope.decrementHours(); $scope.$apply(); } } }); minutesInputEl.on('keydown', function(e) { if (!disabled) { if (e.which === 38) { // up e.preventDefault(); $scope.incrementMinutes(); $scope.$apply(); } else if (e.which === 40) { // down e.preventDefault(); $scope.decrementMinutes(); $scope.$apply(); } } }); secondsInputEl.on('keydown', function(e) { if (!disabled) { if (e.which === 38) { // up e.preventDefault(); $scope.incrementSeconds(); $scope.$apply(); } else if (e.which === 40) { // down e.preventDefault(); $scope.decrementSeconds(); $scope.$apply(); } } }); }; this.setupInputEvents = function(hoursInputEl, minutesInputEl, secondsInputEl) { if ($scope.readonlyInput) { $scope.updateHours = angular.noop; $scope.updateMinutes = angular.noop; $scope.updateSeconds = angular.noop; return; } var invalidate = function(invalidHours, invalidMinutes, invalidSeconds) { ngModelCtrl.$setViewValue(null); ngModelCtrl.$setValidity('time', false); if (angular.isDefined(invalidHours)) { $scope.invalidHours = invalidHours; if (hoursModelCtrl) { hoursModelCtrl.$setValidity('hours', false); } } if (angular.isDefined(invalidMinutes)) { $scope.invalidMinutes = invalidMinutes; if (minutesModelCtrl) { minutesModelCtrl.$setValidity('minutes', false); } } if (angular.isDefined(invalidSeconds)) { $scope.invalidSeconds = invalidSeconds; if (secondsModelCtrl) { secondsModelCtrl.$setValidity('seconds', false); } } }; $scope.updateHours = function() { var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate(); ngModelCtrl.$setDirty(); if (angular.isDefined(hours) && angular.isDefined(minutes)) { selected.setHours(hours); selected.setMinutes(minutes); if (selected < min || selected > max) { invalidate(true); } else { refresh('h'); } } else { invalidate(true); } }; hoursInputEl.on('blur', function(e) { ngModelCtrl.$setTouched(); if (modelIsEmpty()) { makeValid(); } else if ($scope.hours === null || $scope.hours === '') { invalidate(true); } else if (!$scope.invalidHours && $scope.hours < 10) { $scope.$apply(function() { $scope.hours = pad($scope.hours, !padHours); }); } }); $scope.updateMinutes = function() { var minutes = getMinutesFromTemplate(), hours = getHoursFromTemplate(); ngModelCtrl.$setDirty(); if (angular.isDefined(minutes) && angular.isDefined(hours)) { selected.setHours(hours); selected.setMinutes(minutes); if (selected < min || selected > max) { invalidate(undefined, true); } else { refresh('m'); } } else { invalidate(undefined, true); } }; minutesInputEl.on('blur', function(e) { ngModelCtrl.$setTouched(); if (modelIsEmpty()) { makeValid(); } else if ($scope.minutes === null) { invalidate(undefined, true); } else if (!$scope.invalidMinutes && $scope.minutes < 10) { $scope.$apply(function() { $scope.minutes = pad($scope.minutes); }); } }); $scope.updateSeconds = function() { var seconds = getSecondsFromTemplate(); ngModelCtrl.$setDirty(); if (angular.isDefined(seconds)) { selected.setSeconds(seconds); refresh('s'); } else { invalidate(undefined, undefined, true); } }; secondsInputEl.on('blur', function(e) { if (modelIsEmpty()) { makeValid(); } else if (!$scope.invalidSeconds && $scope.seconds < 10) { $scope.$apply( function() { $scope.seconds = pad($scope.seconds); }); } }); }; this.render = function() { var date = ngModelCtrl.$viewValue; if (isNaN(date)) { ngModelCtrl.$setValidity('time', false); $log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.'); } else { if (date) { selected = date; } if (selected < min || selected > max) { ngModelCtrl.$setValidity('time', false); $scope.invalidHours = true; $scope.invalidMinutes = true; } else { makeValid(); } updateTemplate(); } }; // Call internally when we know that model is valid. function refresh(keyboardChange) { makeValid(); ngModelCtrl.$setViewValue(new Date(selected)); updateTemplate(keyboardChange); } function makeValid() { if (hoursModelCtrl) { hoursModelCtrl.$setValidity('hours', true); } if (minutesModelCtrl) { minutesModelCtrl.$setValidity('minutes', true); } if (secondsModelCtrl) { secondsModelCtrl.$setValidity('seconds', true); } ngModelCtrl.$setValidity('time', true); $scope.invalidHours = false; $scope.invalidMinutes = false; $scope.invalidSeconds = false; } function updateTemplate(keyboardChange) { if (!ngModelCtrl.$modelValue) { $scope.hours = null; $scope.minutes = null; $scope.seconds = null; $scope.meridian = meridians[0]; } else { var hours = selected.getHours(), minutes = selected.getMinutes(), seconds = selected.getSeconds(); if ($scope.showMeridian) { hours = hours === 0 || hours === 12 ? 12 : hours % 12; // Convert 24 to 12 hour system } $scope.hours = keyboardChange === 'h' ? hours : pad(hours, !padHours); if (keyboardChange !== 'm') { $scope.minutes = pad(minutes); } $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1]; if (keyboardChange !== 's') { $scope.seconds = pad(seconds); } $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1]; } } function addSecondsToSelected(seconds) { selected = addSeconds(selected, seconds); refresh(); } function addMinutes(selected, minutes) { return addSeconds(selected, minutes*60); } function addSeconds(date, seconds) { var dt = new Date(date.getTime() + seconds * 1000); var newDate = new Date(date); newDate.setHours(dt.getHours(), dt.getMinutes(), dt.getSeconds()); return newDate; } function modelIsEmpty() { return ($scope.hours === null || $scope.hours === '') && ($scope.minutes === null || $scope.minutes === '') && (!$scope.showSeconds || $scope.showSeconds && ($scope.seconds === null || $scope.seconds === '')); } $scope.showSpinners = angular.isDefined($attrs.showSpinners) ? $scope.$parent.$eval($attrs.showSpinners) : timepickerConfig.showSpinners; $scope.incrementHours = function() { if (!$scope.noIncrementHours()) { addSecondsToSelected(hourStep * 60 * 60); } }; $scope.decrementHours = function() { if (!$scope.noDecrementHours()) { addSecondsToSelected(-hourStep * 60 * 60); } }; $scope.incrementMinutes = function() { if (!$scope.noIncrementMinutes()) { addSecondsToSelected(minuteStep * 60); } }; $scope.decrementMinutes = function() { if (!$scope.noDecrementMinutes()) { addSecondsToSelected(-minuteStep * 60); } }; $scope.incrementSeconds = function() { if (!$scope.noIncrementSeconds()) { addSecondsToSelected(secondStep); } }; $scope.decrementSeconds = function() { if (!$scope.noDecrementSeconds()) { addSecondsToSelected(-secondStep); } }; $scope.toggleMeridian = function() { var minutes = getMinutesFromTemplate(), hours = getHoursFromTemplate(); if (!$scope.noToggleMeridian()) { if (angular.isDefined(minutes) && angular.isDefined(hours)) { addSecondsToSelected(12 * 60 * (selected.getHours() < 12 ? 60 : -60)); } else { $scope.meridian = $scope.meridian === meridians[0] ? meridians[1] : meridians[0]; } } }; $scope.blur = function() { ngModelCtrl.$setTouched(); }; $scope.$on('$destroy', function() { while (watchers.length) { watchers.shift()(); } }); }]) .directive('uibTimepicker', ['uibTimepickerConfig', function(uibTimepickerConfig) { return { require: ['uibTimepicker', '?^ngModel'], restrict: 'A', controller: 'UibTimepickerController', controllerAs: 'timepicker', scope: {}, templateUrl: function(element, attrs) { return attrs.templateUrl || uibTimepickerConfig.templateUrl; }, link: function(scope, element, attrs, ctrls) { var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; if (ngModelCtrl) { timepickerCtrl.init(ngModelCtrl, element.find('input')); } } }; }]); angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.debounce', 'ui.bootstrap.position']) /** * A helper service that can parse typeahead's syntax (string provided by users) * Extracted to a separate service for ease of unit testing */ .factory('uibTypeaheadParser', ['$parse', function($parse) { // 000001111111100000000000002222222200000000000000003333333333333330000000000044444444000 var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/; return { parse: function(input) { var match = input.match(TYPEAHEAD_REGEXP); if (!match) { throw new Error( 'Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' + ' but got "' + input + '".'); } return { itemName: match[3], source: $parse(match[4]), viewMapper: $parse(match[2] || match[1]), modelMapper: $parse(match[1]) }; } }; }]) .controller('UibTypeaheadController', ['$scope', '$element', '$attrs', '$compile', '$parse', '$q', '$timeout', '$document', '$window', '$rootScope', '$$debounce', '$uibPosition', 'uibTypeaheadParser', function(originalScope, element, attrs, $compile, $parse, $q, $timeout, $document, $window, $rootScope, $$debounce, $position, typeaheadParser) { var HOT_KEYS = [9, 13, 27, 38, 40]; var eventDebounceTime = 200; var modelCtrl, ngModelOptions; //SUPPORTED ATTRIBUTES (OPTIONS) //minimal no of characters that needs to be entered before typeahead kicks-in var minLength = originalScope.$eval(attrs.typeaheadMinLength); if (!minLength && minLength !== 0) { minLength = 1; } originalScope.$watch(attrs.typeaheadMinLength, function (newVal) { minLength = !newVal && newVal !== 0 ? 1 : newVal; }); //minimal wait time after last character typed before typeahead kicks-in var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0; //should it restrict model values to the ones selected from the popup only? var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false; originalScope.$watch(attrs.typeaheadEditable, function (newVal) { isEditable = newVal !== false; }); //binding to a variable that indicates if matches are being retrieved asynchronously var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop; //a function to determine if an event should cause selection var isSelectEvent = attrs.typeaheadShouldSelect ? $parse(attrs.typeaheadShouldSelect) : function(scope, vals) { var evt = vals.$event; return evt.which === 13 || evt.which === 9; }; //a callback executed when a match is selected var onSelectCallback = $parse(attrs.typeaheadOnSelect); //should it select highlighted popup value when losing focus? var isSelectOnBlur = angular.isDefined(attrs.typeaheadSelectOnBlur) ? originalScope.$eval(attrs.typeaheadSelectOnBlur) : false; //binding to a variable that indicates if there were no results after the query is completed var isNoResultsSetter = $parse(attrs.typeaheadNoResults).assign || angular.noop; var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined; var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false; var appendTo = attrs.typeaheadAppendTo ? originalScope.$eval(attrs.typeaheadAppendTo) : null; var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false; //If input matches an item of the list exactly, select it automatically var selectOnExact = attrs.typeaheadSelectOnExact ? originalScope.$eval(attrs.typeaheadSelectOnExact) : false; //binding to a variable that indicates if dropdown is open var isOpenSetter = $parse(attrs.typeaheadIsOpen).assign || angular.noop; var showHint = originalScope.$eval(attrs.typeaheadShowHint) || false; //INTERNAL VARIABLES //model setter executed upon match selection var parsedModel = $parse(attrs.ngModel); var invokeModelSetter = $parse(attrs.ngModel + '($$$p)'); var $setModelValue = function(scope, newValue) { if (angular.isFunction(parsedModel(originalScope)) && ngModelOptions.getOption('getterSetter')) { return invokeModelSetter(scope, {$$$p: newValue}); } return parsedModel.assign(scope, newValue); }; //expressions used by typeahead var parserResult = typeaheadParser.parse(attrs.uibTypeahead); var hasFocus; //Used to avoid bug in iOS webview where iOS keyboard does not fire //mousedown & mouseup events //Issue #3699 var selected; //create a child scope for the typeahead directive so we are not polluting original scope //with typeahead-specific data (matches, query etc.) var scope = originalScope.$new(); var offDestroy = originalScope.$on('$destroy', function() { scope.$destroy(); }); scope.$on('$destroy', offDestroy); // WAI-ARIA var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000); element.attr({ 'aria-autocomplete': 'list', 'aria-expanded': false, 'aria-owns': popupId }); var inputsContainer, hintInputElem; //add read-only input to show hint if (showHint) { inputsContainer = angular.element('
'); inputsContainer.css('position', 'relative'); element.after(inputsContainer); hintInputElem = element.clone(); hintInputElem.attr('placeholder', ''); hintInputElem.attr('tabindex', '-1'); hintInputElem.val(''); hintInputElem.css({ 'position': 'absolute', 'top': '0px', 'left': '0px', 'border-color': 'transparent', 'box-shadow': 'none', 'opacity': 1, 'background': 'none 0% 0% / auto repeat scroll padding-box border-box rgb(255, 255, 255)', 'color': '#999' }); element.css({ 'position': 'relative', 'vertical-align': 'top', 'background-color': 'transparent' }); if (hintInputElem.attr('id')) { hintInputElem.removeAttr('id'); // remove duplicate id if present. } inputsContainer.append(hintInputElem); hintInputElem.after(element); } //pop-up element used to display matches var popUpEl = angular.element('
'); popUpEl.attr({ id: popupId, matches: 'matches', active: 'activeIdx', select: 'select(activeIdx, evt)', 'move-in-progress': 'moveInProgress', query: 'query', position: 'position', 'assign-is-open': 'assignIsOpen(isOpen)', debounce: 'debounceUpdate' }); //custom item template if (angular.isDefined(attrs.typeaheadTemplateUrl)) { popUpEl.attr('template-url', attrs.typeaheadTemplateUrl); } if (angular.isDefined(attrs.typeaheadPopupTemplateUrl)) { popUpEl.attr('popup-template-url', attrs.typeaheadPopupTemplateUrl); } var resetHint = function() { if (showHint) { hintInputElem.val(''); } }; var resetMatches = function() { scope.matches = []; scope.activeIdx = -1; element.attr('aria-expanded', false); resetHint(); }; var getMatchId = function(index) { return popupId + '-option-' + index; }; // Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead. // This attribute is added or removed automatically when the `activeIdx` changes. scope.$watch('activeIdx', function(index) { if (index < 0) { element.removeAttr('aria-activedescendant'); } else { element.attr('aria-activedescendant', getMatchId(index)); } }); var inputIsExactMatch = function(inputValue, index) { if (scope.matches.length > index && inputValue) { return inputValue.toUpperCase() === scope.matches[index].label.toUpperCase(); } return false; }; var getMatchesAsync = function(inputValue, evt) { var locals = {$viewValue: inputValue}; isLoadingSetter(originalScope, true); isNoResultsSetter(originalScope, false); $q.when(parserResult.source(originalScope, locals)).then(function(matches) { //it might happen that several async queries were in progress if a user were typing fast //but we are interested only in responses that correspond to the current view value var onCurrentRequest = inputValue === modelCtrl.$viewValue; if (onCurrentRequest && hasFocus) { if (matches && matches.length > 0) { scope.activeIdx = focusFirst ? 0 : -1; isNoResultsSetter(originalScope, false); scope.matches.length = 0; //transform labels for (var i = 0; i < matches.length; i++) { locals[parserResult.itemName] = matches[i]; scope.matches.push({ id: getMatchId(i), label: parserResult.viewMapper(scope, locals), model: matches[i] }); } scope.query = inputValue; //position pop-up with matches - we need to re-calculate its position each time we are opening a window //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page //due to other elements being rendered recalculatePosition(); element.attr('aria-expanded', true); //Select the single remaining option if user input matches if (selectOnExact && scope.matches.length === 1 && inputIsExactMatch(inputValue, 0)) { if (angular.isNumber(scope.debounceUpdate) || angular.isObject(scope.debounceUpdate)) { $$debounce(function() { scope.select(0, evt); }, angular.isNumber(scope.debounceUpdate) ? scope.debounceUpdate : scope.debounceUpdate['default']); } else { scope.select(0, evt); } } if (showHint) { var firstLabel = scope.matches[0].label; if (angular.isString(inputValue) && inputValue.length > 0 && firstLabel.slice(0, inputValue.length).toUpperCase() === inputValue.toUpperCase()) { hintInputElem.val(inputValue + firstLabel.slice(inputValue.length)); } else { hintInputElem.val(''); } } } else { resetMatches(); isNoResultsSetter(originalScope, true); } } if (onCurrentRequest) { isLoadingSetter(originalScope, false); } }, function() { resetMatches(); isLoadingSetter(originalScope, false); isNoResultsSetter(originalScope, true); }); }; // bind events only if appendToBody params exist - performance feature if (appendToBody) { angular.element($window).on('resize', fireRecalculating); $document.find('body').on('scroll', fireRecalculating); } // Declare the debounced function outside recalculating for // proper debouncing var debouncedRecalculate = $$debounce(function() { // if popup is visible if (scope.matches.length) { recalculatePosition(); } scope.moveInProgress = false; }, eventDebounceTime); // Default progress type scope.moveInProgress = false; function fireRecalculating() { if (!scope.moveInProgress) { scope.moveInProgress = true; scope.$digest(); } debouncedRecalculate(); } // recalculate actual position and set new values to scope // after digest loop is popup in right position function recalculatePosition() { scope.position = appendToBody ? $position.offset(element) : $position.position(element); scope.position.top += element.prop('offsetHeight'); } //we need to propagate user's query so we can higlight matches scope.query = undefined; //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later var timeoutPromise; var scheduleSearchWithTimeout = function(inputValue) { timeoutPromise = $timeout(function() { getMatchesAsync(inputValue); }, waitTime); }; var cancelPreviousTimeout = function() { if (timeoutPromise) { $timeout.cancel(timeoutPromise); } }; resetMatches(); scope.assignIsOpen = function (isOpen) { isOpenSetter(originalScope, isOpen); }; scope.select = function(activeIdx, evt) { //called from within the $digest() cycle var locals = {}; var model, item; selected = true; locals[parserResult.itemName] = item = scope.matches[activeIdx].model; model = parserResult.modelMapper(originalScope, locals); $setModelValue(originalScope, model); modelCtrl.$setValidity('editable', true); modelCtrl.$setValidity('parse', true); onSelectCallback(originalScope, { $item: item, $model: model, $label: parserResult.viewMapper(originalScope, locals), $event: evt }); resetMatches(); //return focus to the input element if a match was selected via a mouse click event // use timeout to avoid $rootScope:inprog error if (scope.$eval(attrs.typeaheadFocusOnSelect) !== false) { $timeout(function() { element[0].focus(); }, 0, false); } }; //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27) element.on('keydown', function(evt) { //typeahead is open and an "interesting" key was pressed if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) { return; } var shouldSelect = isSelectEvent(originalScope, {$event: evt}); /** * if there's nothing selected (i.e. focusFirst) and enter or tab is hit * or * shift + tab is pressed to bring focus to the previous element * then clear the results */ if (scope.activeIdx === -1 && shouldSelect || evt.which === 9 && !!evt.shiftKey) { resetMatches(); scope.$digest(); return; } evt.preventDefault(); var target; switch (evt.which) { case 27: // escape evt.stopPropagation(); resetMatches(); originalScope.$digest(); break; case 38: // up arrow scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1; scope.$digest(); target = popUpEl[0].querySelectorAll('.uib-typeahead-match')[scope.activeIdx]; target.parentNode.scrollTop = target.offsetTop; break; case 40: // down arrow scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length; scope.$digest(); target = popUpEl[0].querySelectorAll('.uib-typeahead-match')[scope.activeIdx]; target.parentNode.scrollTop = target.offsetTop; break; default: if (shouldSelect) { scope.$apply(function() { if (angular.isNumber(scope.debounceUpdate) || angular.isObject(scope.debounceUpdate)) { $$debounce(function() { scope.select(scope.activeIdx, evt); }, angular.isNumber(scope.debounceUpdate) ? scope.debounceUpdate : scope.debounceUpdate['default']); } else { scope.select(scope.activeIdx, evt); } }); } } }); element.on('focus', function (evt) { hasFocus = true; if (minLength === 0 && !modelCtrl.$viewValue) { $timeout(function() { getMatchesAsync(modelCtrl.$viewValue, evt); }, 0); } }); element.on('blur', function(evt) { if (isSelectOnBlur && scope.matches.length && scope.activeIdx !== -1 && !selected) { selected = true; scope.$apply(function() { if (angular.isObject(scope.debounceUpdate) && angular.isNumber(scope.debounceUpdate.blur)) { $$debounce(function() { scope.select(scope.activeIdx, evt); }, scope.debounceUpdate.blur); } else { scope.select(scope.activeIdx, evt); } }); } if (!isEditable && modelCtrl.$error.editable) { modelCtrl.$setViewValue(); scope.$apply(function() { // Reset validity as we are clearing modelCtrl.$setValidity('editable', true); modelCtrl.$setValidity('parse', true); }); element.val(''); } hasFocus = false; selected = false; }); // Keep reference to click handler to unbind it. var dismissClickHandler = function(evt) { // Issue #3973 // Firefox treats right click as a click on document if (element[0] !== evt.target && evt.which !== 3 && scope.matches.length !== 0) { resetMatches(); if (!$rootScope.$$phase) { originalScope.$digest(); } } }; $document.on('click', dismissClickHandler); originalScope.$on('$destroy', function() { $document.off('click', dismissClickHandler); if (appendToBody || appendTo) { $popup.remove(); } if (appendToBody) { angular.element($window).off('resize', fireRecalculating); $document.find('body').off('scroll', fireRecalculating); } // Prevent jQuery cache memory leak popUpEl.remove(); if (showHint) { inputsContainer.remove(); } }); var $popup = $compile(popUpEl)(scope); if (appendToBody) { $document.find('body').append($popup); } else if (appendTo) { angular.element(appendTo).eq(0).append($popup); } else { element.after($popup); } this.init = function(_modelCtrl) { modelCtrl = _modelCtrl; ngModelOptions = extractOptions(modelCtrl); scope.debounceUpdate = $parse(ngModelOptions.getOption('debounce'))(originalScope); //plug into $parsers pipeline to open a typeahead on view changes initiated from DOM //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue modelCtrl.$parsers.unshift(function(inputValue) { hasFocus = true; if (minLength === 0 || inputValue && inputValue.length >= minLength) { if (waitTime > 0) { cancelPreviousTimeout(); scheduleSearchWithTimeout(inputValue); } else { getMatchesAsync(inputValue); } } else { isLoadingSetter(originalScope, false); cancelPreviousTimeout(); resetMatches(); } if (isEditable) { return inputValue; } if (!inputValue) { // Reset in case user had typed something previously. modelCtrl.$setValidity('editable', true); return null; } modelCtrl.$setValidity('editable', false); return undefined; }); modelCtrl.$formatters.push(function(modelValue) { var candidateViewValue, emptyViewValue; var locals = {}; // The validity may be set to false via $parsers (see above) if // the model is restricted to selected values. If the model // is set manually it is considered to be valid. if (!isEditable) { modelCtrl.$setValidity('editable', true); } if (inputFormatter) { locals.$model = modelValue; return inputFormatter(originalScope, locals); } //it might happen that we don't have enough info to properly render input value //we need to check for this situation and simply return model value if we can't apply custom formatting locals[parserResult.itemName] = modelValue; candidateViewValue = parserResult.viewMapper(originalScope, locals); locals[parserResult.itemName] = undefined; emptyViewValue = parserResult.viewMapper(originalScope, locals); return candidateViewValue !== emptyViewValue ? candidateViewValue : modelValue; }); }; function extractOptions(ngModelCtrl) { var ngModelOptions; if (angular.version.minor < 6) { // in angular < 1.6 $options could be missing // guarantee a value ngModelOptions = ngModelCtrl.$options || {}; // mimic 1.6+ api ngModelOptions.getOption = function (key) { return ngModelOptions[key]; }; } else { // in angular >=1.6 $options is always present ngModelOptions = ngModelCtrl.$options; } return ngModelOptions; } }]) .directive('uibTypeahead', function() { return { controller: 'UibTypeaheadController', require: ['ngModel', 'uibTypeahead'], link: function(originalScope, element, attrs, ctrls) { ctrls[1].init(ctrls[0]); } }; }) .directive('uibTypeaheadPopup', ['$$debounce', function($$debounce) { return { scope: { matches: '=', query: '=', active: '=', position: '&', moveInProgress: '=', select: '&', assignIsOpen: '&', debounce: '&' }, replace: true, templateUrl: function(element, attrs) { return attrs.popupTemplateUrl || 'uib/template/typeahead/typeahead-popup.html'; }, link: function(scope, element, attrs) { scope.templateUrl = attrs.templateUrl; scope.isOpen = function() { var isDropdownOpen = scope.matches.length > 0; scope.assignIsOpen({ isOpen: isDropdownOpen }); return isDropdownOpen; }; scope.isActive = function(matchIdx) { return scope.active === matchIdx; }; scope.selectActive = function(matchIdx) { scope.active = matchIdx; }; scope.selectMatch = function(activeIdx, evt) { var debounce = scope.debounce(); if (angular.isNumber(debounce) || angular.isObject(debounce)) { $$debounce(function() { scope.select({activeIdx: activeIdx, evt: evt}); }, angular.isNumber(debounce) ? debounce : debounce['default']); } else { scope.select({activeIdx: activeIdx, evt: evt}); } }; } }; }]) .directive('uibTypeaheadMatch', ['$templateRequest', '$compile', '$parse', function($templateRequest, $compile, $parse) { return { scope: { index: '=', match: '=', query: '=' }, link: function(scope, element, attrs) { var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'uib/template/typeahead/typeahead-match.html'; $templateRequest(tplUrl).then(function(tplContent) { var tplEl = angular.element(tplContent.trim()); element.replaceWith(tplEl); $compile(tplEl)(scope); }); } }; }]) .filter('uibTypeaheadHighlight', ['$sce', '$injector', '$log', function($sce, $injector, $log) { var isSanitizePresent; isSanitizePresent = $injector.has('$sanitize'); function escapeRegexp(queryToEscape) { // Regex: capture the whole query string and replace it with the string that will be used to match // the results, for example if the capture is "a" the result will be \a return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); } function containsHtml(matchItem) { return /<.*>/g.test(matchItem); } return function(matchItem, query) { if (!isSanitizePresent && containsHtml(matchItem)) { $log.warn('Unsafe use of typeahead please use ngSanitize'); // Warn the user about the danger } matchItem = query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '$&') : matchItem; // Replaces the capture string with a the same string inside of a "strong" tag if (!isSanitizePresent) { matchItem = $sce.trustAsHtml(matchItem); // If $sanitize is not present we pack the string in a $sce object for the ng-bind-html directive } return matchItem; }; }]); angular.module("uib/template/accordion/accordion-group.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/accordion/accordion-group.html", "
\n" + "

\n" + " {{heading}}\n" + "

\n" + "
\n" + "
\n" + "
\n" + "
\n" + ""); }]); angular.module("uib/template/accordion/accordion.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/accordion/accordion.html", "
"); }]); angular.module("uib/template/alert/alert.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/alert/alert.html", "\n" + "
\n" + ""); }]); angular.module("uib/template/carousel/carousel.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/carousel/carousel.html", "
\n" + " 1\">\n" + " \n" + " previous\n" + "\n" + " 1\">\n" + " \n" + " next\n" + "\n" + "
    1\">\n" + "
  1. \n" + " slide {{ $index + 1 }} of {{ slides.length }}, currently active\n" + "
  2. \n" + "
\n" + ""); }]); angular.module("uib/template/carousel/slide.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/carousel/slide.html", "
\n" + ""); }]); angular.module("uib/template/datepicker/datepicker.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/datepicker/datepicker.html", "
\n" + "
\n" + "
\n" + "
\n" + "
\n" + ""); }]); angular.module("uib/template/datepicker/day.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/datepicker/day.html", "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "
{{::label.abbr}}
{{ weekNumbers[$index] }}\n" + " \n" + "
\n" + ""); }]); angular.module("uib/template/datepicker/month.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/datepicker/month.html", "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "
\n" + " \n" + "
\n" + ""); }]); angular.module("uib/template/datepicker/popup.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("uib/template/datepicker/popup.html", "
\n" + "
    \n" + "
  • \n" + "
  • \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "
  • \n" + "
\n" + "
\n" + ""); }]); angular.module("uib/template/datepicker/year.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/datepicker/year.html", "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "
\n" + " \n" + "
\n" + ""); }]); angular.module("uib/template/datepickerPopup/popup.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/datepickerPopup/popup.html", "
    \n" + "
  • \n" + "
  • \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "
  • \n" + "
\n" + ""); }]); angular.module("uib/template/modal/backdrop.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("uib/template/modal/backdrop.html", "
\n" + ""); }]); angular.module("uib/template/modal/window.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/modal/window.html", "
\n" + ""); }]); angular.module("uib/template/pager/pager.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/pager/pager.html", "
  • {{::getText('previous')}}
  • \n" + "
  • {{::getText('next')}}
  • \n" + ""); }]); angular.module("uib/template/pagination/pagination.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/pagination/pagination.html", "
  • {{::getText('first')}}
  • \n" + "
  • {{::getText('previous')}}
  • \n" + "
  • {{page.text}}
  • \n" + "
  • {{::getText('next')}}
  • \n" + "
  • {{::getText('last')}}
  • \n" + ""); }]); angular.module("uib/template/tooltip/tooltip-html-popup.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/tooltip/tooltip-html-popup.html", "
    \n" + "
    \n" + ""); }]); angular.module("uib/template/tooltip/tooltip-popup.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/tooltip/tooltip-popup.html", "
    \n" + "
    \n" + ""); }]); angular.module("uib/template/tooltip/tooltip-template-popup.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/tooltip/tooltip-template-popup.html", "
    \n" + "
    \n" + ""); }]); angular.module("uib/template/popover/popover-html.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/popover/popover-html.html", "
    \n" + "\n" + "
    \n" + "

    \n" + "
    \n" + "
    \n" + ""); }]); angular.module("uib/template/popover/popover-template.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/popover/popover-template.html", "
    \n" + "\n" + "
    \n" + "

    \n" + "
    \n" + "
    \n" + ""); }]); angular.module("uib/template/popover/popover.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/popover/popover.html", "
    \n" + "\n" + "
    \n" + "

    \n" + "
    \n" + "
    \n" + ""); }]); angular.module("uib/template/progressbar/bar.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/progressbar/bar.html", "
    \n" + ""); }]); angular.module("uib/template/progressbar/progress.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/progressbar/progress.html", "
    "); }]); angular.module("uib/template/progressbar/progressbar.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/progressbar/progressbar.html", "
    \n" + "
    \n" + "
    \n" + ""); }]); angular.module("uib/template/rating/rating.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/rating/rating.html", "\n" + " ({{ $index < value ? '*' : ' ' }})\n" + " \n" + "\n" + ""); }]); angular.module("uib/template/tabs/tab.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/tabs/tab.html", "
  • \n" + " {{heading}}\n" + "
  • \n" + ""); }]); angular.module("uib/template/tabs/tabset.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/tabs/tabset.html", "
    \n" + "
      \n" + "
      \n" + "
      \n" + "
      \n" + "
      \n" + "
      \n" + ""); }]); angular.module("uib/template/timepicker/timepicker.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/timepicker/timepicker.html", "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "
        
      \n" + " \n" + " :\n" + " \n" + " :\n" + " \n" + "
        
      \n" + ""); }]); angular.module("uib/template/typeahead/typeahead-match.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/typeahead/typeahead-match.html", "\n" + ""); }]); angular.module("uib/template/typeahead/typeahead-popup.html", []).run(["$templateCache", function ($templateCache) { $templateCache.put("uib/template/typeahead/typeahead-popup.html", "
        \n" + "
      • \n" + "
        \n" + "
      • \n" + "
      \n" + ""); }]); angular.module('ui.bootstrap.carousel').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibCarouselCss && angular.element(document).find('head').prepend(''); angular.$$uibCarouselCss = true; }); angular.module('ui.bootstrap.datepicker').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibDatepickerCss && angular.element(document).find('head').prepend(''); angular.$$uibDatepickerCss = true; }); angular.module('ui.bootstrap.position').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibPositionCss && angular.element(document).find('head').prepend(''); angular.$$uibPositionCss = true; }); angular.module('ui.bootstrap.datepickerPopup').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibDatepickerpopupCss && angular.element(document).find('head').prepend(''); angular.$$uibDatepickerpopupCss = true; }); angular.module('ui.bootstrap.tooltip').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibTooltipCss && angular.element(document).find('head').prepend(''); angular.$$uibTooltipCss = true; }); angular.module('ui.bootstrap.timepicker').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibTimepickerCss && angular.element(document).find('head').prepend(''); angular.$$uibTimepickerCss = true; }); angular.module('ui.bootstrap.typeahead').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibTypeaheadCss && angular.element(document).find('head').prepend(''); angular.$$uibTypeaheadCss = true; }); (function() { 'use strict'; angular.module('toastr', []) .factory('toastr', toastr); toastr.$inject = ['$animate', '$injector', '$document', '$rootScope', '$sce', 'toastrConfig', '$q']; function toastr($animate, $injector, $document, $rootScope, $sce, toastrConfig, $q) { var container; var index = 0; var toasts = []; var previousToastMessage = ''; var openToasts = {}; var containerDefer = $q.defer(); var toast = { active: active, clear: clear, error: error, info: info, remove: remove, success: success, warning: warning, refreshTimer: refreshTimer }; return toast; /* Public API */ function active() { return toasts.length; } function clear(toast) { // Bit of a hack, I will remove this soon with a BC if (arguments.length === 1 && !toast) { return; } if (toast) { remove(toast.toastId); } else { for (var i = 0; i < toasts.length; i++) { remove(toasts[i].toastId); } } } function error(message, title, optionsOverride) { var type = _getOptions().iconClasses.error; return _buildNotification(type, message, title, optionsOverride); } function info(message, title, optionsOverride) { var type = _getOptions().iconClasses.info; return _buildNotification(type, message, title, optionsOverride); } function success(message, title, optionsOverride) { var type = _getOptions().iconClasses.success; return _buildNotification(type, message, title, optionsOverride); } function warning(message, title, optionsOverride) { var type = _getOptions().iconClasses.warning; return _buildNotification(type, message, title, optionsOverride); } function refreshTimer(toast, newTime) { if (toast && toast.isOpened && toasts.indexOf(toast) >= 0) { toast.scope.refreshTimer(newTime); } } function remove(toastId, wasClicked) { var toast = findToast(toastId); if (toast && ! toast.deleting) { // Avoid clicking when fading out toast.deleting = true; toast.isOpened = false; $animate.leave(toast.el).then(function() { if (toast.scope.options.onHidden) { toast.scope.options.onHidden(!!wasClicked, toast); } toast.scope.$destroy(); var index = toasts.indexOf(toast); delete openToasts[toast.scope.message]; toasts.splice(index, 1); var maxOpened = toastrConfig.maxOpened; if (maxOpened && toasts.length >= maxOpened) { toasts[maxOpened - 1].open.resolve(); } if (lastToast()) { container.remove(); container = null; containerDefer = $q.defer(); } }); } function findToast(toastId) { for (var i = 0; i < toasts.length; i++) { if (toasts[i].toastId === toastId) { return toasts[i]; } } } function lastToast() { return !toasts.length; } } /* Internal functions */ function _buildNotification(type, message, title, optionsOverride) { if (angular.isObject(title)) { optionsOverride = title; title = null; } return _notify({ iconClass: type, message: message, optionsOverride: optionsOverride, title: title }); } function _getOptions() { return angular.extend({}, toastrConfig); } function _createOrGetContainer(options) { if(container) { return containerDefer.promise; } container = angular.element('
      '); container.attr('id', options.containerId); container.addClass(options.positionClass); container.css({'pointer-events': 'auto'}); var target = angular.element(document.querySelector(options.target)); if ( ! target || ! target.length) { throw 'Target for toasts doesn\'t exist'; } $animate.enter(container, target).then(function() { containerDefer.resolve(); }); return containerDefer.promise; } function _notify(map) { var options = _getOptions(); if (shouldExit()) { return; } var newToast = createToast(); toasts.push(newToast); if (ifMaxOpenedAndAutoDismiss()) { var oldToasts = toasts.slice(0, (toasts.length - options.maxOpened)); for (var i = 0, len = oldToasts.length; i < len; i++) { remove(oldToasts[i].toastId); } } if (maxOpenedNotReached()) { newToast.open.resolve(); } newToast.open.promise.then(function() { _createOrGetContainer(options).then(function() { newToast.isOpened = true; if (options.newestOnTop) { $animate.enter(newToast.el, container).then(function() { newToast.scope.init(); }); } else { var sibling = container[0].lastChild ? angular.element(container[0].lastChild) : null; $animate.enter(newToast.el, container, sibling).then(function() { newToast.scope.init(); }); } }); }); return newToast; function ifMaxOpenedAndAutoDismiss() { return options.autoDismiss && options.maxOpened && toasts.length > options.maxOpened; } function createScope(toast, map, options) { if (options.allowHtml) { toast.scope.allowHtml = true; toast.scope.title = $sce.trustAsHtml(map.title); toast.scope.message = $sce.trustAsHtml(map.message); } else { toast.scope.title = map.title; toast.scope.message = map.message; } toast.scope.toastType = toast.iconClass; toast.scope.toastId = toast.toastId; toast.scope.extraData = options.extraData; toast.scope.options = { extendedTimeOut: options.extendedTimeOut, messageClass: options.messageClass, onHidden: options.onHidden, onShown: generateEvent('onShown'), onTap: generateEvent('onTap'), progressBar: options.progressBar, tapToDismiss: options.tapToDismiss, timeOut: options.timeOut, titleClass: options.titleClass, toastClass: options.toastClass }; if (options.closeButton) { toast.scope.options.closeHtml = options.closeHtml; } function generateEvent(event) { if (options[event]) { return function() { options[event](toast); }; } } } function createToast() { var newToast = { toastId: index++, isOpened: false, scope: $rootScope.$new(), open: $q.defer() }; newToast.iconClass = map.iconClass; if (map.optionsOverride) { angular.extend(options, cleanOptionsOverride(map.optionsOverride)); newToast.iconClass = map.optionsOverride.iconClass || newToast.iconClass; } createScope(newToast, map, options); newToast.el = createToastEl(newToast.scope); return newToast; function cleanOptionsOverride(options) { var badOptions = ['containerId', 'iconClasses', 'maxOpened', 'newestOnTop', 'positionClass', 'preventDuplicates', 'preventOpenDuplicates', 'templates']; for (var i = 0, l = badOptions.length; i < l; i++) { delete options[badOptions[i]]; } return options; } } function createToastEl(scope) { var angularDomEl = angular.element('
      '), $compile = $injector.get('$compile'); return $compile(angularDomEl)(scope); } function maxOpenedNotReached() { return options.maxOpened && toasts.length <= options.maxOpened || !options.maxOpened; } function shouldExit() { var isDuplicateOfLast = options.preventDuplicates && map.message === previousToastMessage; var isDuplicateOpen = options.preventOpenDuplicates && openToasts[map.message]; if (isDuplicateOfLast || isDuplicateOpen) { return true; } previousToastMessage = map.message; openToasts[map.message] = true; return false; } } } }()); (function() { 'use strict'; angular.module('toastr') .constant('toastrConfig', { allowHtml: false, autoDismiss: false, closeButton: false, closeHtml: '', containerId: 'toast-container', extendedTimeOut: 1000, iconClasses: { error: 'toast-error', info: 'toast-info', success: 'toast-success', warning: 'toast-warning' }, maxOpened: 0, messageClass: 'toast-message', newestOnTop: true, onHidden: null, onShown: null, onTap: null, positionClass: 'toast-top-right', preventDuplicates: false, preventOpenDuplicates: false, progressBar: false, tapToDismiss: true, target: 'body', templates: { toast: 'directives/toast/toast.html', progressbar: 'directives/progressbar/progressbar.html' }, timeOut: 5000, titleClass: 'toast-title', toastClass: 'toast' }); }()); (function() { 'use strict'; angular.module('toastr') .directive('progressBar', progressBar); progressBar.$inject = ['toastrConfig']; function progressBar(toastrConfig) { return { require: '^toast', templateUrl: function() { return toastrConfig.templates.progressbar; }, link: linkFunction }; function linkFunction(scope, element, attrs, toastCtrl) { var intervalId, currentTimeOut, hideTime; toastCtrl.progressBar = scope; scope.start = function(duration) { if (intervalId) { clearInterval(intervalId); } currentTimeOut = parseFloat(duration); hideTime = new Date().getTime() + currentTimeOut; intervalId = setInterval(updateProgress, 10); }; scope.stop = function() { if (intervalId) { clearInterval(intervalId); } }; function updateProgress() { var percentage = ((hideTime - (new Date().getTime())) / currentTimeOut) * 100; element.css('width', percentage + '%'); } scope.$on('$destroy', function() { // Failsafe stop clearInterval(intervalId); }); } } }()); (function() { 'use strict'; angular.module('toastr') .controller('ToastController', ToastController); function ToastController() { this.progressBar = null; this.startProgressBar = function(duration) { if (this.progressBar) { this.progressBar.start(duration); } }; this.stopProgressBar = function() { if (this.progressBar) { this.progressBar.stop(); } }; } }()); (function() { 'use strict'; angular.module('toastr') .directive('toast', toast); toast.$inject = ['$injector', '$interval', 'toastrConfig', 'toastr']; function toast($injector, $interval, toastrConfig, toastr) { return { templateUrl: function() { return toastrConfig.templates.toast; }, controller: 'ToastController', link: toastLinkFunction }; function toastLinkFunction(scope, element, attrs, toastCtrl) { var timeout; scope.toastClass = scope.options.toastClass; scope.titleClass = scope.options.titleClass; scope.messageClass = scope.options.messageClass; scope.progressBar = scope.options.progressBar; if (wantsCloseButton()) { var button = angular.element(scope.options.closeHtml), $compile = $injector.get('$compile'); button.addClass('toast-close-button'); button.attr('ng-click', 'close(true, $event)'); $compile(button)(scope); element.children().prepend(button); } scope.init = function() { if (scope.options.timeOut) { timeout = createTimeout(scope.options.timeOut); } if (scope.options.onShown) { scope.options.onShown(); } }; element.on('mouseenter', function() { hideAndStopProgressBar(); if (timeout) { $interval.cancel(timeout); } }); scope.tapToast = function () { if (angular.isFunction(scope.options.onTap)) { scope.options.onTap(); } if (scope.options.tapToDismiss) { scope.close(true); } }; scope.close = function (wasClicked, $event) { if ($event && angular.isFunction($event.stopPropagation)) { $event.stopPropagation(); } toastr.remove(scope.toastId, wasClicked); }; scope.refreshTimer = function(newTime) { if (timeout) { $interval.cancel(timeout); timeout = createTimeout(newTime || scope.options.timeOut); } }; element.on('mouseleave', function() { if (scope.options.timeOut === 0 && scope.options.extendedTimeOut === 0) { return; } scope.$apply(function() { scope.progressBar = scope.options.progressBar; }); timeout = createTimeout(scope.options.extendedTimeOut); }); function createTimeout(time) { toastCtrl.startProgressBar(time); return $interval(function() { toastCtrl.stopProgressBar(); toastr.remove(scope.toastId); }, time, 1); } function hideAndStopProgressBar() { scope.progressBar = false; toastCtrl.stopProgressBar(); } function wantsCloseButton() { return scope.options.closeHtml; } } } }()); (function() { 'use strict'; angular.module('toastr', []) .factory('toastr', toastr); toastr.$inject = ['$animate', '$injector', '$document', '$rootScope', '$sce', 'toastrConfig', '$q']; function toastr($animate, $injector, $document, $rootScope, $sce, toastrConfig, $q) { var container; var index = 0; var toasts = []; var previousToastMessage = ''; var openToasts = {}; var containerDefer = $q.defer(); var toast = { active: active, clear: clear, error: error, info: info, remove: remove, success: success, warning: warning, refreshTimer: refreshTimer }; return toast; /* Public API */ function active() { return toasts.length; } function clear(toast) { // Bit of a hack, I will remove this soon with a BC if (arguments.length === 1 && !toast) { return; } if (toast) { remove(toast.toastId); } else { for (var i = 0; i < toasts.length; i++) { remove(toasts[i].toastId); } } } function error(message, title, optionsOverride) { var type = _getOptions().iconClasses.error; return _buildNotification(type, message, title, optionsOverride); } function info(message, title, optionsOverride) { var type = _getOptions().iconClasses.info; return _buildNotification(type, message, title, optionsOverride); } function success(message, title, optionsOverride) { var type = _getOptions().iconClasses.success; return _buildNotification(type, message, title, optionsOverride); } function warning(message, title, optionsOverride) { var type = _getOptions().iconClasses.warning; return _buildNotification(type, message, title, optionsOverride); } function refreshTimer(toast, newTime) { if (toast && toast.isOpened && toasts.indexOf(toast) >= 0) { toast.scope.refreshTimer(newTime); } } function remove(toastId, wasClicked) { var toast = findToast(toastId); if (toast && ! toast.deleting) { // Avoid clicking when fading out toast.deleting = true; toast.isOpened = false; $animate.leave(toast.el).then(function() { if (toast.scope.options.onHidden) { toast.scope.options.onHidden(!!wasClicked, toast); } toast.scope.$destroy(); var index = toasts.indexOf(toast); delete openToasts[toast.scope.message]; toasts.splice(index, 1); var maxOpened = toastrConfig.maxOpened; if (maxOpened && toasts.length >= maxOpened) { toasts[maxOpened - 1].open.resolve(); } if (lastToast()) { container.remove(); container = null; containerDefer = $q.defer(); } }); } function findToast(toastId) { for (var i = 0; i < toasts.length; i++) { if (toasts[i].toastId === toastId) { return toasts[i]; } } } function lastToast() { return !toasts.length; } } /* Internal functions */ function _buildNotification(type, message, title, optionsOverride) { if (angular.isObject(title)) { optionsOverride = title; title = null; } return _notify({ iconClass: type, message: message, optionsOverride: optionsOverride, title: title }); } function _getOptions() { return angular.extend({}, toastrConfig); } function _createOrGetContainer(options) { if(container) { return containerDefer.promise; } container = angular.element('
      '); container.attr('id', options.containerId); container.addClass(options.positionClass); container.css({'pointer-events': 'auto'}); var target = angular.element(document.querySelector(options.target)); if ( ! target || ! target.length) { throw 'Target for toasts doesn\'t exist'; } $animate.enter(container, target).then(function() { containerDefer.resolve(); }); return containerDefer.promise; } function _notify(map) { var options = _getOptions(); if (shouldExit()) { return; } var newToast = createToast(); toasts.push(newToast); if (ifMaxOpenedAndAutoDismiss()) { var oldToasts = toasts.slice(0, (toasts.length - options.maxOpened)); for (var i = 0, len = oldToasts.length; i < len; i++) { remove(oldToasts[i].toastId); } } if (maxOpenedNotReached()) { newToast.open.resolve(); } newToast.open.promise.then(function() { _createOrGetContainer(options).then(function() { newToast.isOpened = true; if (options.newestOnTop) { $animate.enter(newToast.el, container).then(function() { newToast.scope.init(); }); } else { var sibling = container[0].lastChild ? angular.element(container[0].lastChild) : null; $animate.enter(newToast.el, container, sibling).then(function() { newToast.scope.init(); }); } }); }); return newToast; function ifMaxOpenedAndAutoDismiss() { return options.autoDismiss && options.maxOpened && toasts.length > options.maxOpened; } function createScope(toast, map, options) { if (options.allowHtml) { toast.scope.allowHtml = true; toast.scope.title = $sce.trustAsHtml(map.title); toast.scope.message = $sce.trustAsHtml(map.message); } else { toast.scope.title = map.title; toast.scope.message = map.message; } toast.scope.toastType = toast.iconClass; toast.scope.toastId = toast.toastId; toast.scope.extraData = options.extraData; toast.scope.options = { extendedTimeOut: options.extendedTimeOut, messageClass: options.messageClass, onHidden: options.onHidden, onShown: generateEvent('onShown'), onTap: generateEvent('onTap'), progressBar: options.progressBar, tapToDismiss: options.tapToDismiss, timeOut: options.timeOut, titleClass: options.titleClass, toastClass: options.toastClass }; if (options.closeButton) { toast.scope.options.closeHtml = options.closeHtml; } function generateEvent(event) { if (options[event]) { return function() { options[event](toast); }; } } } function createToast() { var newToast = { toastId: index++, isOpened: false, scope: $rootScope.$new(), open: $q.defer() }; newToast.iconClass = map.iconClass; if (map.optionsOverride) { angular.extend(options, cleanOptionsOverride(map.optionsOverride)); newToast.iconClass = map.optionsOverride.iconClass || newToast.iconClass; } createScope(newToast, map, options); newToast.el = createToastEl(newToast.scope); return newToast; function cleanOptionsOverride(options) { var badOptions = ['containerId', 'iconClasses', 'maxOpened', 'newestOnTop', 'positionClass', 'preventDuplicates', 'preventOpenDuplicates', 'templates']; for (var i = 0, l = badOptions.length; i < l; i++) { delete options[badOptions[i]]; } return options; } } function createToastEl(scope) { var angularDomEl = angular.element('
      '), $compile = $injector.get('$compile'); return $compile(angularDomEl)(scope); } function maxOpenedNotReached() { return options.maxOpened && toasts.length <= options.maxOpened || !options.maxOpened; } function shouldExit() { var isDuplicateOfLast = options.preventDuplicates && map.message === previousToastMessage; var isDuplicateOpen = options.preventOpenDuplicates && openToasts[map.message]; if (isDuplicateOfLast || isDuplicateOpen) { return true; } previousToastMessage = map.message; openToasts[map.message] = true; return false; } } } }()); (function() { 'use strict'; angular.module('toastr') .constant('toastrConfig', { allowHtml: false, autoDismiss: false, closeButton: false, closeHtml: '', containerId: 'toast-container', extendedTimeOut: 1000, iconClasses: { error: 'toast-error', info: 'toast-info', success: 'toast-success', warning: 'toast-warning' }, maxOpened: 0, messageClass: 'toast-message', newestOnTop: true, onHidden: null, onShown: null, onTap: null, positionClass: 'toast-top-right', preventDuplicates: false, preventOpenDuplicates: false, progressBar: false, tapToDismiss: true, target: 'body', templates: { toast: 'directives/toast/toast.html', progressbar: 'directives/progressbar/progressbar.html' }, timeOut: 5000, titleClass: 'toast-title', toastClass: 'toast' }); }()); (function() { 'use strict'; angular.module('toastr') .directive('progressBar', progressBar); progressBar.$inject = ['toastrConfig']; function progressBar(toastrConfig) { return { require: '^toast', templateUrl: function() { return toastrConfig.templates.progressbar; }, link: linkFunction }; function linkFunction(scope, element, attrs, toastCtrl) { var intervalId, currentTimeOut, hideTime; toastCtrl.progressBar = scope; scope.start = function(duration) { if (intervalId) { clearInterval(intervalId); } currentTimeOut = parseFloat(duration); hideTime = new Date().getTime() + currentTimeOut; intervalId = setInterval(updateProgress, 10); }; scope.stop = function() { if (intervalId) { clearInterval(intervalId); } }; function updateProgress() { var percentage = ((hideTime - (new Date().getTime())) / currentTimeOut) * 100; element.css('width', percentage + '%'); } scope.$on('$destroy', function() { // Failsafe stop clearInterval(intervalId); }); } } }()); (function() { 'use strict'; angular.module('toastr') .controller('ToastController', ToastController); function ToastController() { this.progressBar = null; this.startProgressBar = function(duration) { if (this.progressBar) { this.progressBar.start(duration); } }; this.stopProgressBar = function() { if (this.progressBar) { this.progressBar.stop(); } }; } }()); (function() { 'use strict'; angular.module('toastr') .directive('toast', toast); toast.$inject = ['$injector', '$interval', 'toastrConfig', 'toastr']; function toast($injector, $interval, toastrConfig, toastr) { return { templateUrl: function() { return toastrConfig.templates.toast; }, controller: 'ToastController', link: toastLinkFunction }; function toastLinkFunction(scope, element, attrs, toastCtrl) { var timeout; scope.toastClass = scope.options.toastClass; scope.titleClass = scope.options.titleClass; scope.messageClass = scope.options.messageClass; scope.progressBar = scope.options.progressBar; if (wantsCloseButton()) { var button = angular.element(scope.options.closeHtml), $compile = $injector.get('$compile'); button.addClass('toast-close-button'); button.attr('ng-click', 'close(true, $event)'); $compile(button)(scope); element.children().prepend(button); } scope.init = function() { if (scope.options.timeOut) { timeout = createTimeout(scope.options.timeOut); } if (scope.options.onShown) { scope.options.onShown(); } }; element.on('mouseenter', function() { hideAndStopProgressBar(); if (timeout) { $interval.cancel(timeout); } }); scope.tapToast = function () { if (angular.isFunction(scope.options.onTap)) { scope.options.onTap(); } if (scope.options.tapToDismiss) { scope.close(true); } }; scope.close = function (wasClicked, $event) { if ($event && angular.isFunction($event.stopPropagation)) { $event.stopPropagation(); } toastr.remove(scope.toastId, wasClicked); }; scope.refreshTimer = function(newTime) { if (timeout) { $interval.cancel(timeout); timeout = createTimeout(newTime || scope.options.timeOut); } }; element.on('mouseleave', function() { if (scope.options.timeOut === 0 && scope.options.extendedTimeOut === 0) { return; } scope.$apply(function() { scope.progressBar = scope.options.progressBar; }); timeout = createTimeout(scope.options.extendedTimeOut); }); function createTimeout(time) { toastCtrl.startProgressBar(time); return $interval(function() { toastCtrl.stopProgressBar(); toastr.remove(scope.toastId); }, time, 1); } function hideAndStopProgressBar() { scope.progressBar = false; toastCtrl.stopProgressBar(); } function wantsCloseButton() { return scope.options.closeHtml; } } } }()); angular.module("toastr").run(["$templateCache", function($templateCache) {$templateCache.put("directives/progressbar/progressbar.html","
      \n"); $templateCache.put("directives/toast/toast.html","
      \n
      \n
      {{title}}
      \n
      {{message}}
      \n
      \n
      \n
      \n \n
      \n");}]); (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.angularStripe = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o * * Copyright (c) 2014 Jon Schlinkert, contributors. * Licensed under the MIT license. */ var isNumber = _dereq_('is-number'); var slice = _dereq_('array-slice'); module.exports = function last(arr, num) { if (!Array.isArray(arr)) { throw new Error('array-last expects an array as the first argument.'); } if (arr.length === 0) { return null; } var res = slice(arr, arr.length - (isNumber(num) ? +num : 1)); if (+num === 1 || num == null) { return res[0]; } return res; }; },{"array-slice":8,"is-number":20}],8:[function(_dereq_,module,exports){ /*! * array-slice * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; module.exports = function slice(arr, start, end) { var len = arr.length >>> 0; var range = []; start = idx(arr, start); end = idx(arr, end, len); while (start < end) { range.push(arr[start++]); } return range; }; function idx(arr, pos, end) { var len = arr.length >>> 0; if (pos == null) { pos = end || 0; } else if (pos < 0) { pos = Math.max(len + pos, 0); } else { pos = Math.min(pos, len); } return pos; } },{}],9:[function(_dereq_,module,exports){ "use strict"; // rawAsap provides everything we need except exception management. var rawAsap = _dereq_("./raw"); // RawTasks are recycled to reduce GC churn. var freeTasks = []; // We queue errors to ensure they are thrown in right order (FIFO). // Array-as-queue is good enough here, since we are just dealing with exceptions. var pendingErrors = []; var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError); function throwFirstError() { if (pendingErrors.length) { throw pendingErrors.shift(); } } /** * Calls a task as soon as possible after returning, in its own event, with priority * over other events like animation, reflow, and repaint. An error thrown from an * event will not interrupt, nor even substantially slow down the processing of * other events, but will be rather postponed to a lower priority event. * @param {{call}} task A callable object, typically a function that takes no * arguments. */ module.exports = asap; function asap(task) { var rawTask; if (freeTasks.length) { rawTask = freeTasks.pop(); } else { rawTask = new RawTask(); } rawTask.task = task; rawAsap(rawTask); } // We wrap tasks with recyclable task objects. A task object implements // `call`, just like a function. function RawTask() { this.task = null; } // The sole purpose of wrapping the task is to catch the exception and recycle // the task object after its single use. RawTask.prototype.call = function () { try { this.task.call(); } catch (error) { if (asap.onerror) { // This hook exists purely for testing purposes. // Its name will be periodically randomized to break any code that // depends on its existence. asap.onerror(error); } else { // In a web browser, exceptions are not fatal. However, to avoid // slowing down the queue of pending tasks, we rethrow the error in a // lower priority turn. pendingErrors.push(error); requestErrorThrow(); } } finally { this.task = null; freeTasks[freeTasks.length] = this; } }; },{"./raw":10}],10:[function(_dereq_,module,exports){ (function (global){ "use strict"; // Use the fastest means possible to execute a task in its own turn, with // priority over other events including IO, animation, reflow, and redraw // events in browsers. // // An exception thrown by a task will permanently interrupt the processing of // subsequent tasks. The higher level `asap` function ensures that if an // exception is thrown by a task, that the task queue will continue flushing as // soon as possible, but if you use `rawAsap` directly, you are responsible to // either ensure that no exceptions are thrown from your task, or to manually // call `rawAsap.requestFlush` if an exception is thrown. module.exports = rawAsap; function rawAsap(task) { if (!queue.length) { requestFlush(); flushing = true; } // Equivalent to push, but avoids a function call. queue[queue.length] = task; } var queue = []; // Once a flush has been requested, no further calls to `requestFlush` are // necessary until the next `flush` completes. var flushing = false; // `requestFlush` is an implementation-specific method that attempts to kick // off a `flush` event as quickly as possible. `flush` will attempt to exhaust // the event queue before yielding to the browser's own event loop. var requestFlush; // The position of the next task to execute in the task queue. This is // preserved between calls to `flush` so that it can be resumed if // a task throws an exception. var index = 0; // If a task schedules additional tasks recursively, the task queue can grow // unbounded. To prevent memory exhaustion, the task queue will periodically // truncate already-completed tasks. var capacity = 1024; // The flush function processes all tasks that have been scheduled with // `rawAsap` unless and until one of those tasks throws an exception. // If a task throws an exception, `flush` ensures that its state will remain // consistent and will resume where it left off when called again. // However, `flush` does not make any arrangements to be called again if an // exception is thrown. function flush() { while (index < queue.length) { var currentIndex = index; // Advance the index before calling the task. This ensures that we will // begin flushing on the next task the task throws an error. index = index + 1; queue[currentIndex].call(); // Prevent leaking memory for long chains of recursive calls to `asap`. // If we call `asap` within tasks scheduled by `asap`, the queue will // grow, but to avoid an O(n) walk for every task we execute, we don't // shift tasks off the queue after they have been executed. // Instead, we periodically shift 1024 tasks off the queue. if (index > capacity) { // Manually shift all values starting at the index back to the // beginning of the queue. for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { queue[scan] = queue[scan + index]; } queue.length -= index; index = 0; } } queue.length = 0; index = 0; flushing = false; } // `requestFlush` is implemented using a strategy based on data collected from // every available SauceLabs Selenium web driver worker at time of writing. // https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593 // Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that // have WebKitMutationObserver but not un-prefixed MutationObserver. // Must use `global` or `self` instead of `window` to work in both frames and web // workers. `global` is a provision of Browserify, Mr, Mrs, or Mop. /* globals self */ var scope = typeof global !== "undefined" ? global : self; var BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver; // MutationObservers are desirable because they have high priority and work // reliably everywhere they are implemented. // They are implemented in all modern browsers. // // - Android 4-4.3 // - Chrome 26-34 // - Firefox 14-29 // - Internet Explorer 11 // - iPad Safari 6-7.1 // - iPhone Safari 7-7.1 // - Safari 6-7 if (typeof BrowserMutationObserver === "function") { requestFlush = makeRequestCallFromMutationObserver(flush); // MessageChannels are desirable because they give direct access to the HTML // task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera // 11-12, and in web workers in many engines. // Although message channels yield to any queued rendering and IO tasks, they // would be better than imposing the 4ms delay of timers. // However, they do not work reliably in Internet Explorer or Safari. // Internet Explorer 10 is the only browser that has setImmediate but does // not have MutationObservers. // Although setImmediate yields to the browser's renderer, it would be // preferrable to falling back to setTimeout since it does not have // the minimum 4ms penalty. // Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and // Desktop to a lesser extent) that renders both setImmediate and // MessageChannel useless for the purposes of ASAP. // https://github.com/kriskowal/q/issues/396 // Timers are implemented universally. // We fall back to timers in workers in most engines, and in foreground // contexts in the following browsers. // However, note that even this simple case requires nuances to operate in a // broad spectrum of browsers. // // - Firefox 3-13 // - Internet Explorer 6-9 // - iPad Safari 4.3 // - Lynx 2.8.7 } else { requestFlush = makeRequestCallFromTimer(flush); } // `requestFlush` requests that the high priority event queue be flushed as // soon as possible. // This is useful to prevent an error thrown in a task from stalling the event // queue if the exception handled by Node.js’s // `process.on("uncaughtException")` or by a domain. rawAsap.requestFlush = requestFlush; // To request a high priority event, we induce a mutation observer by toggling // the text of a text node between "1" and "-1". function makeRequestCallFromMutationObserver(callback) { var toggle = 1; var observer = new BrowserMutationObserver(callback); var node = document.createTextNode(""); observer.observe(node, {characterData: true}); return function requestCall() { toggle = -toggle; node.data = toggle; }; } // The message channel technique was discovered by Malte Ubl and was the // original foundation for this library. // http://www.nonblocking.io/2011/06/windownexttick.html // Safari 6.0.5 (at least) intermittently fails to create message ports on a // page's first load. Thankfully, this version of Safari supports // MutationObservers, so we don't need to fall back in that case. // function makeRequestCallFromMessageChannel(callback) { // var channel = new MessageChannel(); // channel.port1.onmessage = callback; // return function requestCall() { // channel.port2.postMessage(0); // }; // } // For reasons explained above, we are also unable to use `setImmediate` // under any circumstances. // Even if we were, there is another bug in Internet Explorer 10. // It is not sufficient to assign `setImmediate` to `requestFlush` because // `setImmediate` must be called *by name* and therefore must be wrapped in a // closure. // Never forget. // function makeRequestCallFromSetImmediate(callback) { // return function requestCall() { // setImmediate(callback); // }; // } // Safari 6.0 has a problem where timers will get lost while the user is // scrolling. This problem does not impact ASAP because Safari 6.0 supports // mutation observers, so that implementation is used instead. // However, if we ever elect to use timers in Safari, the prevalent work-around // is to add a scroll event listener that calls for a flush. // `setTimeout` does not call the passed callback if the delay is less than // approximately 7 in web workers in Firefox 8 through 18, and sometimes not // even then. function makeRequestCallFromTimer(callback) { return function requestCall() { // We dispatch a timeout with a specified delay of 0 for engines that // can reliably accommodate that request. This will usually be snapped // to a 4 milisecond delay, but once we're flushing, there's no delay // between events. var timeoutHandle = setTimeout(handleTimer, 0); // However, since this timer gets frequently dropped in Firefox // workers, we enlist an interval handle that will try to fire // an event 20 times per second until it succeeds. var intervalHandle = setInterval(handleTimer, 50); function handleTimer() { // Whichever timer succeeds will cancel both timers and // execute the callback. clearTimeout(timeoutHandle); clearInterval(intervalHandle); callback(); } }; } // This is for `asap.js` only. // Its name will be periodically randomized to break any code that depends on // its existence. rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer; // ASAP was originally a nextTick shim included in Q. This was factored out // into this ASAP package. It was later adapted to RSVP which made further // amendments. These decisions, particularly to marginalize MessageChannel and // to capture the MutationObserver implementation in a closure, were integrated // back into ASAP proper. // https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],11:[function(_dereq_,module,exports){ 'use strict' var assert = _dereq_('assert-ok') var format = _dereq_('simple-format') var print = _dereq_('print-value') module.exports = function assertEqual (a, b) { assert(a === b, format('expected `%s` to equal `%s`', print(a), print(b))) } },{"assert-ok":13,"print-value":30,"simple-format":32}],12:[function(_dereq_,module,exports){ 'use strict' module.exports = function assertFunction (value) { if (typeof value !== 'function') { throw new TypeError('Expected function, got: ' + value) } } },{}],13:[function(_dereq_,module,exports){ 'use strict' module.exports = function assertOk (value, message) { if (!value) { throw new Error(message || 'Expected true, got ' + value) } } },{}],14:[function(_dereq_,module,exports){ 'use strict' module.exports = CallAll function CallAll (fns) { fns = Array.isArray(fns) ? fns : arguments return function callAll () { var args = arguments var ret = new Array(fns.length) for (var i = 0, ii = fns.length; i < ii; i++) { ret[i] = fns[i].apply(null, args) } return ret } } },{}],15:[function(_dereq_,module,exports){ /** * cuid.js * Collision-resistant UID generator for browsers and node. * Sequential for fast db lookups and recency sorting. * Safe for element IDs and server-side lookups. * * Extracted from CLCTR * * Copyright (c) Eric Elliott 2012 * MIT License */ /*global window, navigator, document, require, process, module */ (function (app) { 'use strict'; var namespace = 'cuid', c = 0, blockSize = 4, base = 36, discreteValues = Math.pow(base, blockSize), pad = function pad(num, size) { var s = "000000000" + num; return s.substr(s.length-size); }, randomBlock = function randomBlock() { return pad((Math.random() * discreteValues << 0) .toString(base), blockSize); }, safeCounter = function () { c = (c < discreteValues) ? c : 0; c++; // this is not subliminal return c - 1; }, api = function cuid() { // Starting with a lowercase letter makes // it HTML element ID friendly. var letter = 'c', // hard-coded allows for sequential access // timestamp // warning: this exposes the exact date and time // that the uid was created. timestamp = (new Date().getTime()).toString(base), // Prevent same-machine collisions. counter, // A few chars to generate distinct ids for different // clients (so different computers are far less // likely to generate the same id) fingerprint = api.fingerprint(), // Grab some more chars from Math.random() random = randomBlock() + randomBlock(); counter = pad(safeCounter().toString(base), blockSize); return (letter + timestamp + counter + fingerprint + random); }; api.slug = function slug() { var date = new Date().getTime().toString(36), counter, print = api.fingerprint().slice(0,1) + api.fingerprint().slice(-1), random = randomBlock().slice(-2); counter = safeCounter().toString(36).slice(-4); return date.slice(-2) + counter + print + random; }; api.globalCount = function globalCount() { // We want to cache the results of this var cache = (function calc() { var i, count = 0; for (i in window) { count++; } return count; }()); api.globalCount = function () { return cache; }; return cache; }; api.fingerprint = function browserPrint() { return pad((navigator.mimeTypes.length + navigator.userAgent.length).toString(36) + api.globalCount().toString(36), 4); }; // don't change anything from here down. if (app.register) { app.register(namespace, api); } else if (typeof module !== 'undefined') { module.exports = api; } else { app[namespace] = api; } }(this.applitude || this)); },{}],16:[function(_dereq_,module,exports){ var wrappy = _dereq_('wrappy') module.exports = wrappy(dezalgo) var asap = _dereq_('asap') function dezalgo (cb) { var sync = true asap(function () { sync = false }) return function zalgoSafe() { var args = arguments var me = this if (sync) asap(function() { cb.apply(me, args) }) else cb.apply(me, args) } } },{"asap":9,"wrappy":35}],17:[function(_dereq_,module,exports){ 'use strict'; var isObj = _dereq_('is-obj'); module.exports.get = function (obj, path) { if (!isObj(obj) || typeof path !== 'string') { return obj; } var pathArr = getPathSegments(path); for (var i = 0; i < pathArr.length; i++) { var descriptor = Object.getOwnPropertyDescriptor(obj, pathArr[i]) || Object.getOwnPropertyDescriptor(Object.prototype, pathArr[i]); if (descriptor && !descriptor.enumerable) { return; } obj = obj[pathArr[i]]; if (obj === undefined || obj === null) { // `obj` is either `undefined` or `null` so we want to stop the loop, and // if this is not the last bit of the path, and // if it did't return `undefined` // it would return `null` if `obj` is `null` // but we want `get({foo: null}, 'foo.bar')` to equal `undefined` not `null` if (i !== pathArr.length - 1) { return undefined; } break; } } return obj; }; module.exports.set = function (obj, path, value) { if (!isObj(obj) || typeof path !== 'string') { return; } var pathArr = getPathSegments(path); for (var i = 0; i < pathArr.length; i++) { var p = pathArr[i]; if (!isObj(obj[p])) { obj[p] = {}; } if (i === pathArr.length - 1) { obj[p] = value; } obj = obj[p]; } }; module.exports.delete = function (obj, path) { if (!isObj(obj) || typeof path !== 'string') { return; } var pathArr = getPathSegments(path); for (var i = 0; i < pathArr.length; i++) { var p = pathArr[i]; if (i === pathArr.length - 1) { delete obj[p]; return; } obj = obj[p]; } }; module.exports.has = function (obj, path) { if (!isObj(obj) || typeof path !== 'string') { return false; } var pathArr = getPathSegments(path); for (var i = 0; i < pathArr.length; i++) { obj = obj[pathArr[i]]; if (obj === undefined) { return false; } } return true; }; function getPathSegments(path) { var pathArr = path.split('.'); var parts = []; for (var i = 0; i < pathArr.length; i++) { var p = pathArr[i]; while (p[p.length - 1] === '\\' && pathArr[i + 1] !== undefined) { p = p.slice(0, -1) + '.'; p += pathArr[++i]; } parts.push(p); } return parts; } },{"is-obj":21}],18:[function(_dereq_,module,exports){ 'use strict' var assertFn = _dereq_('assert-function') module.exports = Ear function Ear () { var callbacks = [] function listeners () { var args = arguments var i = 0 var length = callbacks.length for (; i < length; i++) { var callback = callbacks[i] callback.apply(null, args) } } listeners.add = function (listener) { assertFn(listener) callbacks.push(listener) return function remove () { var i = 0 var length = callbacks.length for (; i < length; i++) { if (callbacks[i] === listener) { callbacks.splice(i, 1) return } } } } return listeners } },{"assert-function":12}],19:[function(_dereq_,module,exports){ (function (global){ var win; if (typeof window !== "undefined") { win = window; } else if (typeof global !== "undefined") { win = global; } else if (typeof self !== "undefined"){ win = self; } else { win = {}; } module.exports = win; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],20:[function(_dereq_,module,exports){ /*! * is-number * * Copyright (c) 2014 Jon Schlinkert, contributors. * Licensed under the MIT License */ 'use strict'; module.exports = function isNumber(n) { return !!(+n) || n === 0 || n === '0'; }; },{}],21:[function(_dereq_,module,exports){ 'use strict'; module.exports = function (x) { var type = typeof x; return x !== null && (type === 'object' || type === 'function'); }; },{}],22:[function(_dereq_,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; },{}],23:[function(_dereq_,module,exports){ /*! * isobject * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; var isArray = _dereq_('isarray'); module.exports = function isObject(o) { return o != null && typeof o === 'object' && !isArray(o); }; },{"isarray":22}],24:[function(_dereq_,module,exports){ exports = module.exports = stringify exports.getSerialize = serializer function stringify(obj, replacer, spaces, cycleReplacer) { return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces) } function serializer(replacer, cycleReplacer) { var stack = [], keys = [] if (cycleReplacer == null) cycleReplacer = function(key, value) { if (stack[0] === value) return "[Circular ~]" return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]" } return function(key, value) { if (stack.length > 0) { var thisPos = stack.indexOf(this) ~thisPos ? stack.splice(thisPos + 1) : stack.push(this) ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key) if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value) } else stack.push(value) return replacer == null ? value : replacer.call(this, key, value) } } },{}],25:[function(_dereq_,module,exports){ 'use strict' var assert = _dereq_('assert-ok') var assertEqual = _dereq_('assert-equal') var dot = _dereq_('dot-prop') var toArray = _dereq_('to-array') var last = _dereq_('array-last') var dezalgo = _dereq_('dezalgo') var all = _dereq_('call-all-fns') module.exports = Lazy function Lazy (methods, load) { assert(Array.isArray(methods), 'methods are required') assertEqual(typeof load, 'function', 'load fn is required') var api = null var error = null var queue = [] load(function (err, lib) { error = err api = lib all(queue)(err, lib) queue = null }) return methods.reduce(function (lazy, method) { dot.set(lazy, method, Deferred(method)) return lazy }, {}) function Deferred (method) { return function deferred () { var args = arguments onReady(function (err, api) { if (!err) return dot.get(api, method).apply(null, args) var callback = last(toArray(args)) if (typeof callback === 'function') { return callback(err) } }) } } function onReady (callback) { callback = dezalgo(callback) if (api || error) return callback(error, api) queue.push(callback) } } },{"array-last":7,"assert-equal":11,"assert-ok":13,"call-all-fns":14,"dezalgo":16,"dot-prop":26,"to-array":34}],26:[function(_dereq_,module,exports){ 'use strict'; var isObj = _dereq_('is-obj'); module.exports.get = function (obj, path) { if (!isObj(obj) || typeof path !== 'string') { return obj; } var pathArr = getPathSegments(path); for (var i = 0; i < pathArr.length; i++) { obj = obj[pathArr[i]]; if (obj === undefined) { break; } } return obj; }; module.exports.set = function (obj, path, value) { if (!isObj(obj) || typeof path !== 'string') { return; } var pathArr = getPathSegments(path); for (var i = 0; i < pathArr.length; i++) { var p = pathArr[i]; if (!isObj(obj[p])) { obj[p] = {}; } if (i === pathArr.length - 1) { obj[p] = value; } obj = obj[p]; } }; module.exports.delete = function (obj, path) { if (!isObj(obj) || typeof path !== 'string') { return; } var pathArr = getPathSegments(path); for (var i = 0; i < pathArr.length; i++) { var p = pathArr[i]; if (i === pathArr.length - 1) { delete obj[p]; return; } obj = obj[p]; } }; module.exports.has = function (obj, path) { if (!isObj(obj) || typeof path !== 'string') { return false; } var pathArr = getPathSegments(path); for (var i = 0; i < pathArr.length; i++) { obj = obj[pathArr[i]]; if (obj === undefined) { return false; } } return true; }; function getPathSegments(path) { var pathArr = path.split('.'); var parts = []; for (var i = 0; i < pathArr.length; i++) { var p = pathArr[i]; while (p[p.length - 1] === '\\') { p = p.slice(0, -1) + '.'; p += pathArr[++i]; } parts.push(p); } return parts; } },{"is-obj":21}],27:[function(_dereq_,module,exports){ 'use strict' var load = _dereq_('load-script') var window = _dereq_('global/window') var extend = _dereq_('xtend') var assert = _dereq_('assert-ok') var dezalgo = _dereq_('dezalgo') var Listeners = _dereq_('ear') var extendQuery = _dereq_('query-extend') var cuid = _dereq_('cuid') module.exports = loadGlobal var listeners = {} function loadGlobal (options, callback) { assert(options, 'options required') assert(options.url, 'url required') assert(options.global, 'global required') assert(callback, 'callback required') options = extend(options) callback = dezalgo(callback) if (getGlobal(options)) { return callback(null, getGlobal(options)) } callback = cache(options, callback) if (!callback) return if (options.jsonp) { var id = jsonpCallback(options, callback) options.url = extendQuery(options.url, {callback: id}) } load(options.url, options, function (err) { if (err) return callback(err) if (!options.jsonp) { var library = getGlobal(options) if (!library) return callback(new Error('expected: `window.' + options.global + '`, actual: `' + library + '`')) callback(null, library) } }) } function cache (options, callback) { if (!get()) { set(Listeners()) get().add(callback) return function onComplete (err, lib) { get()(err, lib) set(Listeners()) } } get().add(callback) return undefined function get () { return listeners[options.global] } function set (value) { listeners[options.global] = value } } function getGlobal (options) { return window[options.global] } function jsonpCallback (options, callback) { var id = cuid() window[id] = function jsonpCallback () { callback(null, getGlobal(options)) delete window[id] } return id } },{"assert-ok":13,"cuid":15,"dezalgo":16,"ear":18,"global/window":19,"load-script":28,"query-extend":31,"xtend":36}],28:[function(_dereq_,module,exports){ module.exports = function load (src, opts, cb) { var head = document.head || document.getElementsByTagName('head')[0] var script = document.createElement('script') if (typeof opts === 'function') { cb = opts opts = {} } opts = opts || {} cb = cb || function() {} script.type = opts.type || 'text/javascript' script.charset = opts.charset || 'utf8'; script.async = 'async' in opts ? !!opts.async : true script.src = src if (opts.attrs) { setAttributes(script, opts.attrs) } if (opts.text) { script.text = '' + opts.text } var onend = 'onload' in script ? stdOnEnd : ieOnEnd onend(script, cb) // some good legacy browsers (firefox) fail the 'in' detection above // so as a fallback we always set onload // old IE will ignore this and new IE will set onload if (!script.onload) { stdOnEnd(script, cb); } head.appendChild(script) } function setAttributes(script, attrs) { for (var attr in attrs) { script.setAttribute(attr, attrs[attr]); } } function stdOnEnd (script, cb) { script.onload = function () { this.onerror = this.onload = null cb(null, script) } script.onerror = function () { // this.onload = null here is necessary // because even IE9 works not like others this.onerror = this.onload = null cb(new Error('Failed to load ' + this.src), script) } } function ieOnEnd (script, cb) { script.onreadystatechange = function () { if (this.readyState != 'complete' && this.readyState != 'loaded') return this.onreadystatechange = null cb(null, script) // there is no way to catch loading errors in IE8 } } },{}],29:[function(_dereq_,module,exports){ 'use strict'; module.exports = function split(str) { var a = 1, res = ''; var parts = str.split('%'), len = parts.length; if (len > 0) { res += parts[0]; } for (var i = 1; i < len; i++) { if (parts[i][0] === 's' || parts[i][0] === 'd') { var value = arguments[a++]; res += parts[i][0] === 'd' ? Math.floor(value) : value; } else if (parts[i][0]) { res += '%' + parts[i][0]; } else { i++; res += '%' + parts[i][0]; } res += parts[i].substring(1); } return res; }; },{}],30:[function(_dereq_,module,exports){ 'use strict' var isObject = _dereq_('isobject') var safeStringify = _dereq_('json-stringify-safe') module.exports = function print (value) { var toString = isJson(value) ? stringify : String return toString(value) } function isJson (value) { return isObject(value) || Array.isArray(value) } function stringify (value) { return safeStringify(value, null, '') } },{"isobject":23,"json-stringify-safe":24}],31:[function(_dereq_,module,exports){ !function(glob) { var queryToObject = function(query) { var obj = {}; if (!query) return obj; each(query.split('&'), function(val) { var pieces = val.split('='); var key = parseKey(pieces[0]); var keyDecoded = decodeURIComponent(key.val); var valDecoded = pieces[1] && decodeURIComponent(pieces[1]); if (key.type === 'array') { if (!obj[keyDecoded]) obj[keyDecoded] = []; obj[keyDecoded].push(valDecoded); } else if (key.type === 'string') { obj[keyDecoded] = valDecoded; } }); return obj; }; var objectToQuery = function(obj) { var pieces = [], encodedKey; for (var k in obj) { if (!obj.hasOwnProperty(k)) continue; if (typeof obj[k] === 'undefined') { pieces.push(encodeURIComponent(k)); continue; } encodedKey = encodeURIComponent(k); if (isArray(obj[k])) { each(obj[k], function(val) { pieces.push(encodedKey + '[]=' + encodeURIComponent(val)); }); continue; } pieces.push(encodedKey + '=' + encodeURIComponent(obj[k])); } return pieces.length ? ('?' + pieces.join('&')) : ''; }; // for now we will only support string and arrays var parseKey = function(key) { var pos = key.indexOf('['); if (pos === -1) return { type: 'string', val: key }; return { type: 'array', val: key.substr(0, pos) }; }; var isArray = function(val) { return Object.prototype.toString.call(val) === '[object Array]'; }; var extract = function(url) { var pos = url.lastIndexOf('?'); var hasQuery = pos !== -1; var base = void 0; if (hasQuery && pos > 0) { base = url.substring(0, pos); } else if (!hasQuery && (url && url.length > 0)) { base = url; } return { base: base, query: hasQuery ? url.substring(pos+1) : void 0 }; }; // thanks raynos! // https://github.com/Raynos/xtend var extend = function() { var target = {}; for (var i = 0; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key]; } } } return target; }; var queryExtend = function() { var args = Array.prototype.slice.call(arguments, 0); var asObject = args[args.length-1] === true; var base = ''; if (!args.length) { return base; } if (asObject) { args.pop(); } var normalized = map(args, function(param) { if (typeof param === 'string') { var extracted = extract(param); if (extracted.base) base = extracted.base; return queryToObject(extracted.query); } return param; }); if (asObject) { return extend.apply({}, normalized); } else { return base + objectToQuery(extend.apply({}, normalized)); } }; var each = function(arr, fn) { for (var i = 0, l = arr.length; i < l; i++) { fn(arr[i], i); } }; var map = function(arr, fn) { var res = []; for (var i = 0, l = arr.length; i < l; i++) { res.push( fn(arr[i], i) ); } return res; }; if (typeof module !== 'undefined' && module.exports) { // Node.js / browserify module.exports = queryExtend; } else if (typeof define === 'function' && define.amd) { // require.js / AMD define(function() { return queryExtend; }); } else { // * * * * * * * * */ angular.module('ui.router', ['ui.router.state']); angular.module('ui.router.compat', ['ui.router']); /** * @ngdoc object * @name ui.router.util.$resolve * * @requires $q * @requires $injector * * @description * Manages resolution of (acyclic) graphs of promises. */ $Resolve.$inject = ['$q', '$injector']; function $Resolve( $q, $injector) { var VISIT_IN_PROGRESS = 1, VISIT_DONE = 2, NOTHING = {}, NO_DEPENDENCIES = [], NO_LOCALS = NOTHING, NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING }); /** * @ngdoc function * @name ui.router.util.$resolve#study * @methodOf ui.router.util.$resolve * * @description * Studies a set of invocables that are likely to be used multiple times. *
         * $resolve.study(invocables)(locals, parent, self)
         * 
      * is equivalent to *
         * $resolve.resolve(invocables, locals, parent, self)
         * 
      * but the former is more efficient (in fact `resolve` just calls `study` * internally). * * @param {object} invocables Invocable objects * @return {function} a function to pass in locals, parent and self */ this.study = function (invocables) { if (!isObject(invocables)) throw new Error("'invocables' must be an object"); var invocableKeys = objectKeys(invocables || {}); // Perform a topological sort of invocables to build an ordered plan var plan = [], cycle = [], visited = {}; function visit(value, key) { if (visited[key] === VISIT_DONE) return; cycle.push(key); if (visited[key] === VISIT_IN_PROGRESS) { cycle.splice(0, indexOf(cycle, key)); throw new Error("Cyclic dependency: " + cycle.join(" -> ")); } visited[key] = VISIT_IN_PROGRESS; if (isString(value)) { plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES); } else { var params = $injector.annotate(value); forEach(params, function (param) { if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param); }); plan.push(key, value, params); } cycle.pop(); visited[key] = VISIT_DONE; } forEach(invocables, visit); invocables = cycle = visited = null; // plan is all that's required function isResolve(value) { return isObject(value) && value.then && value.$$promises; } return function (locals, parent, self) { if (isResolve(locals) && self === undefined) { self = parent; parent = locals; locals = null; } if (!locals) locals = NO_LOCALS; else if (!isObject(locals)) { throw new Error("'locals' must be an object"); } if (!parent) parent = NO_PARENT; else if (!isResolve(parent)) { throw new Error("'parent' must be a promise returned by $resolve.resolve()"); } // To complete the overall resolution, we have to wait for the parent // promise and for the promise for each invokable in our plan. var resolution = $q.defer(), result = silenceUncaughtInPromise(resolution.promise), promises = result.$$promises = {}, values = extend({}, locals), wait = 1 + plan.length/3, merged = false; silenceUncaughtInPromise(result); function done() { // Merge parent values we haven't got yet and publish our own $$values if (!--wait) { if (!merged) merge(values, parent.$$values); result.$$values = values; result.$$promises = result.$$promises || true; // keep for isResolve() delete result.$$inheritedValues; resolution.resolve(values); } } function fail(reason) { result.$$failure = reason; resolution.reject(reason); } // Short-circuit if parent has already failed if (isDefined(parent.$$failure)) { fail(parent.$$failure); return result; } if (parent.$$inheritedValues) { merge(values, omit(parent.$$inheritedValues, invocableKeys)); } // Merge parent values if the parent has already resolved, or merge // parent promises and wait if the parent resolve is still in progress. extend(promises, parent.$$promises); if (parent.$$values) { merged = merge(values, omit(parent.$$values, invocableKeys)); result.$$inheritedValues = omit(parent.$$values, invocableKeys); done(); } else { if (parent.$$inheritedValues) { result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys); } parent.then(done, fail); } // Process each invocable in the plan, but ignore any where a local of the same name exists. for (var i=0, ii=plan.length; i * Impact on loading templates for more details about this mechanism. * * @param {boolean} value */ this.shouldUnsafelyUseHttp = function(value) { shouldUnsafelyUseHttp = !!value; }; /** * @ngdoc object * @name ui.router.util.$templateFactory * * @requires $http * @requires $templateCache * @requires $injector * * @description * Service. Manages loading of templates. */ this.$get = ['$http', '$templateCache', '$injector', function($http, $templateCache, $injector){ return new TemplateFactory($http, $templateCache, $injector, shouldUnsafelyUseHttp);}]; } /** * @ngdoc object * @name ui.router.util.$templateFactory * * @requires $http * @requires $templateCache * @requires $injector * * @description * Service. Manages loading of templates. */ function TemplateFactory($http, $templateCache, $injector, shouldUnsafelyUseHttp) { /** * @ngdoc function * @name ui.router.util.$templateFactory#fromConfig * @methodOf ui.router.util.$templateFactory * * @description * Creates a template from a configuration object. * * @param {object} config Configuration object for which to load a template. * The following properties are search in the specified order, and the first one * that is defined is used to create the template: * * @param {string|object} config.template html string template or function to * load via {@link ui.router.util.$templateFactory#fromString fromString}. * @param {string|object} config.templateUrl url to load or a function returning * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}. * @param {Function} config.templateProvider function to invoke via * {@link ui.router.util.$templateFactory#fromProvider fromProvider}. * @param {object} params Parameters to pass to the template function. * @param {object} locals Locals to pass to `invoke` if the template is loaded * via a `templateProvider`. Defaults to `{ params: params }`. * * @return {string|object} The template html as a string, or a promise for * that string,or `null` if no template is configured. */ this.fromConfig = function (config, params, locals) { return ( isDefined(config.template) ? this.fromString(config.template, params) : isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) : isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) : null ); }; /** * @ngdoc function * @name ui.router.util.$templateFactory#fromString * @methodOf ui.router.util.$templateFactory * * @description * Creates a template from a string or a function returning a string. * * @param {string|object} template html template as a string or function that * returns an html template as a string. * @param {object} params Parameters to pass to the template function. * * @return {string|object} The template html as a string, or a promise for that * string. */ this.fromString = function (template, params) { return isFunction(template) ? template(params) : template; }; /** * @ngdoc function * @name ui.router.util.$templateFactory#fromUrl * @methodOf ui.router.util.$templateFactory * * @description * Loads a template from the a URL via `$http` and `$templateCache`. * * @param {string|Function} url url of the template to load, or a function * that returns a url. * @param {Object} params Parameters to pass to the url function. * @return {string|Promise.} The template html as a string, or a promise * for that string. */ this.fromUrl = function (url, params) { if (isFunction(url)) url = url(params); if (url == null) return null; else { if(!shouldUnsafelyUseHttp) { return $injector.get('$templateRequest')(url); } else { return $http .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }}) .then(function(response) { return response.data; }); } } }; /** * @ngdoc function * @name ui.router.util.$templateFactory#fromProvider * @methodOf ui.router.util.$templateFactory * * @description * Creates a template by invoking an injectable provider function. * * @param {Function} provider Function to invoke via `$injector.invoke` * @param {Object} params Parameters for the template. * @param {Object} locals Locals to pass to `invoke`. Defaults to * `{ params: params }`. * @return {string|Promise.} The template html as a string, or a promise * for that string. */ this.fromProvider = function (provider, params, locals) { return $injector.invoke(provider, null, locals || { params: params }); }; } angular.module('ui.router.util').provider('$templateFactory', TemplateFactoryProvider); var $$UMFP; // reference to $UrlMatcherFactoryProvider /** * @ngdoc object * @name ui.router.util.type:UrlMatcher * * @description * Matches URLs against patterns and extracts named parameters from the path or the search * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list * of search parameters. Multiple search parameter names are separated by '&'. Search parameters * do not influence whether or not a URL is matched, but their values are passed through into * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}. * * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace * syntax, which optionally allows a regular expression for the parameter to be specified: * * * `':'` name - colon placeholder * * `'*'` name - catch-all placeholder * * `'{' name '}'` - curly placeholder * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the * regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash. * * Parameter names may contain only word characters (latin letters, digits, and underscore) and * must be unique within the pattern (across both path and search parameters). For colon * placeholders or curly placeholders without an explicit regexp, a path parameter matches any * number of characters other than '/'. For catch-all placeholders the path parameter matches * any number of characters. * * Examples: * * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for * trailing slashes, and patterns have to match the entire path, not just a prefix. * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or * '/user/bob/details'. The second path segment will be captured as the parameter 'id'. * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax. * * `'/user/{id:[^/]*}'` - Same as the previous example. * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id * parameter consists of 1 to 8 hex digits. * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the * path into the parameter 'path'. * * `'/files/*path'` - ditto. * * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined * in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start * * @param {string} pattern The pattern to compile into a matcher. * @param {Object} config A configuration object hash: * @param {Object=} parentMatcher Used to concatenate the pattern/config onto * an existing UrlMatcher * * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`. * * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`. * * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns * non-null) will start with this prefix. * * @property {string} source The pattern that was passed into the constructor * * @property {string} sourcePath The path portion of the source property * * @property {string} sourceSearch The search portion of the source property * * @property {string} regex The constructed regex that will be used to match against the url when * it is time to determine which url will match. * * @returns {Object} New `UrlMatcher` object */ function UrlMatcher(pattern, config, parentMatcher) { config = extend({ params: {} }, isObject(config) ? config : {}); // Find all placeholders and create a compiled pattern, using either classic or curly syntax: // '*' name // ':' name // '{' name '}' // '{' name ':' regexp '}' // The regular expression is somewhat complicated due to the need to allow curly braces // inside the regular expression. The placeholder regexp breaks down as follows: // ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case) // \{([\w\[\]]+)(?:\:\s*( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either // [^{}\\]+ - anything other than curly braces or backslash // \\. - a backslash escape // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g, searchPlaceholder = /([:]?)([\w\[\].-]+)|\{([\w\[\].-]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g, compiled = '^', last = 0, m, segments = this.segments = [], parentParams = parentMatcher ? parentMatcher.params : {}, params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(), paramNames = []; function addParameter(id, type, config, location) { paramNames.push(id); if (parentParams[id]) return parentParams[id]; if (!/^\w+([-.]+\w+)*(?:\[\])?$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'"); if (params[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'"); params[id] = new $$UMFP.Param(id, type, config, location); return params[id]; } function quoteRegExp(string, pattern, squash, optional) { var surroundPattern = ['',''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&"); if (!pattern) return result; switch(squash) { case false: surroundPattern = ['(', ')' + (optional ? "?" : "")]; break; case true: result = result.replace(/\/$/, ''); surroundPattern = ['(?:\/(', ')|\/)?']; break; default: surroundPattern = ['(' + squash + "|", ')?']; break; } return result + surroundPattern[0] + pattern + surroundPattern[1]; } this.source = pattern; // Split into static segments separated by path parameter placeholders. // The number of segments is always 1 more than the number of parameters. function matchDetails(m, isSearch) { var id, regexp, segment, type, cfg, arrayMode; id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null cfg = config.params[id]; segment = pattern.substring(last, m.index); regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null); if (regexp) { type = $$UMFP.type(regexp) || inherit($$UMFP.type("string"), { pattern: new RegExp(regexp, config.caseInsensitive ? 'i' : undefined) }); } return { id: id, regexp: regexp, segment: segment, type: type, cfg: cfg }; } var p, param, segment; while ((m = placeholder.exec(pattern))) { p = matchDetails(m, false); if (p.segment.indexOf('?') >= 0) break; // we're into the search part param = addParameter(p.id, p.type, p.cfg, "path"); compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash, param.isOptional); segments.push(p.segment); last = placeholder.lastIndex; } segment = pattern.substring(last); // Find any search parameter names and remove them from the last segment var i = segment.indexOf('?'); if (i >= 0) { var search = this.sourceSearch = segment.substring(i); segment = segment.substring(0, i); this.sourcePath = pattern.substring(0, last + i); if (search.length > 0) { last = 0; while ((m = searchPlaceholder.exec(search))) { p = matchDetails(m, true); param = addParameter(p.id, p.type, p.cfg, "search"); last = placeholder.lastIndex; // check if ?& } } } else { this.sourcePath = pattern; this.sourceSearch = ''; } compiled += quoteRegExp(segment) + (config.strict === false ? '\/?' : '') + '$'; segments.push(segment); this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined); this.prefix = segments[0]; this.$$paramNames = paramNames; } /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#concat * @methodOf ui.router.util.type:UrlMatcher * * @description * Returns a new matcher for a pattern constructed by appending the path part and adding the * search parameters of the specified pattern to this pattern. The current pattern is not * modified. This can be understood as creating a pattern for URLs that are relative to (or * suffixes of) the current pattern. * * @example * The following two matchers are equivalent: *
       * new UrlMatcher('/user/{id}?q').concat('/details?date');
       * new UrlMatcher('/user/{id}/details?q&date');
       * 
      * * @param {string} pattern The pattern to append. * @param {Object} config An object hash of the configuration for the matcher. * @returns {UrlMatcher} A matcher for the concatenated pattern. */ UrlMatcher.prototype.concat = function (pattern, config) { // Because order of search parameters is irrelevant, we can add our own search // parameters to the end of the new pattern. Parse the new pattern by itself // and then join the bits together, but it's much easier to do this on a string level. var defaultConfig = { caseInsensitive: $$UMFP.caseInsensitive(), strict: $$UMFP.strictMode(), squash: $$UMFP.defaultSquashPolicy() }; return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this); }; UrlMatcher.prototype.toString = function () { return this.source; }; /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#exec * @methodOf ui.router.util.type:UrlMatcher * * @description * Tests the specified path against this matcher, and returns an object containing the captured * parameter values, or null if the path does not match. The returned object contains the values * of any search parameters that are mentioned in the pattern, but their value may be null if * they are not present in `searchParams`. This means that search parameters are always treated * as optional. * * @example *
       * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {
       *   x: '1', q: 'hello'
       * });
       * // returns { id: 'bob', q: 'hello', r: null }
       * 
      * * @param {string} path The URL path to match, e.g. `$location.path()`. * @param {Object} searchParams URL search parameters, e.g. `$location.search()`. * @returns {Object} The captured parameter values. */ UrlMatcher.prototype.exec = function (path, searchParams) { var m = this.regexp.exec(path); if (!m) return null; searchParams = searchParams || {}; var paramNames = this.parameters(), nTotal = paramNames.length, nPath = this.segments.length - 1, values = {}, i, j, cfg, paramName; if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'"); function decodePathArray(string) { function reverseString(str) { return str.split("").reverse().join(""); } function unquoteDashes(str) { return str.replace(/\\-/g, "-"); } var split = reverseString(string).split(/-(?!\\)/); var allReversed = map(split, reverseString); return map(allReversed, unquoteDashes).reverse(); } var param, paramVal; for (i = 0; i < nPath; i++) { paramName = paramNames[i]; param = this.params[paramName]; paramVal = m[i+1]; // if the param value matches a pre-replace pair, replace the value before decoding. for (j = 0; j < param.replace.length; j++) { if (param.replace[j].from === paramVal) paramVal = param.replace[j].to; } if (paramVal && param.array === true) paramVal = decodePathArray(paramVal); if (isDefined(paramVal)) paramVal = param.type.decode(paramVal); values[paramName] = param.value(paramVal); } for (/**/; i < nTotal; i++) { paramName = paramNames[i]; values[paramName] = this.params[paramName].value(searchParams[paramName]); param = this.params[paramName]; paramVal = searchParams[paramName]; for (j = 0; j < param.replace.length; j++) { if (param.replace[j].from === paramVal) paramVal = param.replace[j].to; } if (isDefined(paramVal)) paramVal = param.type.decode(paramVal); values[paramName] = param.value(paramVal); } return values; }; /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#parameters * @methodOf ui.router.util.type:UrlMatcher * * @description * Returns the names of all path and search parameters of this pattern in an unspecified order. * * @returns {Array.} An array of parameter names. Must be treated as read-only. If the * pattern has no parameters, an empty array is returned. */ UrlMatcher.prototype.parameters = function (param) { if (!isDefined(param)) return this.$$paramNames; return this.params[param] || null; }; /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#validates * @methodOf ui.router.util.type:UrlMatcher * * @description * Checks an object hash of parameters to validate their correctness according to the parameter * types of this `UrlMatcher`. * * @param {Object} params The object hash of parameters to validate. * @returns {boolean} Returns `true` if `params` validates, otherwise `false`. */ UrlMatcher.prototype.validates = function (params) { return this.params.$$validates(params); }; /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#format * @methodOf ui.router.util.type:UrlMatcher * * @description * Creates a URL that matches this pattern by substituting the specified values * for the path and search parameters. Null values for path parameters are * treated as empty strings. * * @example *
       * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });
       * // returns '/user/bob?q=yes'
       * 
      * * @param {Object} values the values to substitute for the parameters in this pattern. * @returns {string} the formatted URL (path and optionally search part). */ UrlMatcher.prototype.format = function (values) { values = values || {}; var segments = this.segments, params = this.parameters(), paramset = this.params; if (!this.validates(values)) return null; var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0]; function encodeDashes(str) { // Replace dashes with encoded "\-" return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); }); } for (i = 0; i < nTotal; i++) { var isPathParam = i < nPath; var name = params[i], param = paramset[name], value = param.value(values[name]); var isDefaultValue = param.isOptional && param.type.equals(param.value(), value); var squash = isDefaultValue ? param.squash : false; var encoded = param.type.encode(value); if (isPathParam) { var nextSegment = segments[i + 1]; var isFinalPathParam = i + 1 === nPath; if (squash === false) { if (encoded != null) { if (isArray(encoded)) { result += map(encoded, encodeDashes).join("-"); } else { result += encodeURIComponent(encoded); } } result += nextSegment; } else if (squash === true) { var capture = result.match(/\/$/) ? /\/?(.*)/ : /(.*)/; result += nextSegment.match(capture)[1]; } else if (isString(squash)) { result += squash + nextSegment; } if (isFinalPathParam && param.squash === true && result.slice(-1) === '/') result = result.slice(0, -1); } else { if (encoded == null || (isDefaultValue && squash !== false)) continue; if (!isArray(encoded)) encoded = [ encoded ]; if (encoded.length === 0) continue; encoded = map(encoded, encodeURIComponent).join('&' + name + '='); result += (search ? '&' : '?') + (name + '=' + encoded); search = true; } } return result; }; /** * @ngdoc object * @name ui.router.util.type:Type * * @description * Implements an interface to define custom parameter types that can be decoded from and encoded to * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`} * objects when matching or formatting URLs, or comparing or validating parameter values. * * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more * information on registering custom types. * * @param {Object} config A configuration object which contains the custom type definition. The object's * properties will override the default methods and/or pattern in `Type`'s public interface. * @example *
       * {
       *   decode: function(val) { return parseInt(val, 10); },
       *   encode: function(val) { return val && val.toString(); },
       *   equals: function(a, b) { return this.is(a) && a === b; },
       *   is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },
       *   pattern: /\d+/
       * }
       * 
      * * @property {RegExp} pattern The regular expression pattern used to match values of this type when * coming from a substring of a URL. * * @returns {Object} Returns a new `Type` object. */ function Type(config) { extend(this, config); } /** * @ngdoc function * @name ui.router.util.type:Type#is * @methodOf ui.router.util.type:Type * * @description * Detects whether a value is of a particular type. Accepts a native (decoded) value * and determines whether it matches the current `Type` object. * * @param {*} val The value to check. * @param {string} key Optional. If the type check is happening in the context of a specific * {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the * parameter in which `val` is stored. Can be used for meta-programming of `Type` objects. * @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`. */ Type.prototype.is = function(val, key) { return true; }; /** * @ngdoc function * @name ui.router.util.type:Type#encode * @methodOf ui.router.util.type:Type * * @description * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it * only needs to be a representation of `val` that has been coerced to a string. * * @param {*} val The value to encode. * @param {string} key The name of the parameter in which `val` is stored. Can be used for * meta-programming of `Type` objects. * @returns {string} Returns a string representation of `val` that can be encoded in a URL. */ Type.prototype.encode = function(val, key) { return val; }; /** * @ngdoc function * @name ui.router.util.type:Type#decode * @methodOf ui.router.util.type:Type * * @description * Converts a parameter value (from URL string or transition param) to a custom/native value. * * @param {string} val The URL parameter value to decode. * @param {string} key The name of the parameter in which `val` is stored. Can be used for * meta-programming of `Type` objects. * @returns {*} Returns a custom representation of the URL parameter value. */ Type.prototype.decode = function(val, key) { return val; }; /** * @ngdoc function * @name ui.router.util.type:Type#equals * @methodOf ui.router.util.type:Type * * @description * Determines whether two decoded values are equivalent. * * @param {*} a A value to compare against. * @param {*} b A value to compare against. * @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`. */ Type.prototype.equals = function(a, b) { return a == b; }; Type.prototype.$subPattern = function() { var sub = this.pattern.toString(); return sub.substr(1, sub.length - 2); }; Type.prototype.pattern = /.*/; Type.prototype.toString = function() { return "{Type:" + this.name + "}"; }; /** Given an encoded string, or a decoded object, returns a decoded object */ Type.prototype.$normalize = function(val) { return this.is(val) ? val : this.decode(val); }; /* * Wraps an existing custom Type as an array of Type, depending on 'mode'. * e.g.: * - urlmatcher pattern "/path?{queryParam[]:int}" * - url: "/path?queryParam=1&queryParam=2 * - $stateParams.queryParam will be [1, 2] * if `mode` is "auto", then * - url: "/path?queryParam=1 will create $stateParams.queryParam: 1 * - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2] */ Type.prototype.$asArray = function(mode, isSearch) { if (!mode) return this; if (mode === "auto" && !isSearch) throw new Error("'auto' array mode is for query parameters only"); function ArrayType(type, mode) { function bindTo(type, callbackName) { return function() { return type[callbackName].apply(type, arguments); }; } // Wrap non-array value as array function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); } // Unwrap array value for "auto" mode. Return undefined for empty array. function arrayUnwrap(val) { switch(val.length) { case 0: return undefined; case 1: return mode === "auto" ? val[0] : val; default: return val; } } function falsey(val) { return !val; } // Wraps type (.is/.encode/.decode) functions to operate on each value of an array function arrayHandler(callback, allTruthyMode) { return function handleArray(val) { if (isArray(val) && val.length === 0) return val; val = arrayWrap(val); var result = map(val, callback); if (allTruthyMode === true) return filter(result, falsey).length === 0; return arrayUnwrap(result); }; } // Wraps type (.equals) functions to operate on each value of an array function arrayEqualsHandler(callback) { return function handleArray(val1, val2) { var left = arrayWrap(val1), right = arrayWrap(val2); if (left.length !== right.length) return false; for (var i = 0; i < left.length; i++) { if (!callback(left[i], right[i])) return false; } return true; }; } this.encode = arrayHandler(bindTo(type, 'encode')); this.decode = arrayHandler(bindTo(type, 'decode')); this.is = arrayHandler(bindTo(type, 'is'), true); this.equals = arrayEqualsHandler(bindTo(type, 'equals')); this.pattern = type.pattern; this.$normalize = arrayHandler(bindTo(type, '$normalize')); this.name = type.name; this.$arrayMode = mode; } return new ArrayType(this, mode); }; /** * @ngdoc object * @name ui.router.util.$urlMatcherFactory * * @description * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory * is also available to providers under the name `$urlMatcherFactoryProvider`. */ function $UrlMatcherFactory() { $$UMFP = this; var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false; // Use tildes to pre-encode slashes. // If the slashes are simply URLEncoded, the browser can choose to pre-decode them, // and bidirectional encoding/decoding fails. // Tilde was chosen because it's not a RFC 3986 section 2.2 Reserved Character function valToString(val) { return val != null ? val.toString().replace(/(~|\/)/g, function (m) { return {'~':'~~', '/':'~2F'}[m]; }) : val; } function valFromString(val) { return val != null ? val.toString().replace(/(~~|~2F)/g, function (m) { return {'~~':'~', '~2F':'/'}[m]; }) : val; } var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = { "string": { encode: valToString, decode: valFromString, // TODO: in 1.0, make string .is() return false if value is undefined/null by default. // In 0.2.x, string params are optional by default for backwards compat is: function(val) { return val == null || !isDefined(val) || typeof val === "string"; }, pattern: /[^/]*/ }, "int": { encode: valToString, decode: function(val) { return parseInt(val, 10); }, is: function(val) { return val !== undefined && val !== null && this.decode(val.toString()) === val; }, pattern: /\d+/ }, "bool": { encode: function(val) { return val ? 1 : 0; }, decode: function(val) { return parseInt(val, 10) !== 0; }, is: function(val) { return val === true || val === false; }, pattern: /0|1/ }, "date": { encode: function (val) { if (!this.is(val)) return undefined; return [ val.getFullYear(), ('0' + (val.getMonth() + 1)).slice(-2), ('0' + val.getDate()).slice(-2) ].join("-"); }, decode: function (val) { if (this.is(val)) return val; var match = this.capture.exec(val); return match ? new Date(match[1], match[2] - 1, match[3]) : undefined; }, is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); }, equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); }, pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/, capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/ }, "json": { encode: angular.toJson, decode: angular.fromJson, is: angular.isObject, equals: angular.equals, pattern: /[^/]*/ }, "any": { // does not encode/decode encode: angular.identity, decode: angular.identity, equals: angular.equals, pattern: /.*/ } }; function getDefaultConfig() { return { strict: isStrictMode, caseInsensitive: isCaseInsensitive }; } function isInjectable(value) { return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1]))); } /** * [Internal] Get the default value of a parameter, which may be an injectable function. */ $UrlMatcherFactory.$$getDefaultValue = function(config) { if (!isInjectable(config.value)) return config.value; if (!injector) throw new Error("Injectable functions cannot be called at configuration time"); return injector.invoke(config.value); }; /** * @ngdoc function * @name ui.router.util.$urlMatcherFactory#caseInsensitive * @methodOf ui.router.util.$urlMatcherFactory * * @description * Defines whether URL matching should be case sensitive (the default behavior), or not. * * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`; * @returns {boolean} the current value of caseInsensitive */ this.caseInsensitive = function(value) { if (isDefined(value)) isCaseInsensitive = value; return isCaseInsensitive; }; /** * @ngdoc function * @name ui.router.util.$urlMatcherFactory#strictMode * @methodOf ui.router.util.$urlMatcherFactory * * @description * Defines whether URLs should match trailing slashes, or not (the default behavior). * * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`. * @returns {boolean} the current value of strictMode */ this.strictMode = function(value) { if (isDefined(value)) isStrictMode = value; return isStrictMode; }; /** * @ngdoc function * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy * @methodOf ui.router.util.$urlMatcherFactory * * @description * Sets the default behavior when generating or matching URLs with default parameter values. * * @param {string} value A string that defines the default parameter URL squashing behavior. * `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL * `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the * parameter is surrounded by slashes, squash (remove) one slash from the URL * any other string, e.g. "~": When generating an href with a default parameter value, squash (remove) * the parameter value from the URL and replace it with this string. */ this.defaultSquashPolicy = function(value) { if (!isDefined(value)) return defaultSquashPolicy; if (value !== true && value !== false && !isString(value)) throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string"); defaultSquashPolicy = value; return value; }; /** * @ngdoc function * @name ui.router.util.$urlMatcherFactory#compile * @methodOf ui.router.util.$urlMatcherFactory * * @description * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern. * * @param {string} pattern The URL pattern. * @param {Object} config The config object hash. * @returns {UrlMatcher} The UrlMatcher. */ this.compile = function (pattern, config) { return new UrlMatcher(pattern, extend(getDefaultConfig(), config)); }; /** * @ngdoc function * @name ui.router.util.$urlMatcherFactory#isMatcher * @methodOf ui.router.util.$urlMatcherFactory * * @description * Returns true if the specified object is a `UrlMatcher`, or false otherwise. * * @param {Object} object The object to perform the type check against. * @returns {Boolean} Returns `true` if the object matches the `UrlMatcher` interface, by * implementing all the same methods. */ this.isMatcher = function (o) { if (!isObject(o)) return false; var result = true; forEach(UrlMatcher.prototype, function(val, name) { if (isFunction(val)) { result = result && (isDefined(o[name]) && isFunction(o[name])); } }); return result; }; /** * @ngdoc function * @name ui.router.util.$urlMatcherFactory#type * @methodOf ui.router.util.$urlMatcherFactory * * @description * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to * generate URLs with typed parameters. * * @param {string} name The type name. * @param {Object|Function} definition The type definition. See * {@link ui.router.util.type:Type `Type`} for information on the values accepted. * @param {Object|Function} definitionFn (optional) A function that is injected before the app * runtime starts. The result of this function is merged into the existing `definition`. * See {@link ui.router.util.type:Type `Type`} for information on the values accepted. * * @returns {Object} Returns `$urlMatcherFactoryProvider`. * * @example * This is a simple example of a custom type that encodes and decodes items from an * array, using the array index as the URL-encoded value: * *
         * var list = ['John', 'Paul', 'George', 'Ringo'];
         *
         * $urlMatcherFactoryProvider.type('listItem', {
         *   encode: function(item) {
         *     // Represent the list item in the URL using its corresponding index
         *     return list.indexOf(item);
         *   },
         *   decode: function(item) {
         *     // Look up the list item by index
         *     return list[parseInt(item, 10)];
         *   },
         *   is: function(item) {
         *     // Ensure the item is valid by checking to see that it appears
         *     // in the list
         *     return list.indexOf(item) > -1;
         *   }
         * });
         *
         * $stateProvider.state('list', {
         *   url: "/list/{item:listItem}",
         *   controller: function($scope, $stateParams) {
         *     console.log($stateParams.item);
         *   }
         * });
         *
         * // ...
         *
         * // Changes URL to '/list/3', logs "Ringo" to the console
         * $state.go('list', { item: "Ringo" });
         * 
      * * This is a more complex example of a type that relies on dependency injection to * interact with services, and uses the parameter name from the URL to infer how to * handle encoding and decoding parameter values: * *
         * // Defines a custom type that gets a value from a service,
         * // where each service gets different types of values from
         * // a backend API:
         * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {
         *
         *   // Matches up services to URL parameter names
         *   var services = {
         *     user: Users,
         *     post: Posts
         *   };
         *
         *   return {
         *     encode: function(object) {
         *       // Represent the object in the URL using its unique ID
         *       return object.id;
         *     },
         *     decode: function(value, key) {
         *       // Look up the object by ID, using the parameter
         *       // name (key) to call the correct service
         *       return services[key].findById(value);
         *     },
         *     is: function(object, key) {
         *       // Check that object is a valid dbObject
         *       return angular.isObject(object) && object.id && services[key];
         *     }
         *     equals: function(a, b) {
         *       // Check the equality of decoded objects by comparing
         *       // their unique IDs
         *       return a.id === b.id;
         *     }
         *   };
         * });
         *
         * // In a config() block, you can then attach URLs with
         * // type-annotated parameters:
         * $stateProvider.state('users', {
         *   url: "/users",
         *   // ...
         * }).state('users.item', {
         *   url: "/{user:dbObject}",
         *   controller: function($scope, $stateParams) {
         *     // $stateParams.user will now be an object returned from
         *     // the Users service
         *   },
         *   // ...
         * });
         * 
      */ this.type = function (name, definition, definitionFn) { if (!isDefined(definition)) return $types[name]; if ($types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined."); $types[name] = new Type(extend({ name: name }, definition)); if (definitionFn) { typeQueue.push({ name: name, def: definitionFn }); if (!enqueue) flushTypeQueue(); } return this; }; // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s function flushTypeQueue() { while(typeQueue.length) { var type = typeQueue.shift(); if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime."); angular.extend($types[type.name], injector.invoke(type.def)); } } // Register default types. Store them in the prototype of $types. forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); }); $types = inherit($types, {}); /* No need to document $get, since it returns this */ this.$get = ['$injector', function ($injector) { injector = $injector; enqueue = false; flushTypeQueue(); forEach(defaultTypes, function(type, name) { if (!$types[name]) $types[name] = new Type(type); }); return this; }]; this.Param = function Param(id, type, config, location) { var self = this; config = unwrapShorthand(config); type = getType(config, type, location); var arrayMode = getArrayMode(); type = arrayMode ? type.$asArray(arrayMode, location === "search") : type; if (type.name === "string" && !arrayMode && location === "path" && config.value === undefined) config.value = ""; // for 0.2.x; in 0.3.0+ do not automatically default to "" var isOptional = config.value !== undefined; var squash = getSquashPolicy(config, isOptional); var replace = getReplace(config, arrayMode, isOptional, squash); function unwrapShorthand(config) { var keys = isObject(config) ? objectKeys(config) : []; var isShorthand = indexOf(keys, "value") === -1 && indexOf(keys, "type") === -1 && indexOf(keys, "squash") === -1 && indexOf(keys, "array") === -1; if (isShorthand) config = { value: config }; config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; }; return config; } function getType(config, urlType, location) { if (config.type && urlType) throw new Error("Param '"+id+"' has two type configurations."); if (urlType) return urlType; if (!config.type) return (location === "config" ? $types.any : $types.string); if (angular.isString(config.type)) return $types[config.type]; if (config.type instanceof Type) return config.type; return new Type(config.type); } // array config: param name (param[]) overrides default settings. explicit config overrides param name. function getArrayMode() { var arrayDefaults = { array: (location === "search" ? "auto" : false) }; var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {}; return extend(arrayDefaults, arrayParamNomenclature, config).array; } /** * returns false, true, or the squash value to indicate the "default parameter url squash policy". */ function getSquashPolicy(config, isOptional) { var squash = config.squash; if (!isOptional || squash === false) return false; if (!isDefined(squash) || squash == null) return defaultSquashPolicy; if (squash === true || isString(squash)) return squash; throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string"); } function getReplace(config, arrayMode, isOptional, squash) { var replace, configuredKeys, defaultPolicy = [ { from: "", to: (isOptional || arrayMode ? undefined : "") }, { from: null, to: (isOptional || arrayMode ? undefined : "") } ]; replace = isArray(config.replace) ? config.replace : []; if (isString(squash)) replace.push({ from: squash, to: undefined }); configuredKeys = map(replace, function(item) { return item.from; } ); return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace); } /** * [Internal] Get the default value of a parameter, which may be an injectable function. */ function $$getDefaultValue() { if (!injector) throw new Error("Injectable functions cannot be called at configuration time"); var defaultValue = injector.invoke(config.$$fn); if (defaultValue !== null && defaultValue !== undefined && !self.type.is(defaultValue)) throw new Error("Default value (" + defaultValue + ") for parameter '" + self.id + "' is not an instance of Type (" + self.type.name + ")"); return defaultValue; } /** * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the * default value, which may be the result of an injectable function. */ function $value(value) { function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; } function $replace(value) { var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; }); return replacement.length ? replacement[0] : value; } value = $replace(value); return !isDefined(value) ? $$getDefaultValue() : self.type.$normalize(value); } function toString() { return "{Param:" + id + " " + type + " squash: '" + squash + "' optional: " + isOptional + "}"; } extend(this, { id: id, type: type, location: location, array: arrayMode, squash: squash, replace: replace, isOptional: isOptional, value: $value, dynamic: undefined, config: config, toString: toString }); }; function ParamSet(params) { extend(this, params || {}); } ParamSet.prototype = { $$new: function() { return inherit(this, extend(new ParamSet(), { $$parent: this})); }, $$keys: function () { var keys = [], chain = [], parent = this, ignore = objectKeys(ParamSet.prototype); while (parent) { chain.push(parent); parent = parent.$$parent; } chain.reverse(); forEach(chain, function(paramset) { forEach(objectKeys(paramset), function(key) { if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key); }); }); return keys; }, $$values: function(paramValues) { var values = {}, self = this; forEach(self.$$keys(), function(key) { values[key] = self[key].value(paramValues && paramValues[key]); }); return values; }, $$equals: function(paramValues1, paramValues2) { var equal = true, self = this; forEach(self.$$keys(), function(key) { var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key]; if (!self[key].type.equals(left, right)) equal = false; }); return equal; }, $$validates: function $$validate(paramValues) { var keys = this.$$keys(), i, param, rawVal, normalized, encoded; for (i = 0; i < keys.length; i++) { param = this[keys[i]]; rawVal = paramValues[keys[i]]; if ((rawVal === undefined || rawVal === null) && param.isOptional) break; // There was no parameter value, but the param is optional normalized = param.type.$normalize(rawVal); if (!param.type.is(normalized)) return false; // The value was not of the correct Type, and could not be decoded to the correct Type encoded = param.type.encode(normalized); if (angular.isString(encoded) && !param.type.pattern.exec(encoded)) return false; // The value was of the correct type, but when encoded, did not match the Type's regexp } return true; }, $$parent: undefined }; this.ParamSet = ParamSet; } // Register as a provider so it's available to other providers angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory); angular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]); /** * @ngdoc object * @name ui.router.router.$urlRouterProvider * * @requires ui.router.util.$urlMatcherFactoryProvider * @requires $locationProvider * * @description * `$urlRouterProvider` has the responsibility of watching `$location`. * When `$location` changes it runs through a list of rules one by one until a * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify * a url in a state configuration. All urls are compiled into a UrlMatcher object. * * There are several methods on `$urlRouterProvider` that make it useful to use directly * in your module config. */ $UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider']; function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) { var rules = [], otherwise = null, interceptDeferred = false, listener; // Returns a string that is a prefix of all strings matching the RegExp function regExpPrefix(re) { var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source); return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : ''; } // Interpolates matched values into a String.replace()-style pattern function interpolate(pattern, match) { return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) { return match[what === '$' ? 0 : Number(what)]; }); } /** * @ngdoc function * @name ui.router.router.$urlRouterProvider#rule * @methodOf ui.router.router.$urlRouterProvider * * @description * Defines rules that are used by `$urlRouterProvider` to find matches for * specific URLs. * * @example *
         * var app = angular.module('app', ['ui.router.router']);
         *
         * app.config(function ($urlRouterProvider) {
         *   // Here's an example of how you might allow case insensitive urls
         *   $urlRouterProvider.rule(function ($injector, $location) {
         *     var path = $location.path(),
         *         normalized = path.toLowerCase();
         *
         *     if (path !== normalized) {
         *       return normalized;
         *     }
         *   });
         * });
         * 
      * * @param {function} rule Handler function that takes `$injector` and `$location` * services as arguments. You can use them to return a valid path as a string. * * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance */ this.rule = function (rule) { if (!isFunction(rule)) throw new Error("'rule' must be a function"); rules.push(rule); return this; }; /** * @ngdoc object * @name ui.router.router.$urlRouterProvider#otherwise * @methodOf ui.router.router.$urlRouterProvider * * @description * Defines a path that is used when an invalid route is requested. * * @example *
         * var app = angular.module('app', ['ui.router.router']);
         *
         * app.config(function ($urlRouterProvider) {
         *   // if the path doesn't match any of the urls you configured
         *   // otherwise will take care of routing the user to the
         *   // specified url
         *   $urlRouterProvider.otherwise('/index');
         *
         *   // Example of using function rule as param
         *   $urlRouterProvider.otherwise(function ($injector, $location) {
         *     return '/a/valid/url';
         *   });
         * });
         * 
      * * @param {string|function} rule The url path you want to redirect to or a function * rule that returns the url path. The function version is passed two params: * `$injector` and `$location` services, and must return a url string. * * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance */ this.otherwise = function (rule) { if (isString(rule)) { var redirect = rule; rule = function () { return redirect; }; } else if (!isFunction(rule)) throw new Error("'rule' must be a function"); otherwise = rule; return this; }; function handleIfMatch($injector, handler, match) { if (!match) return false; var result = $injector.invoke(handler, handler, { $match: match }); return isDefined(result) ? result : true; } /** * @ngdoc function * @name ui.router.router.$urlRouterProvider#when * @methodOf ui.router.router.$urlRouterProvider * * @description * Registers a handler for a given url matching. * * If the handler is a string, it is * treated as a redirect, and is interpolated according to the syntax of match * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise). * * If the handler is a function, it is injectable. It gets invoked if `$location` * matches. You have the option of inject the match object as `$match`. * * The handler can return * * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter` * will continue trying to find another one that matches. * - **string** which is treated as a redirect and passed to `$location.url()` * - **void** or any **truthy** value tells `$urlRouter` that the url was handled. * * @example *
         * var app = angular.module('app', ['ui.router.router']);
         *
         * app.config(function ($urlRouterProvider) {
         *   $urlRouterProvider.when($state.url, function ($match, $stateParams) {
         *     if ($state.$current.navigable !== state ||
         *         !equalForKeys($match, $stateParams) {
         *      $state.transitionTo(state, $match, false);
         *     }
         *   });
         * });
         * 
      * * @param {string|object} what The incoming path that you want to redirect. * @param {string|function} handler The path you want to redirect your user to. */ this.when = function (what, handler) { var redirect, handlerIsString = isString(handler); if (isString(what)) what = $urlMatcherFactory.compile(what); if (!handlerIsString && !isFunction(handler) && !isArray(handler)) throw new Error("invalid 'handler' in when()"); var strategies = { matcher: function (what, handler) { if (handlerIsString) { redirect = $urlMatcherFactory.compile(handler); handler = ['$match', function ($match) { return redirect.format($match); }]; } return extend(function ($injector, $location) { return handleIfMatch($injector, handler, what.exec($location.path(), $location.search())); }, { prefix: isString(what.prefix) ? what.prefix : '' }); }, regex: function (what, handler) { if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky"); if (handlerIsString) { redirect = handler; handler = ['$match', function ($match) { return interpolate(redirect, $match); }]; } return extend(function ($injector, $location) { return handleIfMatch($injector, handler, what.exec($location.path())); }, { prefix: regExpPrefix(what) }); } }; var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp }; for (var n in check) { if (check[n]) return this.rule(strategies[n](what, handler)); } throw new Error("invalid 'what' in when()"); }; /** * @ngdoc function * @name ui.router.router.$urlRouterProvider#deferIntercept * @methodOf ui.router.router.$urlRouterProvider * * @description * Disables (or enables) deferring location change interception. * * If you wish to customize the behavior of syncing the URL (for example, if you wish to * defer a transition but maintain the current URL), call this method at configuration time. * Then, at run time, call `$urlRouter.listen()` after you have configured your own * `$locationChangeSuccess` event handler. * * @example *
         * var app = angular.module('app', ['ui.router.router']);
         *
         * app.config(function ($urlRouterProvider) {
         *
         *   // Prevent $urlRouter from automatically intercepting URL changes;
         *   // this allows you to configure custom behavior in between
         *   // location changes and route synchronization:
         *   $urlRouterProvider.deferIntercept();
         *
         * }).run(function ($rootScope, $urlRouter, UserService) {
         *
         *   $rootScope.$on('$locationChangeSuccess', function(e) {
         *     // UserService is an example service for managing user state
         *     if (UserService.isLoggedIn()) return;
         *
         *     // Prevent $urlRouter's default handler from firing
         *     e.preventDefault();
         *
         *     UserService.handleLogin().then(function() {
         *       // Once the user has logged in, sync the current URL
         *       // to the router:
         *       $urlRouter.sync();
         *     });
         *   });
         *
         *   // Configures $urlRouter's listener *after* your custom listener
         *   $urlRouter.listen();
         * });
         * 
      * * @param {boolean} defer Indicates whether to defer location change interception. Passing no parameter is equivalent to `true`. */ this.deferIntercept = function (defer) { if (defer === undefined) defer = true; interceptDeferred = defer; }; /** * @ngdoc object * @name ui.router.router.$urlRouter * * @requires $location * @requires $rootScope * @requires $injector * @requires $browser * * @description * */ this.$get = $get; $get.$inject = ['$location', '$rootScope', '$injector', '$browser', '$sniffer']; function $get( $location, $rootScope, $injector, $browser, $sniffer) { var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl; function appendBasePath(url, isHtml5, absolute) { if (baseHref === '/') return url; if (isHtml5) return baseHref.slice(0, -1) + url; if (absolute) return baseHref.slice(1) + url; return url; } // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree function update(evt) { if (evt && evt.defaultPrevented) return; var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl; lastPushedUrl = undefined; // TODO: Re-implement this in 1.0 for https://github.com/angular-ui/ui-router/issues/1573 //if (ignoreUpdate) return true; function check(rule) { var handled = rule($injector, $location); if (!handled) return false; if (isString(handled)) $location.replace().url(handled); return true; } var n = rules.length, i; for (i = 0; i < n; i++) { if (check(rules[i])) return; } // always check otherwise last to allow dynamic updates to the set of rules if (otherwise) check(otherwise); } function listen() { listener = listener || $rootScope.$on('$locationChangeSuccess', update); return listener; } if (!interceptDeferred) listen(); return { /** * @ngdoc function * @name ui.router.router.$urlRouter#sync * @methodOf ui.router.router.$urlRouter * * @description * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`. * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event, * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed * with the transition by calling `$urlRouter.sync()`. * * @example *
             * angular.module('app', ['ui.router'])
             *   .run(function($rootScope, $urlRouter) {
             *     $rootScope.$on('$locationChangeSuccess', function(evt) {
             *       // Halt state change from even starting
             *       evt.preventDefault();
             *       // Perform custom logic
             *       var meetsRequirement = ...
             *       // Continue with the update and state transition if logic allows
             *       if (meetsRequirement) $urlRouter.sync();
             *     });
             * });
             * 
      */ sync: function() { update(); }, listen: function() { return listen(); }, update: function(read) { if (read) { location = $location.url(); return; } if ($location.url() === location) return; $location.url(location); $location.replace(); }, push: function(urlMatcher, params, options) { var url = urlMatcher.format(params || {}); // Handle the special hash param, if needed if (url !== null && params && params['#']) { url += '#' + params['#']; } $location.url(url); lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined; if (options && options.replace) $location.replace(); }, /** * @ngdoc function * @name ui.router.router.$urlRouter#href * @methodOf ui.router.router.$urlRouter * * @description * A URL generation method that returns the compiled URL for a given * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters. * * @example *
             * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
             *   person: "bob"
             * });
             * // $bob == "/about/bob";
             * 
      * * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate. * @param {object=} params An object of parameter values to fill the matcher's required parameters. * @param {object=} options Options object. The options are: * * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl". * * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher` */ href: function(urlMatcher, params, options) { if (!urlMatcher.validates(params)) return null; var isHtml5 = $locationProvider.html5Mode(); if (angular.isObject(isHtml5)) { isHtml5 = isHtml5.enabled; } isHtml5 = isHtml5 && $sniffer.history; var url = urlMatcher.format(params); options = options || {}; if (!isHtml5 && url !== null) { url = "#" + $locationProvider.hashPrefix() + url; } // Handle special hash param, if needed if (url !== null && params && params['#']) { url += '#' + params['#']; } url = appendBasePath(url, isHtml5, options.absolute); if (!options.absolute || !url) { return url; } var slash = (!isHtml5 && url ? '/' : ''), port = $location.port(); port = (port === 80 || port === 443 ? '' : ':' + port); return [$location.protocol(), '://', $location.host(), port, slash, url].join(''); } }; } } angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider); /** * @ngdoc object * @name ui.router.state.$stateProvider * * @requires ui.router.router.$urlRouterProvider * @requires ui.router.util.$urlMatcherFactoryProvider * * @description * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely * on state. * * A state corresponds to a "place" in the application in terms of the overall UI and * navigation. A state describes (via the controller / template / view properties) what * the UI looks like and does at that place. * * States often have things in common, and the primary way of factoring out these * commonalities in this model is via the state hierarchy, i.e. parent/child states aka * nested states. * * The `$stateProvider` provides interfaces to declare these states for your app. */ $StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider']; function $StateProvider( $urlRouterProvider, $urlMatcherFactory) { var root, states = {}, $state, queue = {}, abstractKey = 'abstract'; // Builds state properties from definition passed to registerState() var stateBuilder = { // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined. // state.children = []; // if (parent) parent.children.push(state); parent: function(state) { if (isDefined(state.parent) && state.parent) return findState(state.parent); // regex matches any valid composite state name // would match "contact.list" but not "contacts" var compositeName = /^(.+)\.[^.]+$/.exec(state.name); return compositeName ? findState(compositeName[1]) : root; }, // inherit 'data' from parent and override by own values (if any) data: function(state) { if (state.parent && state.parent.data) { state.data = state.self.data = inherit(state.parent.data, state.data); } return state.data; }, // Build a URLMatcher if necessary, either via a relative or absolute URL url: function(state) { var url = state.url, config = { params: state.params || {} }; if (isString(url)) { if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config); return (state.parent.navigable || root).url.concat(url, config); } if (!url || $urlMatcherFactory.isMatcher(url)) return url; throw new Error("Invalid url '" + url + "' in state '" + state + "'"); }, // Keep track of the closest ancestor state that has a URL (i.e. is navigable) navigable: function(state) { return state.url ? state : (state.parent ? state.parent.navigable : null); }, // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params ownParams: function(state) { var params = state.url && state.url.params || new $$UMFP.ParamSet(); forEach(state.params || {}, function(config, id) { if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config"); }); return params; }, // Derive parameters for this state and ensure they're a super-set of parent's parameters params: function(state) { var ownParams = pick(state.ownParams, state.ownParams.$$keys()); return state.parent && state.parent.params ? extend(state.parent.params.$$new(), ownParams) : new $$UMFP.ParamSet(); }, // If there is no explicit multi-view configuration, make one up so we don't have // to handle both cases in the view directive later. Note that having an explicit // 'views' property will mean the default unnamed view properties are ignored. This // is also a good time to resolve view names to absolute names, so everything is a // straight lookup at link time. views: function(state) { var views = {}; forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) { if (name.indexOf('@') < 0) name += '@' + state.parent.name; view.resolveAs = view.resolveAs || state.resolveAs || '$resolve'; views[name] = view; }); return views; }, // Keep a full path from the root down to this state as this is needed for state activation. path: function(state) { return state.parent ? state.parent.path.concat(state) : []; // exclude root from path }, // Speed up $state.contains() as it's used a lot includes: function(state) { var includes = state.parent ? extend({}, state.parent.includes) : {}; includes[state.name] = true; return includes; }, $delegates: {} }; function isRelative(stateName) { return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0; } function findState(stateOrName, base) { if (!stateOrName) return undefined; var isStr = isString(stateOrName), name = isStr ? stateOrName : stateOrName.name, path = isRelative(name); if (path) { if (!base) throw new Error("No reference point given for path '" + name + "'"); base = findState(base); var rel = name.split("."), i = 0, pathLength = rel.length, current = base; for (; i < pathLength; i++) { if (rel[i] === "" && i === 0) { current = base; continue; } if (rel[i] === "^") { if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'"); current = current.parent; continue; } break; } rel = rel.slice(i).join("."); name = current.name + (current.name && rel ? "." : "") + rel; } var state = states[name]; if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) { return state; } return undefined; } function queueState(parentName, state) { if (!queue[parentName]) { queue[parentName] = []; } queue[parentName].push(state); } function flushQueuedChildren(parentName) { var queued = queue[parentName] || []; while(queued.length) { registerState(queued.shift()); } } function registerState(state) { // Wrap a new object around the state so we can store our private details easily. state = inherit(state, { self: state, resolve: state.resolve || {}, toString: function() { return this.name; } }); var name = state.name; if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name"); if (states.hasOwnProperty(name)) throw new Error("State '" + name + "' is already defined"); // Get parent name var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.')) : (isString(state.parent)) ? state.parent : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name : ''; // If parent is not registered yet, add state to queue and register later if (parentName && !states[parentName]) { return queueState(parentName, state.self); } for (var key in stateBuilder) { if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]); } states[name] = state; // Register the state in the global state list and with $urlRouter if necessary. if (!state[abstractKey] && state.url) { $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) { if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) { $state.transitionTo(state, $match, { inherit: true, location: false }); } }]); } // Register any queued children flushQueuedChildren(name); return state; } // Checks text to see if it looks like a glob. function isGlob (text) { return text.indexOf('*') > -1; } // Returns true if glob matches current $state name. function doesStateMatchGlob (glob) { var globSegments = glob.split('.'), segments = $state.$current.name.split('.'); //match single stars for (var i = 0, l = globSegments.length; i < l; i++) { if (globSegments[i] === '*') { segments[i] = '*'; } } //match greedy starts if (globSegments[0] === '**') { segments = segments.slice(indexOf(segments, globSegments[1])); segments.unshift('**'); } //match greedy ends if (globSegments[globSegments.length - 1] === '**') { segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE); segments.push('**'); } if (globSegments.length != segments.length) { return false; } return segments.join('') === globSegments.join(''); } // Implicit root state that is always active root = registerState({ name: '', url: '^', views: null, 'abstract': true }); root.navigable = null; /** * @ngdoc function * @name ui.router.state.$stateProvider#decorator * @methodOf ui.router.state.$stateProvider * * @description * Allows you to extend (carefully) or override (at your own peril) the * `stateBuilder` object used internally by `$stateProvider`. This can be used * to add custom functionality to ui-router, for example inferring templateUrl * based on the state name. * * When passing only a name, it returns the current (original or decorated) builder * function that matches `name`. * * The builder functions that can be decorated are listed below. Though not all * necessarily have a good use case for decoration, that is up to you to decide. * * In addition, users can attach custom decorators, which will generate new * properties within the state's internal definition. There is currently no clear * use-case for this beyond accessing internal states (i.e. $state.$current), * however, expect this to become increasingly relevant as we introduce additional * meta-programming features. * * **Warning**: Decorators should not be interdependent because the order of * execution of the builder functions in non-deterministic. Builder functions * should only be dependent on the state definition object and super function. * * * Existing builder functions and current return values: * * - **parent** `{object}` - returns the parent state object. * - **data** `{object}` - returns state data, including any inherited data that is not * overridden by own values (if any). * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher} * or `null`. * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is * navigable). * - **params** `{object}` - returns an array of state params that are ensured to * be a super-set of parent's params. * - **views** `{object}` - returns a views object where each key is an absolute view * name (i.e. "viewName@stateName") and each value is the config object * (template, controller) for the view. Even when you don't use the views object * explicitly on a state config, one is still created for you internally. * So by decorating this builder function you have access to decorating template * and controller properties. * - **ownParams** `{object}` - returns an array of params that belong to the state, * not including any params defined by ancestor states. * - **path** `{string}` - returns the full path from the root down to this state. * Needed for state activation. * - **includes** `{object}` - returns an object that includes every state that * would pass a `$state.includes()` test. * * @example *
         * // Override the internal 'views' builder with a function that takes the state
         * // definition, and a reference to the internal function being overridden:
         * $stateProvider.decorator('views', function (state, parent) {
         *   var result = {},
         *       views = parent(state);
         *
         *   angular.forEach(views, function (config, name) {
         *     var autoName = (state.name + '.' + name).replace('.', '/');
         *     config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
         *     result[name] = config;
         *   });
         *   return result;
         * });
         *
         * $stateProvider.state('home', {
         *   views: {
         *     'contact.list': { controller: 'ListController' },
         *     'contact.item': { controller: 'ItemController' }
         *   }
         * });
         *
         * // ...
         *
         * $state.go('home');
         * // Auto-populates list and item views with /partials/home/contact/list.html,
         * // and /partials/home/contact/item.html, respectively.
         * 
      * * @param {string} name The name of the builder function to decorate. * @param {object} func A function that is responsible for decorating the original * builder function. The function receives two parameters: * * - `{object}` - state - The state config object. * - `{object}` - super - The original builder function. * * @return {object} $stateProvider - $stateProvider instance */ this.decorator = decorator; function decorator(name, func) { /*jshint validthis: true */ if (isString(name) && !isDefined(func)) { return stateBuilder[name]; } if (!isFunction(func) || !isString(name)) { return this; } if (stateBuilder[name] && !stateBuilder.$delegates[name]) { stateBuilder.$delegates[name] = stateBuilder[name]; } stateBuilder[name] = func; return this; } /** * @ngdoc function * @name ui.router.state.$stateProvider#state * @methodOf ui.router.state.$stateProvider * * @description * Registers a state configuration under a given state name. The stateConfig object * has the following acceptable properties. * * @param {string} name A unique state name, e.g. "home", "about", "contacts". * To create a parent/child state use a dot, e.g. "about.sales", "home.newest". * @param {object} stateConfig State configuration object. * @param {string|function=} stateConfig.template * * html template as a string or a function that returns * an html template as a string which should be used by the uiView directives. This property * takes precedence over templateUrl. * * If `template` is a function, it will be called with the following parameters: * * - {array.<object>} - state parameters extracted from the current $location.path() by * applying the current state * *
      template:
         *   "

      inline template definition

      " + * "
      "
      *
      template: function(params) {
         *       return "

      generated template

      "; }
      *
      * * @param {string|function=} stateConfig.templateUrl * * * path or function that returns a path to an html * template that should be used by uiView. * * If `templateUrl` is a function, it will be called with the following parameters: * * - {array.<object>} - state parameters extracted from the current $location.path() by * applying the current state * *
      templateUrl: "home.html"
      *
      templateUrl: function(params) {
         *     return myTemplates[params.pageId]; }
      * * @param {function=} stateConfig.templateProvider * * Provider function that returns HTML content string. *
       templateProvider:
         *       function(MyTemplateService, params) {
         *         return MyTemplateService.getTemplate(params.pageId);
         *       }
      * * @param {string|function=} stateConfig.controller * * * Controller fn that should be associated with newly * related scope or the name of a registered controller if passed as a string. * Optionally, the ControllerAs may be declared here. *
      controller: "MyRegisteredController"
      *
      controller:
         *     "MyRegisteredController as fooCtrl"}
      *
      controller: function($scope, MyService) {
         *     $scope.data = MyService.getData(); }
      * * @param {function=} stateConfig.controllerProvider * * * Injectable provider function that returns the actual controller or string. *
      controllerProvider:
         *   function(MyResolveData) {
         *     if (MyResolveData.foo)
         *       return "FooCtrl"
         *     else if (MyResolveData.bar)
         *       return "BarCtrl";
         *     else return function($scope) {
         *       $scope.baz = "Qux";
         *     }
         *   }
      * * @param {string=} stateConfig.controllerAs * * * A controller alias name. If present the controller will be * published to scope under the controllerAs name. *
      controllerAs: "myCtrl"
      * * @param {string|object=} stateConfig.parent * * Optionally specifies the parent state of this state. * *
      parent: 'parentState'
      *
      parent: parentState // JS variable
      * * @param {object=} stateConfig.resolve * * * An optional map<string, function> of dependencies which * should be injected into the controller. If any of these dependencies are promises, * the router will wait for them all to be resolved before the controller is instantiated. * If all the promises are resolved successfully, the $stateChangeSuccess event is fired * and the values of the resolved promises are injected into any controllers that reference them. * If any of the promises are rejected the $stateChangeError event is fired. * * The map object is: * * - key - {string}: name of dependency to be injected into controller * - factory - {string|function}: If string then it is alias for service. Otherwise if function, * it is injected and return value it treated as dependency. If result is a promise, it is * resolved before its value is injected into controller. * *
      resolve: {
         *     myResolve1:
         *       function($http, $stateParams) {
         *         return $http.get("/api/foos/"+stateParams.fooID);
         *       }
         *     }
      * * @param {string=} stateConfig.url * * * A url fragment with optional parameters. When a state is navigated or * transitioned to, the `$stateParams` service will be populated with any * parameters that were passed. * * (See {@link ui.router.util.type:UrlMatcher UrlMatcher} `UrlMatcher`} for * more details on acceptable patterns ) * * examples: *
      url: "/home"
         * url: "/users/:userid"
         * url: "/books/{bookid:[a-zA-Z_-]}"
         * url: "/books/{categoryid:int}"
         * url: "/books/{publishername:string}/{categoryid:int}"
         * url: "/messages?before&after"
         * url: "/messages?{before:date}&{after:date}"
         * url: "/messages/:mailboxid?{before:date}&{after:date}"
         * 
      * * @param {object=} stateConfig.views * * an optional map<string, object> which defined multiple views, or targets views * manually/explicitly. * * Examples: * * Targets three named `ui-view`s in the parent state's template *
      views: {
         *     header: {
         *       controller: "headerCtrl",
         *       templateUrl: "header.html"
         *     }, body: {
         *       controller: "bodyCtrl",
         *       templateUrl: "body.html"
         *     }, footer: {
         *       controller: "footCtrl",
         *       templateUrl: "footer.html"
         *     }
         *   }
      * * Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template. *
      views: {
         *     'header@top': {
         *       controller: "msgHeaderCtrl",
         *       templateUrl: "msgHeader.html"
         *     }, 'body': {
         *       controller: "messagesCtrl",
         *       templateUrl: "messages.html"
         *     }
         *   }
      * * @param {boolean=} [stateConfig.abstract=false] * * An abstract state will never be directly activated, * but can provide inherited properties to its common children states. *
      abstract: true
      * * @param {function=} stateConfig.onEnter * * * Callback function for when a state is entered. Good way * to trigger an action or dispatch an event, such as opening a dialog. * If minifying your scripts, make sure to explicitly annotate this function, * because it won't be automatically annotated by your build tools. * *
      onEnter: function(MyService, $stateParams) {
         *     MyService.foo($stateParams.myParam);
         * }
      * * @param {function=} stateConfig.onExit * * * Callback function for when a state is exited. Good way to * trigger an action or dispatch an event, such as opening a dialog. * If minifying your scripts, make sure to explicitly annotate this function, * because it won't be automatically annotated by your build tools. * *
      onExit: function(MyService, $stateParams) {
         *     MyService.cleanup($stateParams.myParam);
         * }
      * * @param {boolean=} [stateConfig.reloadOnSearch=true] * * * If `false`, will not retrigger the same state * just because a search/query parameter has changed (via $location.search() or $location.hash()). * Useful for when you'd like to modify $location.search() without triggering a reload. *
      reloadOnSearch: false
      * * @param {object=} stateConfig.data * * * Arbitrary data object, useful for custom configuration. The parent state's `data` is * prototypally inherited. In other words, adding a data property to a state adds it to * the entire subtree via prototypal inheritance. * *
      data: {
         *     requiredRole: 'foo'
         * } 
      * * @param {object=} stateConfig.params * * * A map which optionally configures parameters declared in the `url`, or * defines additional non-url parameters. For each parameter being * configured, add a configuration object keyed to the name of the parameter. * * Each parameter configuration object may contain the following properties: * * - ** value ** - {object|function=}: specifies the default value for this * parameter. This implicitly sets this parameter as optional. * * When UI-Router routes to a state and no value is * specified for this parameter in the URL or transition, the * default value will be used instead. If `value` is a function, * it will be injected and invoked, and the return value used. * * *Note*: `undefined` is treated as "no default value" while `null` * is treated as "the default value is `null`". * * *Shorthand*: If you only need to configure the default value of the * parameter, you may use a shorthand syntax. In the **`params`** * map, instead mapping the param name to a full parameter configuration * object, simply set map it to the default parameter value, e.g.: * *
      // define a parameter's default value
         * params: {
         *     param1: { value: "defaultValue" }
         * }
         * // shorthand default values
         * params: {
         *     param1: "defaultValue",
         *     param2: "param2Default"
         * }
      * * - ** array ** - {boolean=}: *(default: false)* If true, the param value will be * treated as an array of values. If you specified a Type, the value will be * treated as an array of the specified Type. Note: query parameter values * default to a special `"auto"` mode. * * For query parameters in `"auto"` mode, if multiple values for a single parameter * are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values * are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`). However, if * only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single * value (e.g.: `{ foo: '1' }`). * *
      params: {
         *     param1: { array: true }
         * }
      * * - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when * the current parameter value is the same as the default value. If `squash` is not set, it uses the * configured default squash policy. * (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`}) * * There are three squash settings: * * - false: The parameter's default value is not squashed. It is encoded and included in the URL * - true: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed * by slashes in the state's `url` declaration, then one of those slashes are omitted. * This can allow for cleaner looking URLs. * - `""`: The parameter's default value is replaced with an arbitrary placeholder of your choice. * *
      params: {
         *     param1: {
         *       value: "defaultId",
         *       squash: true
         * } }
         * // squash "defaultValue" to "~"
         * params: {
         *     param1: {
         *       value: "defaultValue",
         *       squash: "~"
         * } }
         * 
      * * * @example *
         * // Some state name examples
         *
         * // stateName can be a single top-level name (must be unique).
         * $stateProvider.state("home", {});
         *
         * // Or it can be a nested state name. This state is a child of the
         * // above "home" state.
         * $stateProvider.state("home.newest", {});
         *
         * // Nest states as deeply as needed.
         * $stateProvider.state("home.newest.abc.xyz.inception", {});
         *
         * // state() returns $stateProvider, so you can chain state declarations.
         * $stateProvider
         *   .state("home", {})
         *   .state("about", {})
         *   .state("contacts", {});
         * 
      * */ this.state = state; function state(name, definition) { /*jshint validthis: true */ if (isObject(name)) definition = name; else definition.name = name; registerState(definition); return this; } /** * @ngdoc object * @name ui.router.state.$state * * @requires $rootScope * @requires $q * @requires ui.router.state.$view * @requires $injector * @requires ui.router.util.$resolve * @requires ui.router.state.$stateParams * @requires ui.router.router.$urlRouter * * @property {object} params A param object, e.g. {sectionId: section.id)}, that * you'd like to test against the current active state. * @property {object} current A reference to the state's config object. However * you passed it in. Useful for accessing custom data. * @property {object} transition Currently pending transition. A promise that'll * resolve or reject. * * @description * `$state` service is responsible for representing states as well as transitioning * between them. It also provides interfaces to ask for current state or even states * you're coming from. */ this.$get = $get; $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory']; function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) { var TransitionSupersededError = new Error('transition superseded'); var TransitionSuperseded = silenceUncaughtInPromise($q.reject(TransitionSupersededError)); var TransitionPrevented = silenceUncaughtInPromise($q.reject(new Error('transition prevented'))); var TransitionAborted = silenceUncaughtInPromise($q.reject(new Error('transition aborted'))); var TransitionFailed = silenceUncaughtInPromise($q.reject(new Error('transition failed'))); // Handles the case where a state which is the target of a transition is not found, and the user // can optionally retry or defer the transition function handleRedirect(redirect, state, params, options) { /** * @ngdoc event * @name ui.router.state.$state#$stateNotFound * @eventOf ui.router.state.$state * @eventType broadcast on root scope * @description * Fired when a requested state **cannot be found** using the provided state name during transition. * The event is broadcast allowing any handlers a single chance to deal with the error (usually by * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler, * you can see its three properties in the example. You can use `event.preventDefault()` to abort the * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value. * * @param {Object} event Event object. * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties. * @param {State} fromState Current state object. * @param {Object} fromParams Current state params. * * @example * *
             * // somewhere, assume lazy.state has not been defined
             * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
             *
             * // somewhere else
             * $scope.$on('$stateNotFound',
             * function(event, unfoundState, fromState, fromParams){
             *     console.log(unfoundState.to); // "lazy.state"
             *     console.log(unfoundState.toParams); // {a:1, b:2}
             *     console.log(unfoundState.options); // {inherit:false} + default options
             * })
             * 
      */ var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params); if (evt.defaultPrevented) { $urlRouter.update(); return TransitionAborted; } if (!evt.retry) { return null; } // Allow the handler to return a promise to defer state lookup retry if (options.$retry) { $urlRouter.update(); return TransitionFailed; } var retryTransition = $state.transition = $q.when(evt.retry); retryTransition.then(function() { if (retryTransition !== $state.transition) { $rootScope.$broadcast('$stateChangeCancel', redirect.to, redirect.toParams, state, params); return TransitionSuperseded; } redirect.options.$retry = true; return $state.transitionTo(redirect.to, redirect.toParams, redirect.options); }, function() { return TransitionAborted; }); $urlRouter.update(); return retryTransition; } root.locals = { resolve: null, globals: { $stateParams: {} } }; $state = { params: {}, current: root.self, $current: root, transition: null }; /** * @ngdoc function * @name ui.router.state.$state#reload * @methodOf ui.router.state.$state * * @description * A method that force reloads the current state. All resolves are re-resolved, * controllers reinstantiated, and events re-fired. * * @example *
           * var app angular.module('app', ['ui.router']);
           *
           * app.controller('ctrl', function ($scope, $state) {
           *   $scope.reload = function(){
           *     $state.reload();
           *   }
           * });
           * 
      * * `reload()` is just an alias for: *
           * $state.transitionTo($state.current, $stateParams, { 
           *   reload: true, inherit: false, notify: true
           * });
           * 
      * * @param {string=|object=} state - A state name or a state object, which is the root of the resolves to be re-resolved. * @example *
           * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item' 
           * //and current state is 'contacts.detail.item'
           * var app angular.module('app', ['ui.router']);
           *
           * app.controller('ctrl', function ($scope, $state) {
           *   $scope.reload = function(){
           *     //will reload 'contact.detail' and 'contact.detail.item' states
           *     $state.reload('contact.detail');
           *   }
           * });
           * 
      * * `reload()` is just an alias for: *
           * $state.transitionTo($state.current, $stateParams, { 
           *   reload: true, inherit: false, notify: true
           * });
           * 
      * @returns {promise} A promise representing the state of the new transition. See * {@link ui.router.state.$state#methods_go $state.go}. */ $state.reload = function reload(state) { return $state.transitionTo($state.current, $stateParams, { reload: state || true, inherit: false, notify: true}); }; /** * @ngdoc function * @name ui.router.state.$state#go * @methodOf ui.router.state.$state * * @description * Convenience method for transitioning to a new state. `$state.go` calls * `$state.transitionTo` internally but automatically sets options to * `{ location: true, inherit: true, relative: $state.$current, notify: true }`. * This allows you to easily use an absolute or relative to path and specify * only the parameters you'd like to update (while letting unspecified parameters * inherit from the currently active ancestor states). * * @example *
           * var app = angular.module('app', ['ui.router']);
           *
           * app.controller('ctrl', function ($scope, $state) {
           *   $scope.changeState = function () {
           *     $state.go('contact.detail');
           *   };
           * });
           * 
      * * * @param {string} to Absolute state name or relative state path. Some examples: * * - `$state.go('contact.detail')` - will go to the `contact.detail` state * - `$state.go('^')` - will go to a parent state * - `$state.go('^.sibling')` - will go to a sibling state * - `$state.go('.child.grandchild')` - will go to grandchild state * * @param {object=} params A map of the parameters that will be sent to the state, * will populate $stateParams. Any parameters that are not specified will be inherited from currently * defined parameters. Only parameters specified in the state definition can be overridden, new * parameters will be ignored. This allows, for example, going to a sibling state that shares parameters * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e. * transitioning to a sibling will get you the parameters for all parents, transitioning to a child * will get you all current parameters, etc. * @param {object=} options Options object. The options are: * * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false` * will not. If string, must be `"replace"`, which will update url and also replace last history record. * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), * defines which state to be relative from. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events. * - **`reload`** (v0.2.5) - {boolean=false|string|object}, If `true` will force transition even if no state or params * have changed. It will reload the resolves and views of the current state and parent states. * If `reload` is a string (or state object), the state object is fetched (by name, or object reference); and \ * the transition reloads the resolves and views for that matched state, and all its children states. * * @returns {promise} A promise representing the state of the new transition. * * Possible success values: * * - $state.current * *
      Possible rejection values: * * - 'transition superseded' - when a newer transition has been started after this one * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or * when a `$stateNotFound` `event.retry` promise errors. * - 'transition failed' - when a state has been unsuccessfully found after 2 tries. * - *resolve error* - when an error has occurred with a `resolve` * */ $state.go = function go(to, params, options) { return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options)); }; /** * @ngdoc function * @name ui.router.state.$state#transitionTo * @methodOf ui.router.state.$state * * @description * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go} * uses `transitionTo` internally. `$state.go` is recommended in most situations. * * @example *
           * var app = angular.module('app', ['ui.router']);
           *
           * app.controller('ctrl', function ($scope, $state) {
           *   $scope.changeState = function () {
           *     $state.transitionTo('contact.detail');
           *   };
           * });
           * 
      * * @param {string} to State name. * @param {object=} toParams A map of the parameters that will be sent to the state, * will populate $stateParams. * @param {object=} options Options object. The options are: * * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false` * will not. If string, must be `"replace"`, which will update url and also replace last history record. * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url. * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'), * defines which state to be relative from. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events. * - **`reload`** (v0.2.5) - {boolean=false|string=|object=}, If `true` will force transition even if the state or params * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd * use this when you want to force a reload when *everything* is the same, including search params. * if String, then will reload the state with the name given in reload, and any children. * if Object, then a stateObj is expected, will reload the state found in stateObj, and any children. * * @returns {promise} A promise representing the state of the new transition. See * {@link ui.router.state.$state#methods_go $state.go}. */ $state.transitionTo = function transitionTo(to, toParams, options) { toParams = toParams || {}; options = extend({ location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false }, options || {}); var from = $state.$current, fromParams = $state.params, fromPath = from.path; var evt, toState = findState(to, options.relative); // Store the hash param for later (since it will be stripped out by various methods) var hash = toParams['#']; if (!isDefined(toState)) { var redirect = { to: to, toParams: toParams, options: options }; var redirectResult = handleRedirect(redirect, from.self, fromParams, options); if (redirectResult) { return redirectResult; } // Always retry once if the $stateNotFound was not prevented // (handles either redirect changed or state lazy-definition) to = redirect.to; toParams = redirect.toParams; options = redirect.options; toState = findState(to, options.relative); if (!isDefined(toState)) { if (!options.relative) throw new Error("No such state '" + to + "'"); throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'"); } } if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'"); if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState); if (!toState.params.$$validates(toParams)) return TransitionFailed; toParams = toState.params.$$values(toParams); to = toState; var toPath = to.path; // Starting from the root of the path, keep all levels that haven't changed var keep = 0, state = toPath[keep], locals = root.locals, toLocals = []; if (!options.reload) { while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) { locals = toLocals[keep] = state.locals; keep++; state = toPath[keep]; } } else if (isString(options.reload) || isObject(options.reload)) { if (isObject(options.reload) && !options.reload.name) { throw new Error('Invalid reload state object'); } var reloadState = options.reload === true ? fromPath[0] : findState(options.reload); if (options.reload && !reloadState) { throw new Error("No such reload state '" + (isString(options.reload) ? options.reload : options.reload.name) + "'"); } while (state && state === fromPath[keep] && state !== reloadState) { locals = toLocals[keep] = state.locals; keep++; state = toPath[keep]; } } // If we're going to the same state and all locals are kept, we've got nothing to do. // But clear 'transition', as we still want to cancel any other pending transitions. // TODO: We may not want to bump 'transition' if we're called from a location change // that we've initiated ourselves, because we might accidentally abort a legitimate // transition initiated from code? if (shouldSkipReload(to, toParams, from, fromParams, locals, options)) { if (hash) toParams['#'] = hash; $state.params = toParams; copy($state.params, $stateParams); copy(filterByKeys(to.params.$$keys(), $stateParams), to.locals.globals.$stateParams); if (options.location && to.navigable && to.navigable.url) { $urlRouter.push(to.navigable.url, toParams, { $$avoidResync: true, replace: options.location === 'replace' }); $urlRouter.update(true); } $state.transition = null; return $q.when($state.current); } // Filter parameters before we pass them to event handlers etc. toParams = filterByKeys(to.params.$$keys(), toParams || {}); // Re-add the saved hash before we start returning things or broadcasting $stateChangeStart if (hash) toParams['#'] = hash; // Broadcast start event and cancel the transition if requested if (options.notify) { /** * @ngdoc event * @name ui.router.state.$state#$stateChangeStart * @eventOf ui.router.state.$state * @eventType broadcast on root scope * @description * Fired when the state transition **begins**. You can use `event.preventDefault()` * to prevent the transition from happening and then the transition promise will be * rejected with a `'transition prevented'` value. * * @param {Object} event Event object. * @param {State} toState The state being transitioned to. * @param {Object} toParams The params supplied to the `toState`. * @param {State} fromState The current state, pre-transition. * @param {Object} fromParams The params supplied to the `fromState`. * * @example * *
               * $rootScope.$on('$stateChangeStart',
               * function(event, toState, toParams, fromState, fromParams){
               *     event.preventDefault();
               *     // transitionTo() promise will be rejected with
               *     // a 'transition prevented' error
               * })
               * 
      */ if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams, options).defaultPrevented) { $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams); //Don't update and resync url if there's been a new transition started. see issue #2238, #600 if ($state.transition == null) $urlRouter.update(); return TransitionPrevented; } } // Resolve locals for the remaining states, but don't update any global state just // yet -- if anything fails to resolve the current state needs to remain untouched. // We also set up an inheritance chain for the locals here. This allows the view directive // to quickly look up the correct definition for each view in the current state. Even // though we create the locals object itself outside resolveState(), it is initially // empty and gets filled asynchronously. We need to keep track of the promise for the // (fully resolved) current locals, and pass this down the chain. var resolved = $q.when(locals); for (var l = keep; l < toPath.length; l++, state = toPath[l]) { locals = toLocals[l] = inherit(locals); resolved = resolveState(state, toParams, state === to, resolved, locals, options); } // Once everything is resolved, we are ready to perform the actual transition // and return a promise for the new state. We also keep track of what the // current promise is, so that we can detect overlapping transitions and // keep only the outcome of the last transition. var transition = $state.transition = resolved.then(function () { var l, entering, exiting; if ($state.transition !== transition) { $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams); return TransitionSuperseded; } // Exit 'from' states not kept for (l = fromPath.length - 1; l >= keep; l--) { exiting = fromPath[l]; if (exiting.self.onExit) { $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals); } exiting.locals = null; } // Enter 'to' states not kept for (l = keep; l < toPath.length; l++) { entering = toPath[l]; entering.locals = toLocals[l]; if (entering.self.onEnter) { $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals); } } // Run it again, to catch any transitions in callbacks if ($state.transition !== transition) { $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams); return TransitionSuperseded; } // Update globals in $state $state.$current = to; $state.current = to.self; $state.params = toParams; copy($state.params, $stateParams); $state.transition = null; if (options.location && to.navigable) { $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, { $$avoidResync: true, replace: options.location === 'replace' }); } if (options.notify) { /** * @ngdoc event * @name ui.router.state.$state#$stateChangeSuccess * @eventOf ui.router.state.$state * @eventType broadcast on root scope * @description * Fired once the state transition is **complete**. * * @param {Object} event Event object. * @param {State} toState The state being transitioned to. * @param {Object} toParams The params supplied to the `toState`. * @param {State} fromState The current state, pre-transition. * @param {Object} fromParams The params supplied to the `fromState`. */ $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams); } $urlRouter.update(true); return $state.current; }).then(null, function (error) { // propagate TransitionSuperseded error without emitting $stateChangeCancel // as it was already emitted in the success handler above if (error === TransitionSupersededError) return TransitionSuperseded; if ($state.transition !== transition) { $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams); return TransitionSuperseded; } $state.transition = null; /** * @ngdoc event * @name ui.router.state.$state#$stateChangeError * @eventOf ui.router.state.$state * @eventType broadcast on root scope * @description * Fired when an **error occurs** during transition. It's important to note that if you * have any errors in your resolve functions (javascript errors, non-existent services, etc) * they will not throw traditionally. You must listen for this $stateChangeError event to * catch **ALL** errors. * * @param {Object} event Event object. * @param {State} toState The state being transitioned to. * @param {Object} toParams The params supplied to the `toState`. * @param {State} fromState The current state, pre-transition. * @param {Object} fromParams The params supplied to the `fromState`. * @param {Error} error The resolve error object. */ evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error); if (!evt.defaultPrevented) { $urlRouter.update(); } return $q.reject(error); }); silenceUncaughtInPromise(transition); return transition; }; /** * @ngdoc function * @name ui.router.state.$state#is * @methodOf ui.router.state.$state * * @description * Similar to {@link ui.router.state.$state#methods_includes $state.includes}, * but only checks for the full state name. If params is supplied then it will be * tested for strict equality against the current active params object, so all params * must match with none missing and no extras. * * @example *
           * $state.$current.name = 'contacts.details.item';
           *
           * // absolute name
           * $state.is('contact.details.item'); // returns true
           * $state.is(contactDetailItemStateObject); // returns true
           *
           * // relative name (. and ^), typically from a template
           * // E.g. from the 'contacts.details' template
           * 
      Item
      *
      * * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check. * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like * to test against the current active state. * @param {object=} options An options object. The options are: * * - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will * test relative to `options.relative` state (or name). * * @returns {boolean} Returns true if it is the state. */ $state.is = function is(stateOrName, params, options) { options = extend({ relative: $state.$current }, options || {}); var state = findState(stateOrName, options.relative); if (!isDefined(state)) { return undefined; } if ($state.$current !== state) { return false; } return !params || objectKeys(params).reduce(function(acc, key) { var paramDef = state.params[key]; return acc && !paramDef || paramDef.type.equals($stateParams[key], params[key]); }, true); }; /** * @ngdoc function * @name ui.router.state.$state#includes * @methodOf ui.router.state.$state * * @description * A method to determine if the current active state is equal to or is the child of the * state stateName. If any params are passed then they will be tested for a match as well. * Not all the parameters need to be passed, just the ones you'd like to test for equality. * * @example * Partial and relative names *
           * $state.$current.name = 'contacts.details.item';
           *
           * // Using partial names
           * $state.includes("contacts"); // returns true
           * $state.includes("contacts.details"); // returns true
           * $state.includes("contacts.details.item"); // returns true
           * $state.includes("contacts.list"); // returns false
           * $state.includes("about"); // returns false
           *
           * // Using relative names (. and ^), typically from a template
           * // E.g. from the 'contacts.details' template
           * 
      Item
      *
      * * Basic globbing patterns *
           * $state.$current.name = 'contacts.details.item.url';
           *
           * $state.includes("*.details.*.*"); // returns true
           * $state.includes("*.details.**"); // returns true
           * $state.includes("**.item.**"); // returns true
           * $state.includes("*.details.item.url"); // returns true
           * $state.includes("*.details.*.url"); // returns true
           * $state.includes("*.details.*"); // returns false
           * $state.includes("item.**"); // returns false
           * 
      * * @param {string} stateOrName A partial name, relative name, or glob pattern * to be searched for within the current state name. * @param {object=} params A param object, e.g. `{sectionId: section.id}`, * that you'd like to test against the current active state. * @param {object=} options An options object. The options are: * * - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set, * .includes will test relative to `options.relative` state (or name). * * @returns {boolean} Returns true if it does include the state */ $state.includes = function includes(stateOrName, params, options) { options = extend({ relative: $state.$current }, options || {}); if (isString(stateOrName) && isGlob(stateOrName)) { if (!doesStateMatchGlob(stateOrName)) { return false; } stateOrName = $state.$current.name; } var state = findState(stateOrName, options.relative); if (!isDefined(state)) { return undefined; } if (!isDefined($state.$current.includes[state.name])) { return false; } if (!params) { return true; } var keys = objectKeys(params); for (var i = 0; i < keys.length; i++) { var key = keys[i], paramDef = state.params[key]; if (paramDef && !paramDef.type.equals($stateParams[key], params[key])) { return false; } } return objectKeys(params).reduce(function(acc, key) { var paramDef = state.params[key]; return acc && !paramDef || paramDef.type.equals($stateParams[key], params[key]); }, true); }; /** * @ngdoc function * @name ui.router.state.$state#href * @methodOf ui.router.state.$state * * @description * A url generation method that returns the compiled url for the given state populated with the given params. * * @example *
           * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
           * 
      * * @param {string|object} stateOrName The state name or state object you'd like to generate a url from. * @param {object=} params An object of parameter values to fill the state's required parameters. * @param {object=} options Options object. The options are: * * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the * first parameter, then the constructed href url will be built from the first navigable ancestor (aka * ancestor with a valid url). * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), * defines which state to be relative from. * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl". * * @returns {string} compiled state url */ $state.href = function href(stateOrName, params, options) { options = extend({ lossy: true, inherit: true, absolute: false, relative: $state.$current }, options || {}); var state = findState(stateOrName, options.relative); if (!isDefined(state)) return null; if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state); var nav = (state && options.lossy) ? state.navigable : state; if (!nav || nav.url === undefined || nav.url === null) { return null; } return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys().concat('#'), params || {}), { absolute: options.absolute }); }; /** * @ngdoc function * @name ui.router.state.$state#get * @methodOf ui.router.state.$state * * @description * Returns the state configuration object for any specific state or all states. * * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for * the requested state. If not provided, returns an array of ALL state configs. * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context. * @returns {Object|Array} State configuration object or array of all objects. */ $state.get = function (stateOrName, context) { if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; }); var state = findState(stateOrName, context || $state.$current); return (state && state.self) ? state.self : null; }; function resolveState(state, params, paramsAreFiltered, inherited, dst, options) { // Make a restricted $stateParams with only the parameters that apply to this state if // necessary. In addition to being available to the controller and onEnter/onExit callbacks, // we also need $stateParams to be available for any $injector calls we make during the // dependency resolution process. var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params); var locals = { $stateParams: $stateParams }; // Resolve 'global' dependencies for the state, i.e. those not specific to a view. // We're also including $stateParams in this; that way the parameters are restricted // to the set that should be visible to the state, and are independent of when we update // the global $state and $stateParams values. dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state); var promises = [dst.resolve.then(function (globals) { dst.globals = globals; })]; if (inherited) promises.push(inherited); function resolveViews() { var viewsPromises = []; // Resolve template and dependencies for all views. forEach(state.views, function (view, name) { var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {}); injectables.$template = [ function () { return $view.load(name, { view: view, locals: dst.globals, params: $stateParams, notify: options.notify }) || ''; }]; viewsPromises.push($resolve.resolve(injectables, dst.globals, dst.resolve, state).then(function (result) { // References to the controller (only instantiated at link time) if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) { var injectLocals = angular.extend({}, injectables, dst.globals); result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals); } else { result.$$controller = view.controller; } // Provide access to the state itself for internal use result.$$state = state; result.$$controllerAs = view.controllerAs; result.$$resolveAs = view.resolveAs; dst[name] = result; })); }); return $q.all(viewsPromises).then(function(){ return dst.globals; }); } // Wait for all the promises and then return the activation object return $q.all(promises).then(resolveViews).then(function (values) { return dst; }); } return $state; } function shouldSkipReload(to, toParams, from, fromParams, locals, options) { // Return true if there are no differences in non-search (path/object) params, false if there are differences function nonSearchParamsEqual(fromAndToState, fromParams, toParams) { // Identify whether all the parameters that differ between `fromParams` and `toParams` were search params. function notSearchParam(key) { return fromAndToState.params[key].location != "search"; } var nonQueryParamKeys = fromAndToState.params.$$keys().filter(notSearchParam); var nonQueryParams = pick.apply({}, [fromAndToState.params].concat(nonQueryParamKeys)); var nonQueryParamSet = new $$UMFP.ParamSet(nonQueryParams); return nonQueryParamSet.$$equals(fromParams, toParams); } // If reload was not explicitly requested // and we're transitioning to the same state we're already in // and the locals didn't change // or they changed in a way that doesn't merit reloading // (reloadOnParams:false, or reloadOnSearch.false and only search params changed) // Then return true. if (!options.reload && to === from && (locals === from.locals || (to.self.reloadOnSearch === false && nonSearchParamsEqual(from, fromParams, toParams)))) { return true; } } } angular.module('ui.router.state') .factory('$stateParams', function () { return {}; }) .constant("$state.runtime", { autoinject: true }) .provider('$state', $StateProvider) // Inject $state to initialize when entering runtime. #2574 .run(['$injector', function ($injector) { // Allow tests (stateSpec.js) to turn this off by defining this constant if ($injector.get("$state.runtime").autoinject) { $injector.get('$state'); } }]); $ViewProvider.$inject = []; function $ViewProvider() { this.$get = $get; /** * @ngdoc object * @name ui.router.state.$view * * @requires ui.router.util.$templateFactory * @requires $rootScope * * @description * */ $get.$inject = ['$rootScope', '$templateFactory']; function $get( $rootScope, $templateFactory) { return { // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... }) /** * @ngdoc function * @name ui.router.state.$view#load * @methodOf ui.router.state.$view * * @description * * @param {string} name name * @param {object} options option object. */ load: function load(name, options) { var result, defaults = { template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {} }; options = extend(defaults, options); if (options.view) { result = $templateFactory.fromConfig(options.view, options.params, options.locals); } return result; } }; } } angular.module('ui.router.state').provider('$view', $ViewProvider); /** * @ngdoc object * @name ui.router.state.$uiViewScrollProvider * * @description * Provider that returns the {@link ui.router.state.$uiViewScroll} service function. */ function $ViewScrollProvider() { var useAnchorScroll = false; /** * @ngdoc function * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll * @methodOf ui.router.state.$uiViewScrollProvider * * @description * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for * scrolling based on the url anchor. */ this.useAnchorScroll = function () { useAnchorScroll = true; }; /** * @ngdoc object * @name ui.router.state.$uiViewScroll * * @requires $anchorScroll * @requires $timeout * * @description * When called with a jqLite element, it scrolls the element into view (after a * `$timeout` so the DOM has time to refresh). * * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor, * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}. */ this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) { if (useAnchorScroll) { return $anchorScroll; } return function ($element) { return $timeout(function () { $element[0].scrollIntoView(); }, 0, false); }; }]; } angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider); /** * @ngdoc directive * @name ui.router.state.directive:ui-view * * @requires ui.router.state.$state * @requires $compile * @requires $controller * @requires $injector * @requires ui.router.state.$uiViewScroll * @requires $document * * @restrict ECA * * @description * The ui-view directive tells $state where to place your templates. * * @param {string=} name A view name. The name should be unique amongst the other views in the * same state. You can have views of the same name that live in different states. * * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you * scroll ui-view elements into view when they are populated during a state activation. * * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.* * * @param {string=} onload Expression to evaluate whenever the view updates. * * @example * A view can be unnamed or named. *
       * 
       * 
      * * *
      *
      * * You can only have one unnamed view within any template (or root html). If you are only using a * single view and it is unnamed then you can populate it like so: *
       * 
      * $stateProvider.state("home", { * template: "

      HELLO!

      " * }) *
      * * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#methods_state `views`} * config property, by name, in this case an empty name: *
       * $stateProvider.state("home", {
       *   views: {
       *     "": {
       *       template: "

      HELLO!

      " * } * } * }) *
      * * But typically you'll only use the views property if you name your view or have more than one view * in the same template. There's not really a compelling reason to name a view if its the only one, * but you could if you wanted, like so: *
       * 
      *
      *
       * $stateProvider.state("home", {
       *   views: {
       *     "main": {
       *       template: "

      HELLO!

      " * } * } * }) *
      * * Really though, you'll use views to set up multiple views: *
       * 
      *
      *
      *
      * *
       * $stateProvider.state("home", {
       *   views: {
       *     "": {
       *       template: "

      HELLO!

      " * }, * "chart": { * template: "" * }, * "data": { * template: "" * } * } * }) *
      * * Examples for `autoscroll`: * *
       * 
       * 
       *
       * 
       * 
       * 
       * 
       * 
      * * Resolve data: * * The resolved data from the state's `resolve` block is placed on the scope as `$resolve` (this * can be customized using [[ViewDeclaration.resolveAs]]). This can be then accessed from the template. * * Note that when `controllerAs` is being used, `$resolve` is set on the controller instance *after* the * controller is instantiated. The `$onInit()` hook can be used to perform initialization code which * depends on `$resolve` data. * * Example usage of $resolve in a view template *
       * $stateProvider.state('home', {
       *   template: '',
       *   resolve: {
       *     user: function(UserService) { return UserService.fetchUser(); }
       *   }
       * });
       * 
      */ $ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate', '$q']; function $ViewDirective( $state, $injector, $uiViewScroll, $interpolate, $q) { function getService() { return ($injector.has) ? function(service) { return $injector.has(service) ? $injector.get(service) : null; } : function(service) { try { return $injector.get(service); } catch (e) { return null; } }; } var service = getService(), $animator = service('$animator'), $animate = service('$animate'); // Returns a set of DOM manipulation functions based on which Angular version // it should use function getRenderer(attrs, scope) { var statics = function() { return { enter: function (element, target, cb) { target.after(element); cb(); }, leave: function (element, cb) { element.remove(); cb(); } }; }; if ($animate) { return { enter: function(element, target, cb) { if (angular.version.minor > 2) { $animate.enter(element, null, target).then(cb); } else { $animate.enter(element, null, target, cb); } }, leave: function(element, cb) { if (angular.version.minor > 2) { $animate.leave(element).then(cb); } else { $animate.leave(element, cb); } } }; } if ($animator) { var animate = $animator && $animator(scope, attrs); return { enter: function(element, target, cb) {animate.enter(element, null, target); cb(); }, leave: function(element, cb) { animate.leave(element); cb(); } }; } return statics(); } var directive = { restrict: 'ECA', terminal: true, priority: 400, transclude: 'element', compile: function (tElement, tAttrs, $transclude) { return function (scope, $element, attrs) { var previousEl, currentEl, currentScope, latestLocals, onloadExp = attrs.onload || '', autoScrollExp = attrs.autoscroll, renderer = getRenderer(attrs, scope), inherited = $element.inheritedData('$uiView'); scope.$on('$stateChangeSuccess', function() { updateView(false); }); updateView(true); function cleanupLastView() { if (previousEl) { previousEl.remove(); previousEl = null; } if (currentScope) { currentScope.$destroy(); currentScope = null; } if (currentEl) { var $uiViewData = currentEl.data('$uiViewAnim'); renderer.leave(currentEl, function() { $uiViewData.$$animLeave.resolve(); previousEl = null; }); previousEl = currentEl; currentEl = null; } } function updateView(firstTime) { var newScope, name = getUiViewName(scope, attrs, $element, $interpolate), previousLocals = name && $state.$current && $state.$current.locals[name]; if (!firstTime && previousLocals === latestLocals) return; // nothing to do newScope = scope.$new(); latestLocals = $state.$current.locals[name]; /** * @ngdoc event * @name ui.router.state.directive:ui-view#$viewContentLoading * @eventOf ui.router.state.directive:ui-view * @eventType emits on ui-view directive scope * @description * * Fired once the view **begins loading**, *before* the DOM is rendered. * * @param {Object} event Event object. * @param {string} viewName Name of the view. */ newScope.$emit('$viewContentLoading', name); var clone = $transclude(newScope, function(clone) { var animEnter = $q.defer(), animLeave = $q.defer(); var viewAnimData = { $animEnter: animEnter.promise, $animLeave: animLeave.promise, $$animLeave: animLeave }; clone.data('$uiViewAnim', viewAnimData); renderer.enter(clone, $element, function onUiViewEnter() { animEnter.resolve(); if(currentScope) { currentScope.$emit('$viewContentAnimationEnded'); } if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) { $uiViewScroll(clone); } }); cleanupLastView(); }); currentEl = clone; currentScope = newScope; /** * @ngdoc event * @name ui.router.state.directive:ui-view#$viewContentLoaded * @eventOf ui.router.state.directive:ui-view * @eventType emits on ui-view directive scope * @description * Fired once the view is **loaded**, *after* the DOM is rendered. * * @param {Object} event Event object. * @param {string} viewName Name of the view. */ currentScope.$emit('$viewContentLoaded', name); currentScope.$eval(onloadExp); } }; } }; return directive; } $ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate']; function $ViewDirectiveFill ( $compile, $controller, $state, $interpolate) { return { restrict: 'ECA', priority: -400, compile: function (tElement) { var initial = tElement.html(); if (tElement.empty) { tElement.empty(); } else { // ng 1.0.0 doesn't have empty(), which cleans up data and handlers tElement[0].innerHTML = null; } return function (scope, $element, attrs) { var current = $state.$current, name = getUiViewName(scope, attrs, $element, $interpolate), locals = current && current.locals[name]; if (! locals) { $element.html(initial); $compile($element.contents())(scope); return; } $element.data('$uiView', { name: name, state: locals.$$state }); $element.html(locals.$template ? locals.$template : initial); var resolveData = angular.extend({}, locals); scope[locals.$$resolveAs] = resolveData; var link = $compile($element.contents()); if (locals.$$controller) { locals.$scope = scope; locals.$element = $element; var controller = $controller(locals.$$controller, locals); if (locals.$$controllerAs) { scope[locals.$$controllerAs] = controller; scope[locals.$$controllerAs][locals.$$resolveAs] = resolveData; } if (isFunction(controller.$onInit)) controller.$onInit(); $element.data('$ngControllerController', controller); $element.children().data('$ngControllerController', controller); } link(scope); }; } }; } /** * Shared ui-view code for both directives: * Given scope, element, and its attributes, return the view's name */ function getUiViewName(scope, attrs, element, $interpolate) { var name = $interpolate(attrs.uiView || attrs.name || '')(scope); var uiViewCreatedBy = element.inheritedData('$uiView'); return name.indexOf('@') >= 0 ? name : (name + '@' + (uiViewCreatedBy ? uiViewCreatedBy.state.name : '')); } angular.module('ui.router.state').directive('uiView', $ViewDirective); angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill); function parseStateRef(ref, current) { var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed; if (preparsed) ref = current + '(' + preparsed[1] + ')'; parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/); if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'"); return { state: parsed[1], paramExpr: parsed[3] || null }; } function stateContext(el) { var stateData = el.parent().inheritedData('$uiView'); if (stateData && stateData.state && stateData.state.name) { return stateData.state; } } function getTypeInfo(el) { // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. var isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]'; var isForm = el[0].nodeName === "FORM"; return { attr: isForm ? "action" : (isSvg ? 'xlink:href' : 'href'), isAnchor: el.prop("tagName").toUpperCase() === "A", clickable: !isForm }; } function clickHook(el, $state, $timeout, type, current) { return function(e) { var button = e.which || e.button, target = current(); if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) { // HACK: This is to allow ng-clicks to be processed before the transition is initiated: var transition = $timeout(function() { $state.go(target.state, target.params, target.options); }); e.preventDefault(); // if the state has no URL, ignore one preventDefault from the directive. var ignorePreventDefaultCount = type.isAnchor && !target.href ? 1: 0; e.preventDefault = function() { if (ignorePreventDefaultCount-- <= 0) $timeout.cancel(transition); }; } }; } function defaultOpts(el, $state) { return { relative: stateContext(el) || $state.$current, inherit: true }; } /** * @ngdoc directive * @name ui.router.state.directive:ui-sref * * @requires ui.router.state.$state * @requires $timeout * * @restrict A * * @description * A directive that binds a link (`` tag) to a state. If the state has an associated * URL, the directive will automatically generate & update the `href` attribute via * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking * the link will trigger a state transition with optional parameters. * * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be * handled natively by the browser. * * You can also use relative state paths within ui-sref, just like the relative * paths passed to `$state.go()`. You just need to be aware that the path is relative * to the state that the link lives in, in other words the state that loaded the * template containing the link. * * You can specify options to pass to {@link ui.router.state.$state#methods_go $state.go()} * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`, * and `reload`. * * @example * Here's an example of how you'd use ui-sref and how it would compile. If you have the * following template: *
       * Home | About | Next page
       *
       * 
       * 
      * * Then the compiled html would be (assuming Html5Mode is off and current state is contacts): *
       * Home | About | Next page
       *
       * 
       *
       * Home
       * 
      * * @param {string} ui-sref 'stateName' can be any valid absolute or relative state * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#methods_go $state.go()} */ $StateRefDirective.$inject = ['$state', '$timeout']; function $StateRefDirective($state, $timeout) { return { restrict: 'A', require: ['?^uiSrefActive', '?^uiSrefActiveEq'], link: function(scope, element, attrs, uiSrefActive) { var ref = parseStateRef(attrs.uiSref, $state.current.name); var def = { state: ref.state, href: null, params: null }; var type = getTypeInfo(element); var active = uiSrefActive[1] || uiSrefActive[0]; var unlinkInfoFn = null; var hookFn; def.options = extend(defaultOpts(element, $state), attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {}); var update = function(val) { if (val) def.params = angular.copy(val); def.href = $state.href(ref.state, def.params, def.options); if (unlinkInfoFn) unlinkInfoFn(); if (active) unlinkInfoFn = active.$$addStateInfo(ref.state, def.params); if (def.href !== null) attrs.$set(type.attr, def.href); }; if (ref.paramExpr) { scope.$watch(ref.paramExpr, function(val) { if (val !== def.params) update(val); }, true); def.params = angular.copy(scope.$eval(ref.paramExpr)); } update(); if (!type.clickable) return; hookFn = clickHook(element, $state, $timeout, type, function() { return def; }); element[element.on ? 'on' : 'bind']("click", hookFn); scope.$on('$destroy', function() { element[element.off ? 'off' : 'unbind']("click", hookFn); }); } }; } /** * @ngdoc directive * @name ui.router.state.directive:ui-state * * @requires ui.router.state.uiSref * * @restrict A * * @description * Much like ui-sref, but will accept named $scope properties to evaluate for a state definition, * params and override options. * * @param {string} ui-state 'stateName' can be any valid absolute or relative state * @param {Object} ui-state-params params to pass to {@link ui.router.state.$state#methods_href $state.href()} * @param {Object} ui-state-opts options to pass to {@link ui.router.state.$state#methods_go $state.go()} */ $StateRefDynamicDirective.$inject = ['$state', '$timeout']; function $StateRefDynamicDirective($state, $timeout) { return { restrict: 'A', require: ['?^uiSrefActive', '?^uiSrefActiveEq'], link: function(scope, element, attrs, uiSrefActive) { var type = getTypeInfo(element); var active = uiSrefActive[1] || uiSrefActive[0]; var group = [attrs.uiState, attrs.uiStateParams || null, attrs.uiStateOpts || null]; var watch = '[' + group.map(function(val) { return val || 'null'; }).join(', ') + ']'; var def = { state: null, params: null, options: null, href: null }; var unlinkInfoFn = null; var hookFn; function runStateRefLink (group) { def.state = group[0]; def.params = group[1]; def.options = group[2]; def.href = $state.href(def.state, def.params, def.options); if (unlinkInfoFn) unlinkInfoFn(); if (active) unlinkInfoFn = active.$$addStateInfo(def.state, def.params); if (def.href) attrs.$set(type.attr, def.href); } scope.$watch(watch, runStateRefLink, true); runStateRefLink(scope.$eval(watch)); if (!type.clickable) return; hookFn = clickHook(element, $state, $timeout, type, function() { return def; }); element[element.on ? 'on' : 'bind']("click", hookFn); scope.$on('$destroy', function() { element[element.off ? 'off' : 'unbind']("click", hookFn); }); } }; } /** * @ngdoc directive * @name ui.router.state.directive:ui-sref-active * * @requires ui.router.state.$state * @requires ui.router.state.$stateParams * @requires $interpolate * * @restrict A * * @description * A directive working alongside ui-sref to add classes to an element when the * related ui-sref directive's state is active, and removing them when it is inactive. * The primary use-case is to simplify the special appearance of navigation menus * relying on `ui-sref`, by having the "active" state's menu button appear different, * distinguishing it from the inactive menu items. * * ui-sref-active can live on the same element as ui-sref or on a parent element. The first * ui-sref-active found at the same level or above the ui-sref will be used. * * Will activate when the ui-sref's target state or any child state is active. If you * need to activate only when the ui-sref target state is active and *not* any of * it's children, then you will use * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq} * * @example * Given the following template: *
       * 
       * 
      * * * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins", * the resulting HTML will appear as (note the 'active' class): *
       * 
       * 
      * * The class name is interpolated **once** during the directives link time (any further changes to the * interpolated value are ignored). * * Multiple classes may be specified in a space-separated format: *
       * 
       * 
      * * It is also possible to pass ui-sref-active an expression that evaluates * to an object hash, whose keys represent active class names and whose * values represent the respective state names/globs. * ui-sref-active will match if the current active state **includes** any of * the specified state names/globs, even the abstract ones. * * @Example * Given the following template, with "admin" being an abstract state: *
       * 
      * Roles *
      *
      * * When the current state is "admin.roles" the "active" class will be applied * to both the
      and elements. It is important to note that the state * names/globs passed to ui-sref-active shadow the state provided by ui-sref. */ /** * @ngdoc directive * @name ui.router.state.directive:ui-sref-active-eq * * @requires ui.router.state.$state * @requires ui.router.state.$stateParams * @requires $interpolate * * @restrict A * * @description * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate * when the exact target state used in the `ui-sref` is active; no child states. * */ $StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate']; function $StateRefActiveDirective($state, $stateParams, $interpolate) { return { restrict: "A", controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) { var states = [], activeClasses = {}, activeEqClass, uiSrefActive; // There probably isn't much point in $observing this // uiSrefActive and uiSrefActiveEq share the same directive object with some // slight difference in logic routing activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope); try { uiSrefActive = $scope.$eval($attrs.uiSrefActive); } catch (e) { // Do nothing. uiSrefActive is not a valid expression. // Fall back to using $interpolate below } uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope); if (isObject(uiSrefActive)) { forEach(uiSrefActive, function(stateOrName, activeClass) { if (isString(stateOrName)) { var ref = parseStateRef(stateOrName, $state.current.name); addState(ref.state, $scope.$eval(ref.paramExpr), activeClass); } }); } // Allow uiSref to communicate with uiSrefActive[Equals] this.$$addStateInfo = function (newState, newParams) { // we already got an explicit state provided by ui-sref-active, so we // shadow the one that comes from ui-sref if (isObject(uiSrefActive) && states.length > 0) { return; } var deregister = addState(newState, newParams, uiSrefActive); update(); return deregister; }; $scope.$on('$stateChangeSuccess', update); function addState(stateName, stateParams, activeClass) { var state = $state.get(stateName, stateContext($element)); var stateHash = createStateHash(stateName, stateParams); var stateInfo = { state: state || { name: stateName }, params: stateParams, hash: stateHash }; states.push(stateInfo); activeClasses[stateHash] = activeClass; return function removeState() { var idx = states.indexOf(stateInfo); if (idx !== -1) states.splice(idx, 1); }; } /** * @param {string} state * @param {Object|string} [params] * @return {string} */ function createStateHash(state, params) { if (!isString(state)) { throw new Error('state should be a string'); } if (isObject(params)) { return state + toJson(params); } params = $scope.$eval(params); if (isObject(params)) { return state + toJson(params); } return state; } // Update route state function update() { for (var i = 0; i < states.length; i++) { if (anyMatch(states[i].state, states[i].params)) { addClass($element, activeClasses[states[i].hash]); } else { removeClass($element, activeClasses[states[i].hash]); } if (exactMatch(states[i].state, states[i].params)) { addClass($element, activeEqClass); } else { removeClass($element, activeEqClass); } } } function addClass(el, className) { $timeout(function () { el.addClass(className); }); } function removeClass(el, className) { el.removeClass(className); } function anyMatch(state, params) { return $state.includes(state.name, params); } function exactMatch(state, params) { return $state.is(state.name, params); } update(); }] }; } angular.module('ui.router.state') .directive('uiSref', $StateRefDirective) .directive('uiSrefActive', $StateRefActiveDirective) .directive('uiSrefActiveEq', $StateRefActiveDirective) .directive('uiState', $StateRefDynamicDirective); /** * @ngdoc filter * @name ui.router.state.filter:isState * * @requires ui.router.state.$state * * @description * Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}. */ $IsStateFilter.$inject = ['$state']; function $IsStateFilter($state) { var isFilter = function (state, params) { return $state.is(state, params); }; isFilter.$stateful = true; return isFilter; } /** * @ngdoc filter * @name ui.router.state.filter:includedByState * * @requires ui.router.state.$state * * @description * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}. */ $IncludedByStateFilter.$inject = ['$state']; function $IncludedByStateFilter($state) { var includesFilter = function (state, params, options) { return $state.includes(state, params, options); }; includesFilter.$stateful = true; return includesFilter; } angular.module('ui.router.state') .filter('isState', $IsStateFilter) .filter('includedByState', $IncludedByStateFilter); })(window, window.angular); /** * Duo Web SDK v2 * Copyright 2017, Duo Security */ (function (root, factory) { /*eslint-disable */ if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); /*eslint-enable */ } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) var Duo = factory(); // If the Javascript was loaded via a script tag, attempt to autoload // the frame. Duo._onReady(Duo.init); // Attach Duo to the `window` object root.Duo = Duo; } }(this, function() { var DUO_MESSAGE_FORMAT = /^(?:AUTH|ENROLL)+\|[A-Za-z0-9\+\/=]+\|[A-Za-z0-9\+\/=]+$/; var DUO_ERROR_FORMAT = /^ERR\|[\w\s\.\(\)]+$/; var DUO_OPEN_WINDOW_FORMAT = /^DUO_OPEN_WINDOW\|/; var VALID_OPEN_WINDOW_DOMAINS = [ 'duo.com', 'duosecurity.com', 'duomobile.s3-us-west-1.amazonaws.com' ]; var iframeId = 'duo_iframe', postAction = '', postArgument = 'sig_response', host, sigRequest, duoSig, appSig, iframe, submitCallback; function throwError(message, url) { throw new Error( 'Duo Web SDK error: ' + message + (url ? ('\n' + 'See ' + url + ' for more information') : '') ); } function hyphenize(str) { return str.replace(/([a-z])([A-Z])/, '$1-$2').toLowerCase(); } // cross-browser data attributes function getDataAttribute(element, name) { if ('dataset' in element) { return element.dataset[name]; } else { return element.getAttribute('data-' + hyphenize(name)); } } // cross-browser event binding/unbinding function on(context, event, fallbackEvent, callback) { if ('addEventListener' in window) { context.addEventListener(event, callback, false); } else { context.attachEvent(fallbackEvent, callback); } } function off(context, event, fallbackEvent, callback) { if ('removeEventListener' in window) { context.removeEventListener(event, callback, false); } else { context.detachEvent(fallbackEvent, callback); } } function onReady(callback) { on(document, 'DOMContentLoaded', 'onreadystatechange', callback); } function offReady(callback) { off(document, 'DOMContentLoaded', 'onreadystatechange', callback); } function onMessage(callback) { on(window, 'message', 'onmessage', callback); } function offMessage(callback) { off(window, 'message', 'onmessage', callback); } /** * Parse the sig_request parameter, throwing errors if the token contains * a server error or if the token is invalid. * * @param {String} sig Request token */ function parseSigRequest(sig) { if (!sig) { // nothing to do return; } // see if the token contains an error, throwing it if it does if (sig.indexOf('ERR|') === 0) { throwError(sig.split('|')[1]); } // validate the token if (sig.indexOf(':') === -1 || sig.split(':').length !== 2) { throwError( 'Duo was given a bad token. This might indicate a configuration ' + 'problem with one of Duo\'s client libraries.', 'https://www.duosecurity.com/docs/duoweb#first-steps' ); } var sigParts = sig.split(':'); // hang on to the token, and the parsed duo and app sigs sigRequest = sig; duoSig = sigParts[0]; appSig = sigParts[1]; return { sigRequest: sig, duoSig: sigParts[0], appSig: sigParts[1] }; } /** * This function is set up to run when the DOM is ready, if the iframe was * not available during `init`. */ function onDOMReady() { iframe = document.getElementById(iframeId); if (!iframe) { throw new Error( 'This page does not contain an iframe for Duo to use.' + 'Add an element like ' + 'to this page. ' + 'See https://www.duosecurity.com/docs/duoweb#3.-show-the-iframe ' + 'for more information.' ); } // we've got an iframe, away we go! ready(); // always clean up after yourself offReady(onDOMReady); } /** * Validate that a MessageEvent came from the Duo service, and that it * is a properly formatted payload. * * The Google Chrome sign-in page injects some JS into pages that also * make use of postMessage, so we need to do additional validation above * and beyond the origin. * * @param {MessageEvent} event Message received via postMessage */ function isDuoMessage(event) { return Boolean( event.origin === ('https://' + host) && typeof event.data === 'string' && ( event.data.match(DUO_MESSAGE_FORMAT) || event.data.match(DUO_ERROR_FORMAT) || event.data.match(DUO_OPEN_WINDOW_FORMAT) ) ); } /** * Validate the request token and prepare for the iframe to become ready. * * All options below can be passed into an options hash to `Duo.init`, or * specified on the iframe using `data-` attributes. * * Options specified using the options hash will take precedence over * `data-` attributes. * * Example using options hash: * ```javascript * Duo.init({ * iframe: "some_other_id", * host: "api-main.duo.test", * sig_request: "...", * post_action: "/auth", * post_argument: "resp" * }); * ``` * * Example using `data-` attributes: * ``` * * ``` * * @param {Object} options * @param {String} options.iframe The iframe, or id of an iframe to set up * @param {String} options.host Hostname * @param {String} options.sig_request Request token * @param {String} [options.post_action=''] URL to POST back to after successful auth * @param {String} [options.post_argument='sig_response'] Parameter name to use for response token * @param {Function} [options.submit_callback] If provided, duo will not submit the form instead execute * the callback function with reference to the "duo_form" form object * submit_callback can be used to prevent the webpage from reloading. */ function init(options) { if (options) { if (options.host) { host = options.host; } if (options.sig_request) { parseSigRequest(options.sig_request); } if (options.post_action) { postAction = options.post_action; } if (options.post_argument) { postArgument = options.post_argument; } if (options.iframe) { if (options.iframe.tagName) { iframe = options.iframe; } else if (typeof options.iframe === 'string') { iframeId = options.iframe; } } if (typeof options.submit_callback === 'function') { submitCallback = options.submit_callback; } } // if we were given an iframe, no need to wait for the rest of the DOM if (false && iframe) { ready(); } else { // try to find the iframe in the DOM iframe = document.getElementById(iframeId); // iframe is in the DOM, away we go! if (iframe) { ready(); } else { // wait until the DOM is ready, then try again onReady(onDOMReady); } } // always clean up after yourself! offReady(init); } /** * This function is called when a message was received from another domain * using the `postMessage` API. Check that the event came from the Duo * service domain, and that the message is a properly formatted payload, * then perform the post back to the primary service. * * @param event Event object (contains origin and data) */ function onReceivedMessage(event) { if (isDuoMessage(event)) { if (event.data.match(DUO_OPEN_WINDOW_FORMAT)) { var url = event.data.substring("DUO_OPEN_WINDOW|".length); if (isValidUrlToOpen(url)) { // Open the URL that comes after the DUO_WINDOW_OPEN token. window.open(url, "_self"); } } else { // the event came from duo, do the post back doPostBack(event.data); // always clean up after yourself! offMessage(onReceivedMessage); } } } /** * Validate that this passed in URL is one that we will actually allow to * be opened. * @param url String URL that the message poster wants to open * @returns {boolean} true if we allow this url to be opened in the window */ function isValidUrlToOpen(url) { if (!url) { return false; } var parser = document.createElement('a'); parser.href = url; if (parser.protocol === "duotrustedendpoints:") { return true; } else if (parser.protocol !== "https:") { return false; } for (var i = 0; i < VALID_OPEN_WINDOW_DOMAINS.length; i++) { if (parser.hostname.endsWith("." + VALID_OPEN_WINDOW_DOMAINS[i]) || parser.hostname === VALID_OPEN_WINDOW_DOMAINS[i]) { return true; } } return false; } /** * Point the iframe at Duo, then wait for it to postMessage back to us. */ function ready() { if (!host) { host = getDataAttribute(iframe, 'host'); if (!host) { throwError( 'No API hostname is given for Duo to use. Be sure to pass ' + 'a `host` parameter to Duo.init, or through the `data-host` ' + 'attribute on the iframe element.', 'https://www.duosecurity.com/docs/duoweb#3.-show-the-iframe' ); } } if (!duoSig || !appSig) { parseSigRequest(getDataAttribute(iframe, 'sigRequest')); if (!duoSig || !appSig) { throwError( 'No valid signed request is given. Be sure to give the ' + '`sig_request` parameter to Duo.init, or use the ' + '`data-sig-request` attribute on the iframe element.', 'https://www.duosecurity.com/docs/duoweb#3.-show-the-iframe' ); } } // if postAction/Argument are defaults, see if they are specified // as data attributes on the iframe if (postAction === '') { postAction = getDataAttribute(iframe, 'postAction') || postAction; } if (postArgument === 'sig_response') { postArgument = getDataAttribute(iframe, 'postArgument') || postArgument; } // point the iframe at Duo iframe.src = [ 'https://', host, '/frame/web/v1/auth?tx=', duoSig, '&parent=', encodeURIComponent(document.location.href), '&v=2.6' ].join(''); // listen for the 'message' event onMessage(onReceivedMessage); } /** * We received a postMessage from Duo. POST back to the primary service * with the response token, and any additional user-supplied parameters * given in form#duo_form. */ function doPostBack(response) { // create a hidden input to contain the response token var input = document.createElement('input'); input.type = 'hidden'; input.name = postArgument; input.value = response + ':' + appSig; // user may supply their own form with additional inputs var form = document.getElementById('duo_form'); // if the form doesn't exist, create one if (!form) { form = document.createElement('form'); // insert the new form after the iframe iframe.parentElement.insertBefore(form, iframe.nextSibling); } // make sure we are actually posting to the right place form.method = 'POST'; form.action = postAction; // add the response token input to the form form.appendChild(input); // away we go! if (typeof submitCallback === "function") { submitCallback.call(null, form); } else { form.submit(); } } return { init: init, _onReady: onReady, _parseSigRequest: parseSigRequest, _isDuoMessage: isDuoMessage, _doPostBack: doPostBack }; })); (function(window, angular, undefined) {'use strict'; /** * @ngdoc overview * @name angulartics.google.analytics * Enables analytics support for Google Analytics (http://google.com/analytics) */ angular.module('angulartics.google.analytics', ['angulartics']) .config(['$analyticsProvider', function ($analyticsProvider) { // GA already supports buffered invocations so we don't need // to wrap these inside angulartics.waitForVendorApi $analyticsProvider.settings.pageTracking.trackRelativePath = true; // Set the default settings for this module $analyticsProvider.settings.ga = { additionalAccountNames: undefined, // Select hits to send to all additional accounts additionalAccountHitTypes: { pageview: true, event: true, exception: false, ecommerce: false, userTiming: false, setUserProperties: false, userId: false }, disableEventTracking: null, disablePageTracking: null, enhancedEcommerce: false, // GA supports transporting data via gif requests, XHRs, or sendBeacons // @link https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#transport transport: null, userId: null }; /** * Track Pageview in GA * @name pageTrack * * @param {string} path value of Page dimension stored with hit e.g. '/home' * @param {object} properties Object with optional addtional Custom Dimensions/Metrics * * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/pages * @link https://developers.google.com/analytics/devguides/collection/gajs/ */ $analyticsProvider.registerPageTrack(function (path, properties) { properties = properties || {}; // Do nothing if page tracking is disabled if ($analyticsProvider.settings.ga.disablePageTracking) return; dispatchToGa('pageview', 'send', angular.extend({}, properties, { hitType: 'pageview', page: path })); }); /** * Track Event in GA * @name eventTrack * * @param {string} action Required 'action' (string) associated with the event * @param {object} properties Comprised of the mandatory field 'category' (string) and optional fields 'label' (string), 'value' (integer) and 'nonInteraction' (boolean) * * @link https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide#SettingUpEventTracking * * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/events */ $analyticsProvider.registerEventTrack(function(action, properties) { // Do nothing if event tracking is disabled if ($analyticsProvider.settings.ga.disableEventTracking) return; if (!action && action + '' !== '0') { return; } // Sets default properties properties = properties || {}; properties.category = properties.category || 'Event'; // GA requires that eventValue be an integer, see: // https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#eventValue // https://github.com/luisfarzati/angulartics/issues/81 if (properties.value) { var parsed = parseInt(properties.value, 10); properties.value = isNaN(parsed) ? 0 : parsed; } // GA requires that hitCallback be an function, see: // https://developers.google.com/analytics/devguides/collection/analyticsjs/sending-hits#hitcallback if (!angular.isFunction(properties.hitCallback)) { properties.hitCallback = null; } // Making nonInteraction parameter more intuitive, includes backwards compatibilty // https://github.com/angulartics/angulartics-google-analytics/issues/49 properties.nonInteraction = properties.nonInteraction || properties.noninteraction; dispatchToGa('event', 'send', angular.extend({}, properties, { hitType: 'event', eventCategory: properties.category, eventAction: action, eventLabel: properties.label, eventValue: properties.value, nonInteraction: properties.nonInteraction, page: properties.page || window.location.hash.substring(1) || window.location.pathname, hitCallback: properties.hitCallback, })); }); /** * Exception Track Event in GA * @name exceptionTrack * Sugar on top of the eventTrack method for easily handling errors * * @param {object} error An Error object to track: error.toString() used for event 'action', error.stack used for event 'label'. * @param {object} cause The cause of the error given from $exceptionHandler, not used. * * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/events */ $analyticsProvider.registerExceptionTrack(function (error, cause) { dispatchToGa('exception', 'send', { hitType: 'event', eventCategory: 'Exceptions', eventAction: error.toString(), eventLabel: error.stack, nonInteraction: true, page: window.location.hash.substring(1) || window.location.pathname, isException: true }); }); /** * Set Username * @name setUsername * * @param {string} userId Registers User ID of user for use with other hits * * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id#user_id */ $analyticsProvider.registerSetUsername(function (userId) { $analyticsProvider.settings.ga.userId = userId; }); /** * Set User Properties * @name setUserProperties * * @param {object} properties Sets all properties with dimensionN or metricN to their respective values * * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#customs */ $analyticsProvider.registerSetUserProperties(function (properties) { if (properties) { dispatchToGa('setUserProperties', 'set', dimensionsAndMetrics(properties)); } }); /** * User Timings Event in GA * @name userTimings * * @param {object} properties Comprised of the mandatory fields: * 'timingCategory' (string), * 'timingVar' (string), * 'timingValue' (number) * Properties can also have the optional fields: * 'timingLabel' (string) * 'optSampleRate' (number) Classic Analytics only - determines % of users to collect data from, handled serverside by UA * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/user-timings#sampling_considerations * * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/user-timings */ $analyticsProvider.registerUserTimings(function (properties) { if (!angular.isObject(properties) || angular.isArray(properties)) { return console.log('Required argument properties is missing or not an object'); } angular.forEach(['timingCategory', 'timingVar', 'timingValue'], function(prop) { if (angular.isUndefined(properties[prop])) { return console.log('Argument properties missing required property ' + prop); } }); dispatchToGa('userTiming', 'send', { hitType: 'timing', timingCategory: properties.timingCategory, timingVar: properties.timingVar, timingValue: properties.timingValue, timingLabel: properties.timingLabel, optSampleRate: properties.optSampleRate, // Classic Analytics only page: properties.page || window.location.hash.substring(1) || window.location.pathname, }); }); /** * Ecommerce Tracking in GA * @name transactionTrack * * @param {object} transaction comprised of following fields: * 'id': 'T12345', // Transaction ID. Required for purchases and refunds. * 'affiliation': 'Online Store', * 'revenue': '35.43', // Total transaction value (incl. tax and shipping) * 'tax':'4.90', * 'shipping': '5.99', * 'coupon': 'SUMMER_SALE', // Enhanced Ecommerce Only * 'dimension1': 'Card ID #1234', // Hit, Session, or User-level Custom Dimension(s) * 'metric1': 1, // Custom Metric(s) * 'currencyCode': 'EUR', // Currency Code to track the transaction with. Recognized codes: https://support.google.com/analytics/answer/6205902?hl=en#supported-currencies * 'billingCity': 'San Francisco', // Classic Analytics only * 'billingRegion': 'California', // Classic Analytics only * 'billingCountry': 'USA', // Classic Analytics only * 'products': [{ // List of products * 'name': 'Triblend Android T-Shirt', // Name or ID is required. * 'id': '12345', // Product SKU * 'price': '15.25', * 'brand': 'Google', // Enhanced Ecommerce only * 'category': 'Apparel', * 'variant': 'Gray', // Enhanced Ecommerce only * 'quantity': 1, * 'coupon': '', // Enhanced Ecommerce only. * 'currencyCode': 'BRL', // Product-level currency code, Enhanced Ecommerce only * 'dimension2': 'Clearance', // Product-level Custom Dimension * 'metric2': 1 // Product-level Custom Metric * }, * ... * ] * * @param {object] properties comprised of custom dimensions and metrics to * send with the transaction hit * Utilizes traditional ecommerce tracking by default. To used Enhanced Ecommerce, * set the $analytics.settings.ga.enhancedEcommerce flag to true * * Docs on traditional ecommerce (UA): * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce * * Docs on Enhanced Ecommerce * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce * * Docs on Classic Ecommerce (_gaq) * @link https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce **/ $analyticsProvider.registerTransactionTrack(function(transaction) { var product; var i; // Universal Analytics splits off the ecommerce code into a separate // library we must include by using the "require" command dispatchToGa('ecommerce', 'require', 'ecommerce'); dispatchToGa('ecommerce', 'ecommerce:addTransaction', transaction); if (transaction.products) { for (i = 0; i < transaction.products.length; i++) { product = transaction.products[i]; // GA uses a SKU property and stores the transaction ID in the ID Field product.sku = product.id; product.id = transaction.id; dispatchToGa('ecommerce', 'ecommerce:addItem', transaction.products[i]); } } if (transaction.currencyCode) { dispatchToGa('ecommerce', '_set', transaction.currencyCode); // Classic Anayltics only - UA uses fieldsObj.currencyCode instead } dispatchToGa('ecommerce', 'ecommerce:send', angular.copy(transaction)); }); /** * Detects if Universal Analytics is installed * * @name detectUniversalAnalytics */ function detectUniversalAnalytics() { // Use the GoogleAnalyticsObject property set by the default GA snippet // to correctly determine the namespace of the GA global var gaNamespace = window.GoogleAnalyticsObject; return gaNamespace && window[gaNamespace]; } /** * Detects if Classic Analytics is installed * * @name detectClassicAnalytics */ function detectClassicAnalytics() { // If _gaq is undefined, we're trusting Classic Analytics to be there return !angular.isUndefined(window._gaq); } /** * Extract Custom Data for a hit * @name dimensionsAndMetrics * * @param {object} properties properties object from an API call that is filtered for Custom Dimensions & Metrics * * @returns {object} customData object with only Custom Dimensions/Metrics from properties argument */ function dimensionsAndMetrics(properties) { // add custom dimensions and metrics var customData = {}; var key; for (key in properties) { // Keys must be dimensionXX or metricXX, e.g. dimension1, metric155, so // if those strings aren't at zero (which evaluates to falsey), ignore // the key if (!key.indexOf('dimension') || !key.indexOf('metric')) { customData[key] = properties[key]; } } return customData; } /** * Handler for hits to GA. Dynamically adjusts syntax for * targeted version based on global detection. * * @name dispatchToGa * * @param {string} method Name of angulartics method for checking if hits should be duplicated * @param {string} command Standard Universal Analytics command (create, send, set) * @param {object} fieldsObj object with hit-specific fields. Fields are whitelisted in handler - non-supported fields are ignored. * */ var dispatchToGa = (function() { var handler; if (detectClassicAnalytics()) { handler = dispatchToClassic_; } if (detectUniversalAnalytics()) { handler = dispatchToUniversal_; } // If neither has been detected, GA is not above the angular code if (!handler) { return angular.noop; } return function(method, command, fieldsObj) { var shouldCopyHit = $analyticsProvider.settings.ga.additionalAccountHitTypes[method]; handler(command, fieldsObj, shouldCopyHit); } /** * Dispatches a hit using Universal syntax * * @name dispatchToUniversal_ * @private * * @param {string} command Standard Universal Analytics command (create, send, set) * @param {object} fieldsObj object with hit-specific fields. Fields are whitelisted in handler - non-supported fields are ignored. * @param {boolean} shouldCopyHit should hit be propogated to all trackers */ function dispatchToUniversal_(command, fieldsObj, shouldCopyHit) { var userId = $analyticsProvider.settings.ga.userId; var uaCommand, pluginName; if (command === 'require' && fieldsObj === 'ecommerce') { pluginName = fieldsObj; if ($analyticsProvider.settings.ga.enhancedEcommerce) { pluginName = 'ec'; } // Exit here - require calls don't have fieldsObjs return applyUniversalCall_([command, pluginName], shouldCopyHit); } // If our User ID is set, set it on the hit if (userId && angular.isObject(fieldsObj)) fieldsObj.userId = userId; // If a transport preference is specified, set it on the hit if ($analyticsProvider.settings.ga.transport) { fieldsObj.transport = $analyticsProvider.settings.ga.transport; } if (command.indexOf('ecommerce:') > -1 && $analyticsProvider.settings.ga.enhancedEcommerce) { switch (command) { case 'ecommerce:addTransaction': command = ['ec:setAction', 'purchase']; break; case 'ecommerce:addItem': command = 'ec:addProduct'; // Enhanced Ecommerce reverts to using the ID property for the SKU, // so we swap them back here fieldsObj.id = fieldsObj.sku; break; case 'ecommerce:send': command = 'send'; fieldsObj.hitType = 'event'; fieldsObj.eventCategory = 'Angulartics Enhanced Ecommerce'; fieldsObj.eventAction = 'Purchase'; fieldsObj.nonInteraction = true; break; } } uaCommand = command instanceof Array ? command.concat(fieldsObj) : [command, fieldsObj]; applyUniversalCall_(uaCommand, shouldCopyHit); } /** * Handles applying a constructed call to the global Universal GA object * This exists primarily so calls within dispatchToUa_ can short circuit * out of the function to handle specific edge cases, e.g. require commands * @name applyUniversalCall_ * @private * * @param commandArray {array} command to be .apply()'d * @param shouldCopyHit {boolean} should the command be applied to all accts */ function applyUniversalCall_(commandArray, shouldCopyHit) { var userId = $analyticsProvider.settings.ga.userId; var gaNamespace = window.GoogleAnalyticsObject; var commandClone; // Perform our initial call window[gaNamespace].apply(this, commandArray); if (shouldCopyHit) { commandClone = angular.copy(commandArray); // If the userId shouldn't be duplicated, remove from the fieldsObj if (userId && !$analyticsProvider.settings.ga.additionalAccountHitTypes.userId) { if (commandClone[2] && typeof commandClone[2] === 'object') { delete commandClone[2].userId; } } angular.forEach($analyticsProvider.settings.ga.additionalAccountNames, function (accountName){ commandClone[0] = accountName + '.' + commandClone[0]; window[gaNamespace].apply(this, commandClone); }); } } /** * Dispatches a hit using Classic syntax * Translates Universal Syntax to Classic syntax * * @name dispatchToClassic_ * @private * * @param {string} command Standard Universal Analytics command (create, send, set) * @param {object} fieldsObj object with hit-specific fields. Fields are whitelisted in handler - non-supported fields are ignored. * @param {boolean} shouldCopyHit should hit be propogated to all trackers */ function dispatchToClassic_(command, fieldsObj, shouldCopyHit) { if (command === 'set') { return console.log('Classic Analytics does not support the "set" command or Custom Dimensions. Command ignored.'); } var classicCommand; // Transpose our syntax from Universal Analytics to Classic Analytics // Currently we only support 'send' style commands if (command === 'send') { switch(fieldsObj.hitType) { case 'pageview': classicCommand = ['_trackPageview', fieldsObj.page]; break; case 'event': classicCommand = [ '_trackEvent', fieldsObj.category, fieldsObj.action, fieldsObj.label, fieldsObj.value, fieldsObj.nonInteraction ]; break; case 'timing': classicCommand = [ '_trackTiming', fieldsObj.timingCategory, fieldsObj.timingVar, fieldsObj.timingValue, fieldsObj.timingLabel, fieldsObj.optSampleRate ]; break; } } if (command === 'ecommerce:addTransaction') { classicCommand = [ '_addTrans', fieldsObj.id, fieldsObj.affiliation, fieldsObj.revenue, fieldsObj.tax, fieldsObj.shipping, fieldsObj.billingCity, fieldsObj.billingRegion, fieldsObj.billingCountry ]; } if (command === 'ecommerce:addItem') { classicCommand = [ '_addItem', fieldsObj.id, fieldsObj.sku, fieldsObj.name, fieldsObj.category, fieldsObj.price, fieldsObj.quantity ]; } if (command === '_set') { classicCommand = [ '_set', 'currencyCode', fieldsObj ]; } if (command === 'ecommerce:send') { classicCommand = [ '_trackTrans' ]; } if (!classicCommand) { return console.log('Unable to find command ' + command + ' or fieldsObj missing required properties. Command ignored.'); } // Issue our command to GA window._gaq.push(classicCommand); if (shouldCopyHit) { angular.forEach($analyticsProvider.settings.ga.additionalAccountNames, function (accountName){ var classicCommandClone = [].slice.call(classicCommand); // Namespace the command as required classicCommandClone[0] = accountName + '.' + classicCommandClone[0]; window._gaq.push(classicCommandClone); }); } } })(); }]); })(window, window.angular); /*! Papa Parse v4.3.6 https://github.com/mholt/PapaParse License: MIT */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); } else if (typeof module === 'object' && typeof exports !== 'undefined') { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) root.Papa = factory(); } }(this, function() { 'use strict'; var global = (function () { // alternative method, similar to `Function('return this')()` // but without using `eval` (which is disabled when // using Content Security Policy). if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } // When running tests none of the above have been defined return {}; })(); var IS_WORKER = !global.document && !!global.postMessage, IS_PAPA_WORKER = IS_WORKER && /(\?|&)papaworker(=|&|$)/.test(global.location.search), LOADED_SYNC = false, AUTO_SCRIPT_PATH; var workers = {}, workerIdCounter = 0; var Papa = {}; Papa.parse = CsvToJson; Papa.unparse = JsonToCsv; Papa.RECORD_SEP = String.fromCharCode(30); Papa.UNIT_SEP = String.fromCharCode(31); Papa.BYTE_ORDER_MARK = '\ufeff'; Papa.BAD_DELIMITERS = ['\r', '\n', '"', Papa.BYTE_ORDER_MARK]; Papa.WORKERS_SUPPORTED = !IS_WORKER && !!global.Worker; Papa.SCRIPT_PATH = null; // Must be set by your code if you use workers and this lib is loaded asynchronously // Configurable chunk sizes for local and remote files, respectively Papa.LocalChunkSize = 1024 * 1024 * 10; // 10 MB Papa.RemoteChunkSize = 1024 * 1024 * 5; // 5 MB Papa.DefaultDelimiter = ','; // Used if not specified and detection fails // Exposed for testing and development only Papa.Parser = Parser; Papa.ParserHandle = ParserHandle; Papa.NetworkStreamer = NetworkStreamer; Papa.FileStreamer = FileStreamer; Papa.StringStreamer = StringStreamer; Papa.ReadableStreamStreamer = ReadableStreamStreamer; if (global.jQuery) { var $ = global.jQuery; $.fn.parse = function(options) { var config = options.config || {}; var queue = []; this.each(function(idx) { var supported = $(this).prop('tagName').toUpperCase() === 'INPUT' && $(this).attr('type').toLowerCase() === 'file' && global.FileReader; if (!supported || !this.files || this.files.length === 0) return true; // continue to next input element for (var i = 0; i < this.files.length; i++) { queue.push({ file: this.files[i], inputElem: this, instanceConfig: $.extend({}, config) }); } }); parseNextFile(); // begin parsing return this; // maintains chainability function parseNextFile() { if (queue.length === 0) { if (isFunction(options.complete)) options.complete(); return; } var f = queue[0]; if (isFunction(options.before)) { var returned = options.before(f.file, f.inputElem); if (typeof returned === 'object') { if (returned.action === 'abort') { error('AbortError', f.file, f.inputElem, returned.reason); return; // Aborts all queued files immediately } else if (returned.action === 'skip') { fileComplete(); // parse the next file in the queue, if any return; } else if (typeof returned.config === 'object') f.instanceConfig = $.extend(f.instanceConfig, returned.config); } else if (returned === 'skip') { fileComplete(); // parse the next file in the queue, if any return; } } // Wrap up the user's complete callback, if any, so that ours also gets executed var userCompleteFunc = f.instanceConfig.complete; f.instanceConfig.complete = function(results) { if (isFunction(userCompleteFunc)) userCompleteFunc(results, f.file, f.inputElem); fileComplete(); }; Papa.parse(f.file, f.instanceConfig); } function error(name, file, elem, reason) { if (isFunction(options.error)) options.error({name: name}, file, elem, reason); } function fileComplete() { queue.splice(0, 1); parseNextFile(); } } } if (IS_PAPA_WORKER) { global.onmessage = workerThreadReceivedMessage; } else if (Papa.WORKERS_SUPPORTED) { AUTO_SCRIPT_PATH = getScriptPath(); // Check if the script was loaded synchronously if (!document.body) { // Body doesn't exist yet, must be synchronous LOADED_SYNC = true; } else { document.addEventListener('DOMContentLoaded', function () { LOADED_SYNC = true; }, true); } } function CsvToJson(_input, _config) { _config = _config || {}; var dynamicTyping = _config.dynamicTyping || false; if (isFunction(dynamicTyping)) { _config.dynamicTypingFunction = dynamicTyping; // Will be filled on first row call dynamicTyping = {}; } _config.dynamicTyping = dynamicTyping; if (_config.worker && Papa.WORKERS_SUPPORTED) { var w = newWorker(); w.userStep = _config.step; w.userChunk = _config.chunk; w.userComplete = _config.complete; w.userError = _config.error; _config.step = isFunction(_config.step); _config.chunk = isFunction(_config.chunk); _config.complete = isFunction(_config.complete); _config.error = isFunction(_config.error); delete _config.worker; // prevent infinite loop w.postMessage({ input: _input, config: _config, workerId: w.id }); return; } var streamer = null; if (typeof _input === 'string') { if (_config.download) streamer = new NetworkStreamer(_config); else streamer = new StringStreamer(_config); } else if (_input.readable === true && isFunction(_input.read) && isFunction(_input.on)) { streamer = new ReadableStreamStreamer(_config); } else if ((global.File && _input instanceof File) || _input instanceof Object) // ...Safari. (see issue #106) streamer = new FileStreamer(_config); return streamer.stream(_input); } function JsonToCsv(_input, _config) { var _output = ''; var _fields = []; // Default configuration /** whether to surround every datum with quotes */ var _quotes = false; /** whether to write headers */ var _writeHeader = true; /** delimiting character */ var _delimiter = ','; /** newline character(s) */ var _newline = '\r\n'; /** quote character */ var _quoteChar = '"'; unpackConfig(); var quoteCharRegex = new RegExp(_quoteChar, 'g'); if (typeof _input === 'string') _input = JSON.parse(_input); if (_input instanceof Array) { if (!_input.length || _input[0] instanceof Array) return serialize(null, _input); else if (typeof _input[0] === 'object') return serialize(objectKeys(_input[0]), _input); } else if (typeof _input === 'object') { if (typeof _input.data === 'string') _input.data = JSON.parse(_input.data); if (_input.data instanceof Array) { if (!_input.fields) _input.fields = _input.meta && _input.meta.fields; if (!_input.fields) _input.fields = _input.data[0] instanceof Array ? _input.fields : objectKeys(_input.data[0]); if (!(_input.data[0] instanceof Array) && typeof _input.data[0] !== 'object') _input.data = [_input.data]; // handles input like [1,2,3] or ['asdf'] } return serialize(_input.fields || [], _input.data || []); } // Default (any valid paths should return before this) throw 'exception: Unable to serialize unrecognized input'; function unpackConfig() { if (typeof _config !== 'object') return; if (typeof _config.delimiter === 'string' && _config.delimiter.length === 1 && Papa.BAD_DELIMITERS.indexOf(_config.delimiter) === -1) { _delimiter = _config.delimiter; } if (typeof _config.quotes === 'boolean' || _config.quotes instanceof Array) _quotes = _config.quotes; if (typeof _config.newline === 'string') _newline = _config.newline; if (typeof _config.quoteChar === 'string') _quoteChar = _config.quoteChar; if (typeof _config.header === 'boolean') _writeHeader = _config.header; } /** Turns an object's keys into an array */ function objectKeys(obj) { if (typeof obj !== 'object') return []; var keys = []; for (var key in obj) keys.push(key); return keys; } /** The double for loop that iterates the data and writes out a CSV string including header row */ function serialize(fields, data) { var csv = ''; if (typeof fields === 'string') fields = JSON.parse(fields); if (typeof data === 'string') data = JSON.parse(data); var hasHeader = fields instanceof Array && fields.length > 0; var dataKeyedByField = !(data[0] instanceof Array); // If there a header row, write it first if (hasHeader && _writeHeader) { for (var i = 0; i < fields.length; i++) { if (i > 0) csv += _delimiter; csv += safe(fields[i], i); } if (data.length > 0) csv += _newline; } // Then write out the data for (var row = 0; row < data.length; row++) { var maxCol = hasHeader ? fields.length : data[row].length; for (var col = 0; col < maxCol; col++) { if (col > 0) csv += _delimiter; var colIdx = hasHeader && dataKeyedByField ? fields[col] : col; csv += safe(data[row][colIdx], col); } if (row < data.length - 1) csv += _newline; } return csv; } /** Encloses a value around quotes if needed (makes a value safe for CSV insertion) */ function safe(str, col) { if (typeof str === 'undefined' || str === null) return ''; str = str.toString().replace(quoteCharRegex, _quoteChar+_quoteChar); var needsQuotes = (typeof _quotes === 'boolean' && _quotes) || (_quotes instanceof Array && _quotes[col]) || hasAny(str, Papa.BAD_DELIMITERS) || str.indexOf(_delimiter) > -1 || str.charAt(0) === ' ' || str.charAt(str.length - 1) === ' '; return needsQuotes ? _quoteChar + str + _quoteChar : str; } function hasAny(str, substrings) { for (var i = 0; i < substrings.length; i++) if (str.indexOf(substrings[i]) > -1) return true; return false; } } /** ChunkStreamer is the base prototype for various streamer implementations. */ function ChunkStreamer(config) { this._handle = null; this._paused = false; this._finished = false; this._input = null; this._baseIndex = 0; this._partialLine = ''; this._rowCount = 0; this._start = 0; this._nextChunk = null; this.isFirstChunk = true; this._completeResults = { data: [], errors: [], meta: {} }; replaceConfig.call(this, config); this.parseChunk = function(chunk) { // First chunk pre-processing if (this.isFirstChunk && isFunction(this._config.beforeFirstChunk)) { var modifiedChunk = this._config.beforeFirstChunk(chunk); if (modifiedChunk !== undefined) chunk = modifiedChunk; } this.isFirstChunk = false; // Rejoin the line we likely just split in two by chunking the file var aggregate = this._partialLine + chunk; this._partialLine = ''; var results = this._handle.parse(aggregate, this._baseIndex, !this._finished); if (this._handle.paused() || this._handle.aborted()) return; var lastIndex = results.meta.cursor; if (!this._finished) { this._partialLine = aggregate.substring(lastIndex - this._baseIndex); this._baseIndex = lastIndex; } if (results && results.data) this._rowCount += results.data.length; var finishedIncludingPreview = this._finished || (this._config.preview && this._rowCount >= this._config.preview); if (IS_PAPA_WORKER) { global.postMessage({ results: results, workerId: Papa.WORKER_ID, finished: finishedIncludingPreview }); } else if (isFunction(this._config.chunk)) { this._config.chunk(results, this._handle); if (this._paused) return; results = undefined; this._completeResults = undefined; } if (!this._config.step && !this._config.chunk) { this._completeResults.data = this._completeResults.data.concat(results.data); this._completeResults.errors = this._completeResults.errors.concat(results.errors); this._completeResults.meta = results.meta; } if (finishedIncludingPreview && isFunction(this._config.complete) && (!results || !results.meta.aborted)) this._config.complete(this._completeResults, this._input); if (!finishedIncludingPreview && (!results || !results.meta.paused)) this._nextChunk(); return results; }; this._sendError = function(error) { if (isFunction(this._config.error)) this._config.error(error); else if (IS_PAPA_WORKER && this._config.error) { global.postMessage({ workerId: Papa.WORKER_ID, error: error, finished: false }); } }; function replaceConfig(config) { // Deep-copy the config so we can edit it var configCopy = copy(config); configCopy.chunkSize = parseInt(configCopy.chunkSize); // parseInt VERY important so we don't concatenate strings! if (!config.step && !config.chunk) configCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196 this._handle = new ParserHandle(configCopy); this._handle.streamer = this; this._config = configCopy; // persist the copy to the caller } } function NetworkStreamer(config) { config = config || {}; if (!config.chunkSize) config.chunkSize = Papa.RemoteChunkSize; ChunkStreamer.call(this, config); var xhr; if (IS_WORKER) { this._nextChunk = function() { this._readChunk(); this._chunkLoaded(); }; } else { this._nextChunk = function() { this._readChunk(); }; } this.stream = function(url) { this._input = url; this._nextChunk(); // Starts streaming }; this._readChunk = function() { if (this._finished) { this._chunkLoaded(); return; } xhr = new XMLHttpRequest(); if (this._config.withCredentials) { xhr.withCredentials = this._config.withCredentials; } if (!IS_WORKER) { xhr.onload = bindFunction(this._chunkLoaded, this); xhr.onerror = bindFunction(this._chunkError, this); } xhr.open('GET', this._input, !IS_WORKER); // Headers can only be set when once the request state is OPENED if (this._config.downloadRequestHeaders) { var headers = this._config.downloadRequestHeaders; for (var headerName in headers) { xhr.setRequestHeader(headerName, headers[headerName]); } } if (this._config.chunkSize) { var end = this._start + this._config.chunkSize - 1; // minus one because byte range is inclusive xhr.setRequestHeader('Range', 'bytes='+this._start+'-'+end); xhr.setRequestHeader('If-None-Match', 'webkit-no-cache'); // https://bugs.webkit.org/show_bug.cgi?id=82672 } try { xhr.send(); } catch (err) { this._chunkError(err.message); } if (IS_WORKER && xhr.status === 0) this._chunkError(); else this._start += this._config.chunkSize; } this._chunkLoaded = function() { if (xhr.readyState != 4) return; if (xhr.status < 200 || xhr.status >= 400) { this._chunkError(); return; } this._finished = !this._config.chunkSize || this._start > getFileSize(xhr); this.parseChunk(xhr.responseText); } this._chunkError = function(errorMessage) { var errorText = xhr.statusText || errorMessage; this._sendError(errorText); } function getFileSize(xhr) { var contentRange = xhr.getResponseHeader('Content-Range'); if (contentRange === null) { // no content range, then finish! return -1; } return parseInt(contentRange.substr(contentRange.lastIndexOf('/') + 1)); } } NetworkStreamer.prototype = Object.create(ChunkStreamer.prototype); NetworkStreamer.prototype.constructor = NetworkStreamer; function FileStreamer(config) { config = config || {}; if (!config.chunkSize) config.chunkSize = Papa.LocalChunkSize; ChunkStreamer.call(this, config); var reader, slice; // FileReader is better than FileReaderSync (even in worker) - see http://stackoverflow.com/q/24708649/1048862 // But Firefox is a pill, too - see issue #76: https://github.com/mholt/PapaParse/issues/76 var usingAsyncReader = typeof FileReader !== 'undefined'; // Safari doesn't consider it a function - see issue #105 this.stream = function(file) { this._input = file; slice = file.slice || file.webkitSlice || file.mozSlice; if (usingAsyncReader) { reader = new FileReader(); // Preferred method of reading files, even in workers reader.onload = bindFunction(this._chunkLoaded, this); reader.onerror = bindFunction(this._chunkError, this); } else reader = new FileReaderSync(); // Hack for running in a web worker in Firefox this._nextChunk(); // Starts streaming }; this._nextChunk = function() { if (!this._finished && (!this._config.preview || this._rowCount < this._config.preview)) this._readChunk(); } this._readChunk = function() { var input = this._input; if (this._config.chunkSize) { var end = Math.min(this._start + this._config.chunkSize, this._input.size); input = slice.call(input, this._start, end); } var txt = reader.readAsText(input, this._config.encoding); if (!usingAsyncReader) this._chunkLoaded({ target: { result: txt } }); // mimic the async signature } this._chunkLoaded = function(event) { // Very important to increment start each time before handling results this._start += this._config.chunkSize; this._finished = !this._config.chunkSize || this._start >= this._input.size; this.parseChunk(event.target.result); } this._chunkError = function() { this._sendError(reader.error); } } FileStreamer.prototype = Object.create(ChunkStreamer.prototype); FileStreamer.prototype.constructor = FileStreamer; function StringStreamer(config) { config = config || {}; ChunkStreamer.call(this, config); var string; var remaining; this.stream = function(s) { string = s; remaining = s; return this._nextChunk(); } this._nextChunk = function() { if (this._finished) return; var size = this._config.chunkSize; var chunk = size ? remaining.substr(0, size) : remaining; remaining = size ? remaining.substr(size) : ''; this._finished = !remaining; return this.parseChunk(chunk); } } StringStreamer.prototype = Object.create(StringStreamer.prototype); StringStreamer.prototype.constructor = StringStreamer; function ReadableStreamStreamer(config) { config = config || {}; ChunkStreamer.call(this, config); var queue = []; var parseOnData = true; this.stream = function(stream) { this._input = stream; this._input.on('data', this._streamData); this._input.on('end', this._streamEnd); this._input.on('error', this._streamError); } this._nextChunk = function() { if (queue.length) { this.parseChunk(queue.shift()); } else { parseOnData = true; } } this._streamData = bindFunction(function(chunk) { try { queue.push(typeof chunk === 'string' ? chunk : chunk.toString(this._config.encoding)); if (parseOnData) { parseOnData = false; this.parseChunk(queue.shift()); } } catch (error) { this._streamError(error); } }, this); this._streamError = bindFunction(function(error) { this._streamCleanUp(); this._sendError(error.message); }, this); this._streamEnd = bindFunction(function() { this._streamCleanUp(); this._finished = true; this._streamData(''); }, this); this._streamCleanUp = bindFunction(function() { this._input.removeListener('data', this._streamData); this._input.removeListener('end', this._streamEnd); this._input.removeListener('error', this._streamError); }, this); } ReadableStreamStreamer.prototype = Object.create(ChunkStreamer.prototype); ReadableStreamStreamer.prototype.constructor = ReadableStreamStreamer; // Use one ParserHandle per entire CSV file or string function ParserHandle(_config) { // One goal is to minimize the use of regular expressions... var FLOAT = /^\s*-?(\d*\.?\d+|\d+\.?\d*)(e[-+]?\d+)?\s*$/i; var self = this; var _stepCounter = 0; // Number of times step was called (number of rows parsed) var _input; // The input being parsed var _parser; // The core parser being used var _paused = false; // Whether we are paused or not var _aborted = false; // Whether the parser has aborted or not var _delimiterError; // Temporary state between delimiter detection and processing results var _fields = []; // Fields are from the header row of the input, if there is one var _results = { // The last results returned from the parser data: [], errors: [], meta: {} }; if (isFunction(_config.step)) { var userStep = _config.step; _config.step = function(results) { _results = results; if (needsHeaderRow()) processResults(); else // only call user's step function after header row { processResults(); // It's possbile that this line was empty and there's no row here after all if (_results.data.length === 0) return; _stepCounter += results.data.length; if (_config.preview && _stepCounter > _config.preview) _parser.abort(); else userStep(_results, self); } }; } /** * Parses input. Most users won't need, and shouldn't mess with, the baseIndex * and ignoreLastRow parameters. They are used by streamers (wrapper functions) * when an input comes in multiple chunks, like from a file. */ this.parse = function(input, baseIndex, ignoreLastRow) { if (!_config.newline) _config.newline = guessLineEndings(input); _delimiterError = false; if (!_config.delimiter) { var delimGuess = guessDelimiter(input, _config.newline, _config.skipEmptyLines); if (delimGuess.successful) _config.delimiter = delimGuess.bestDelimiter; else { _delimiterError = true; // add error after parsing (otherwise it would be overwritten) _config.delimiter = Papa.DefaultDelimiter; } _results.meta.delimiter = _config.delimiter; } else if(isFunction(_config.delimiter)) { _config.delimiter = _config.delimiter(input); _results.meta.delimiter = _config.delimiter; } var parserConfig = copy(_config); if (_config.preview && _config.header) parserConfig.preview++; // to compensate for header row _input = input; _parser = new Parser(parserConfig); _results = _parser.parse(_input, baseIndex, ignoreLastRow); processResults(); return _paused ? { meta: { paused: true } } : (_results || { meta: { paused: false } }); }; this.paused = function() { return _paused; }; this.pause = function() { _paused = true; _parser.abort(); _input = _input.substr(_parser.getCharIndex()); }; this.resume = function() { _paused = false; self.streamer.parseChunk(_input); }; this.aborted = function () { return _aborted; }; this.abort = function() { _aborted = true; _parser.abort(); _results.meta.aborted = true; if (isFunction(_config.complete)) _config.complete(_results); _input = ''; }; function processResults() { if (_results && _delimiterError) { addError('Delimiter', 'UndetectableDelimiter', 'Unable to auto-detect delimiting character; defaulted to \''+Papa.DefaultDelimiter+'\''); _delimiterError = false; } if (_config.skipEmptyLines) { for (var i = 0; i < _results.data.length; i++) if (_results.data[i].length === 1 && _results.data[i][0] === '') _results.data.splice(i--, 1); } if (needsHeaderRow()) fillHeaderFields(); return applyHeaderAndDynamicTyping(); } function needsHeaderRow() { return _config.header && _fields.length === 0; } function fillHeaderFields() { if (!_results) return; for (var i = 0; needsHeaderRow() && i < _results.data.length; i++) for (var j = 0; j < _results.data[i].length; j++) _fields.push(_results.data[i][j]); _results.data.splice(0, 1); } function shouldApplyDynamicTyping(field) { // Cache function values to avoid calling it for each row if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) { _config.dynamicTyping[field] = _config.dynamicTypingFunction(field); } return (_config.dynamicTyping[field] || _config.dynamicTyping) === true } function parseDynamic(field, value) { if (shouldApplyDynamicTyping(field)) { if (value === 'true' || value === 'TRUE') return true; else if (value === 'false' || value === 'FALSE') return false; else return tryParseFloat(value); } return value; } function applyHeaderAndDynamicTyping() { if (!_results || (!_config.header && !_config.dynamicTyping)) return _results; for (var i = 0; i < _results.data.length; i++) { var row = _config.header ? {} : []; for (var j = 0; j < _results.data[i].length; j++) { var field = j; var value = _results.data[i][j]; if (_config.header) field = j >= _fields.length ? '__parsed_extra' : _fields[j]; value = parseDynamic(field, value); if (field === '__parsed_extra') { row[field] = row[field] || []; row[field].push(value); } else row[field] = value; } _results.data[i] = row; if (_config.header) { if (j > _fields.length) addError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, i); else if (j < _fields.length) addError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, i); } } if (_config.header && _results.meta) _results.meta.fields = _fields; return _results; } function guessDelimiter(input, newline, skipEmptyLines) { var delimChoices = [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP]; var bestDelim, bestDelta, fieldCountPrevRow; for (var i = 0; i < delimChoices.length; i++) { var delim = delimChoices[i]; var delta = 0, avgFieldCount = 0, emptyLinesCount = 0; fieldCountPrevRow = undefined; var preview = new Parser({ delimiter: delim, newline: newline, preview: 10 }).parse(input); for (var j = 0; j < preview.data.length; j++) { if (skipEmptyLines && preview.data[j].length === 1 && preview.data[j][0].length === 0) { emptyLinesCount++ continue } var fieldCount = preview.data[j].length; avgFieldCount += fieldCount; if (typeof fieldCountPrevRow === 'undefined') { fieldCountPrevRow = fieldCount; continue; } else if (fieldCount > 1) { delta += Math.abs(fieldCount - fieldCountPrevRow); fieldCountPrevRow = fieldCount; } } if (preview.data.length > 0) avgFieldCount /= (preview.data.length - emptyLinesCount); if ((typeof bestDelta === 'undefined' || delta < bestDelta) && avgFieldCount > 1.99) { bestDelta = delta; bestDelim = delim; } } _config.delimiter = bestDelim; return { successful: !!bestDelim, bestDelimiter: bestDelim } } function guessLineEndings(input) { input = input.substr(0, 1024*1024); // max length 1 MB var r = input.split('\r'); var n = input.split('\n'); var nAppearsFirst = (n.length > 1 && n[0].length < r[0].length); if (r.length === 1 || nAppearsFirst) return '\n'; var numWithN = 0; for (var i = 0; i < r.length; i++) { if (r[i][0] === '\n') numWithN++; } return numWithN >= r.length / 2 ? '\r\n' : '\r'; } function tryParseFloat(val) { var isNumber = FLOAT.test(val); return isNumber ? parseFloat(val) : val; } function addError(type, code, msg, row) { _results.errors.push({ type: type, code: code, message: msg, row: row }); } } /** The core parser implements speedy and correct CSV parsing */ function Parser(config) { // Unpack the config object config = config || {}; var delim = config.delimiter; var newline = config.newline; var comments = config.comments; var step = config.step; var preview = config.preview; var fastMode = config.fastMode; var quoteChar = config.quoteChar || '"'; // Delimiter must be valid if (typeof delim !== 'string' || Papa.BAD_DELIMITERS.indexOf(delim) > -1) delim = ','; // Comment character must be valid if (comments === delim) throw 'Comment character same as delimiter'; else if (comments === true) comments = '#'; else if (typeof comments !== 'string' || Papa.BAD_DELIMITERS.indexOf(comments) > -1) comments = false; // Newline must be valid: \r, \n, or \r\n if (newline != '\n' && newline != '\r' && newline != '\r\n') newline = '\n'; // We're gonna need these at the Parser scope var cursor = 0; var aborted = false; this.parse = function(input, baseIndex, ignoreLastRow) { // For some reason, in Chrome, this speeds things up (!?) if (typeof input !== 'string') throw 'Input must be a string'; // We don't need to compute some of these every time parse() is called, // but having them in a more local scope seems to perform better var inputLen = input.length, delimLen = delim.length, newlineLen = newline.length, commentsLen = comments.length; var stepIsFunction = isFunction(step); // Establish starting state cursor = 0; var data = [], errors = [], row = [], lastCursor = 0; if (!input) return returnable(); if (fastMode || (fastMode !== false && input.indexOf(quoteChar) === -1)) { var rows = input.split(newline); for (var i = 0; i < rows.length; i++) { var row = rows[i]; cursor += row.length; if (i !== rows.length - 1) cursor += newline.length; else if (ignoreLastRow) return returnable(); if (comments && row.substr(0, commentsLen) === comments) continue; if (stepIsFunction) { data = []; pushRow(row.split(delim)); doStep(); if (aborted) return returnable(); } else pushRow(row.split(delim)); if (preview && i >= preview) { data = data.slice(0, preview); return returnable(true); } } return returnable(); } var nextDelim = input.indexOf(delim, cursor); var nextNewline = input.indexOf(newline, cursor); var quoteCharRegex = new RegExp(quoteChar+quoteChar, 'g'); // Parser loop for (;;) { // Field has opening quote if (input[cursor] === quoteChar) { // Start our search for the closing quote where the cursor is var quoteSearch = cursor; // Skip the opening quote cursor++; for (;;) { // Find closing quote var quoteSearch = input.indexOf(quoteChar, quoteSearch+1); //No other quotes are found - no other delimiters if (quoteSearch === -1) { if (!ignoreLastRow) { // No closing quote... what a pity errors.push({ type: 'Quotes', code: 'MissingQuotes', message: 'Quoted field unterminated', row: data.length, // row has yet to be inserted index: cursor }); } return finish(); } // Closing quote at EOF if (quoteSearch === inputLen-1) { var value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar); return finish(value); } // If this quote is escaped, it's part of the data; skip it if (input[quoteSearch+1] === quoteChar) { quoteSearch++; continue; } // Closing quote followed by delimiter if (input[quoteSearch+1] === delim) { row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); cursor = quoteSearch + 1 + delimLen; nextDelim = input.indexOf(delim, cursor); nextNewline = input.indexOf(newline, cursor); break; } // Closing quote followed by newline if (input.substr(quoteSearch+1, newlineLen) === newline) { row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); saveRow(quoteSearch + 1 + newlineLen); nextDelim = input.indexOf(delim, cursor); // because we may have skipped the nextDelim in the quoted field if (stepIsFunction) { doStep(); if (aborted) return returnable(); } if (preview && data.length >= preview) return returnable(true); break; } // Checks for valid closing quotes are complete (escaped quotes or quote followed by EOF/delimiter/newline) -- assume these quotes are part of an invalid text string errors.push({ type: 'Quotes', code: 'InvalidQuotes', message: 'Trailing quote on quoted field is malformed', row: data.length, // row has yet to be inserted index: cursor }); quoteSearch++; continue; } continue; } // Comment found at start of new line if (comments && row.length === 0 && input.substr(cursor, commentsLen) === comments) { if (nextNewline === -1) // Comment ends at EOF return returnable(); cursor = nextNewline + newlineLen; nextNewline = input.indexOf(newline, cursor); nextDelim = input.indexOf(delim, cursor); continue; } // Next delimiter comes before next newline, so we've reached end of field if (nextDelim !== -1 && (nextDelim < nextNewline || nextNewline === -1)) { row.push(input.substring(cursor, nextDelim)); cursor = nextDelim + delimLen; nextDelim = input.indexOf(delim, cursor); continue; } // End of row if (nextNewline !== -1) { row.push(input.substring(cursor, nextNewline)); saveRow(nextNewline + newlineLen); if (stepIsFunction) { doStep(); if (aborted) return returnable(); } if (preview && data.length >= preview) return returnable(true); continue; } break; } return finish(); function pushRow(row) { data.push(row); lastCursor = cursor; } /** * Appends the remaining input from cursor to the end into * row, saves the row, calls step, and returns the results. */ function finish(value) { if (ignoreLastRow) return returnable(); if (typeof value === 'undefined') value = input.substr(cursor); row.push(value); cursor = inputLen; // important in case parsing is paused pushRow(row); if (stepIsFunction) doStep(); return returnable(); } /** * Appends the current row to the results. It sets the cursor * to newCursor and finds the nextNewline. The caller should * take care to execute user's step function and check for * preview and end parsing if necessary. */ function saveRow(newCursor) { cursor = newCursor; pushRow(row); row = []; nextNewline = input.indexOf(newline, cursor); } /** Returns an object with the results, errors, and meta. */ function returnable(stopped) { return { data: data, errors: errors, meta: { delimiter: delim, linebreak: newline, aborted: aborted, truncated: !!stopped, cursor: lastCursor + (baseIndex || 0) } }; } /** Executes the user's step function and resets data & errors. */ function doStep() { step(returnable()); data = [], errors = []; } }; /** Sets the abort flag */ this.abort = function() { aborted = true; }; /** Gets the cursor position */ this.getCharIndex = function() { return cursor; }; } // If you need to load Papa Parse asynchronously and you also need worker threads, hard-code // the script path here. See: https://github.com/mholt/PapaParse/issues/87#issuecomment-57885358 function getScriptPath() { var scripts = document.getElementsByTagName('script'); return scripts.length ? scripts[scripts.length - 1].src : ''; } function newWorker() { if (!Papa.WORKERS_SUPPORTED) return false; if (!LOADED_SYNC && Papa.SCRIPT_PATH === null) throw new Error( 'Script path cannot be determined automatically when Papa Parse is loaded asynchronously. ' + 'You need to set Papa.SCRIPT_PATH manually.' ); var workerUrl = Papa.SCRIPT_PATH || AUTO_SCRIPT_PATH; // Append 'papaworker' to the search string to tell papaparse that this is our worker. workerUrl += (workerUrl.indexOf('?') !== -1 ? '&' : '?') + 'papaworker'; var w = new global.Worker(workerUrl); w.onmessage = mainThreadReceivedMessage; w.id = workerIdCounter++; workers[w.id] = w; return w; } /** Callback when main thread receives a message */ function mainThreadReceivedMessage(e) { var msg = e.data; var worker = workers[msg.workerId]; var aborted = false; if (msg.error) worker.userError(msg.error, msg.file); else if (msg.results && msg.results.data) { var abort = function() { aborted = true; completeWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } }); }; var handle = { abort: abort, pause: notImplemented, resume: notImplemented }; if (isFunction(worker.userStep)) { for (var i = 0; i < msg.results.data.length; i++) { worker.userStep({ data: [msg.results.data[i]], errors: msg.results.errors, meta: msg.results.meta }, handle); if (aborted) break; } delete msg.results; // free memory ASAP } else if (isFunction(worker.userChunk)) { worker.userChunk(msg.results, handle, msg.file); delete msg.results; } } if (msg.finished && !aborted) completeWorker(msg.workerId, msg.results); } function completeWorker(workerId, results) { var worker = workers[workerId]; if (isFunction(worker.userComplete)) worker.userComplete(results); worker.terminate(); delete workers[workerId]; } function notImplemented() { throw 'Not implemented.'; } /** Callback when worker thread receives a message */ function workerThreadReceivedMessage(e) { var msg = e.data; if (typeof Papa.WORKER_ID === 'undefined' && msg) Papa.WORKER_ID = msg.workerId; if (typeof msg.input === 'string') { global.postMessage({ workerId: Papa.WORKER_ID, results: Papa.parse(msg.input, msg.config), finished: true }); } else if ((global.File && msg.input instanceof File) || msg.input instanceof Object) // thank you, Safari (see issue #106) { var results = Papa.parse(msg.input, msg.config); if (results) global.postMessage({ workerId: Papa.WORKER_ID, results: results, finished: true }); } } /** Makes a deep copy of an array or object (mostly) */ function copy(obj) { if (typeof obj !== 'object') return obj; var cpy = obj instanceof Array ? [] : {}; for (var key in obj) cpy[key] = copy(obj[key]); return cpy; } function bindFunction(f, self) { return function() { f.apply(self, arguments); }; } function isFunction(func) { return typeof func === 'function'; } return Papa; })); (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(['angular'], factory); } else if (root.hasOwnProperty('angular')) { // Browser globals (root is window), we don't register it. factory(root.angular); } else if (typeof exports === 'object') { module.exports = factory(require('angular')); } }(this , function (angular) { 'use strict'; // In cases where Angular does not get passed or angular is a truthy value // but misses .module we can fall back to using window. angular = (angular && angular.module ) ? angular : window.angular; function isStorageSupported($window, storageType) { // Some installations of IE, for an unknown reason, throw "SCRIPT5: Error: Access is denied" // when accessing window.localStorage. This happens before you try to do anything with it. Catch // that error and allow execution to continue. // fix 'SecurityError: DOM Exception 18' exception in Desktop Safari, Mobile Safari // when "Block cookies": "Always block" is turned on var supported; try { supported = $window[storageType]; } catch(err) { supported = false; } // When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage and sessionStorage // is available, but trying to call .setItem throws an exception below: // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota." if(supported) { var key = '__' + Math.round(Math.random() * 1e7); try { $window[storageType].setItem(key, key); $window[storageType].removeItem(key, key); } catch(err) { supported = false; } } return supported; } /** * @ngdoc overview * @name ngStorage */ return angular.module('ngStorage', []) /** * @ngdoc object * @name ngStorage.$localStorage * @requires $rootScope * @requires $window */ .provider('$localStorage', _storageProvider('localStorage')) /** * @ngdoc object * @name ngStorage.$sessionStorage * @requires $rootScope * @requires $window */ .provider('$sessionStorage', _storageProvider('sessionStorage')); function _storageProvider(storageType) { var providerWebStorage = isStorageSupported(window, storageType); return function () { var storageKeyPrefix = 'ngStorage-'; this.setKeyPrefix = function (prefix) { if (typeof prefix !== 'string') { throw new TypeError('[ngStorage] - ' + storageType + 'Provider.setKeyPrefix() expects a String.'); } storageKeyPrefix = prefix; }; var serializer = angular.toJson; var deserializer = angular.fromJson; this.setSerializer = function (s) { if (typeof s !== 'function') { throw new TypeError('[ngStorage] - ' + storageType + 'Provider.setSerializer expects a function.'); } serializer = s; }; this.setDeserializer = function (d) { if (typeof d !== 'function') { throw new TypeError('[ngStorage] - ' + storageType + 'Provider.setDeserializer expects a function.'); } deserializer = d; }; this.supported = function() { return !!providerWebStorage; }; // Note: This is not very elegant at all. this.get = function (key) { return providerWebStorage && deserializer(providerWebStorage.getItem(storageKeyPrefix + key)); }; // Note: This is not very elegant at all. this.set = function (key, value) { return providerWebStorage && providerWebStorage.setItem(storageKeyPrefix + key, serializer(value)); }; this.remove = function (key) { providerWebStorage && providerWebStorage.removeItem(storageKeyPrefix + key); } this.$get = [ '$rootScope', '$window', '$log', '$timeout', '$document', function( $rootScope, $window, $log, $timeout, $document ){ // The magic number 10 is used which only works for some keyPrefixes... // See https://github.com/gsklee/ngStorage/issues/137 var prefixLength = storageKeyPrefix.length; // #9: Assign a placeholder object if Web Storage is unavailable to prevent breaking the entire AngularJS app // Note: recheck mainly for testing (so we can use $window[storageType] rather than window[storageType]) var isSupported = isStorageSupported($window, storageType), webStorage = isSupported || ($log.warn('This browser does not support Web Storage!'), {setItem: angular.noop, getItem: angular.noop, removeItem: angular.noop}), $storage = { $default: function(items) { for (var k in items) { angular.isDefined($storage[k]) || ($storage[k] = angular.copy(items[k]) ); } $storage.$sync(); return $storage; }, $reset: function(items) { for (var k in $storage) { '$' === k[0] || (delete $storage[k] && webStorage.removeItem(storageKeyPrefix + k)); } return $storage.$default(items); }, $sync: function () { for (var i = 0, l = webStorage.length, k; i < l; i++) { // #8, #10: `webStorage.key(i)` may be an empty string (or throw an exception in IE9 if `webStorage` is empty) (k = webStorage.key(i)) && storageKeyPrefix === k.slice(0, prefixLength) && ($storage[k.slice(prefixLength)] = deserializer(webStorage.getItem(k))); } }, $apply: function() { var temp$storage; _debounce = null; if (!angular.equals($storage, _last$storage)) { temp$storage = angular.copy(_last$storage); angular.forEach($storage, function(v, k) { if (angular.isDefined(v) && '$' !== k[0]) { webStorage.setItem(storageKeyPrefix + k, serializer(v)); delete temp$storage[k]; } }); for (var k in temp$storage) { webStorage.removeItem(storageKeyPrefix + k); } _last$storage = angular.copy($storage); } }, $supported: function() { return !!isSupported; } }, _last$storage, _debounce; $storage.$sync(); _last$storage = angular.copy($storage); $rootScope.$watch(function() { _debounce || (_debounce = $timeout($storage.$apply, 100, false)); }); // #6: Use `$window.addEventListener` instead of `angular.element` to avoid the jQuery-specific `event.originalEvent` $window.addEventListener && $window.addEventListener('storage', function(event) { if (!event.key) { return; } // Reference doc. var doc = $document[0]; if ( (!doc.hasFocus || !doc.hasFocus()) && storageKeyPrefix === event.key.slice(0, prefixLength) ) { event.newValue ? $storage[event.key.slice(prefixLength)] = deserializer(event.newValue) : delete $storage[event.key.slice(prefixLength)]; _last$storage = angular.copy($storage); $rootScope.$apply(); } }); $window.addEventListener && $window.addEventListener('beforeunload', function() { $storage.$apply(); }); return $storage; } ]; }; } })); /*! * clipboard.js v1.7.1 * https://zenorocha.github.io/clipboard.js * * Licensed MIT © Zeno Rocha */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Clipboard = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0 && arguments[0] !== undefined ? arguments[0] : {}; this.action = options.action; this.container = options.container; this.emitter = options.emitter; this.target = options.target; this.text = options.text; this.trigger = options.trigger; this.selectedText = ''; } }, { key: 'initSelection', value: function initSelection() { if (this.text) { this.selectFake(); } else if (this.target) { this.selectTarget(); } } }, { key: 'selectFake', value: function selectFake() { var _this = this; var isRTL = document.documentElement.getAttribute('dir') == 'rtl'; this.removeFake(); this.fakeHandlerCallback = function () { return _this.removeFake(); }; this.fakeHandler = this.container.addEventListener('click', this.fakeHandlerCallback) || true; this.fakeElem = document.createElement('textarea'); // Prevent zooming on iOS this.fakeElem.style.fontSize = '12pt'; // Reset box model this.fakeElem.style.border = '0'; this.fakeElem.style.padding = '0'; this.fakeElem.style.margin = '0'; // Move element out of screen horizontally this.fakeElem.style.position = 'absolute'; this.fakeElem.style[isRTL ? 'right' : 'left'] = '-9999px'; // Move element to the same position vertically var yPosition = window.pageYOffset || document.documentElement.scrollTop; this.fakeElem.style.top = yPosition + 'px'; this.fakeElem.setAttribute('readonly', ''); this.fakeElem.value = this.text; this.container.appendChild(this.fakeElem); this.selectedText = (0, _select2.default)(this.fakeElem); this.copyText(); } }, { key: 'removeFake', value: function removeFake() { if (this.fakeHandler) { this.container.removeEventListener('click', this.fakeHandlerCallback); this.fakeHandler = null; this.fakeHandlerCallback = null; } if (this.fakeElem) { this.container.removeChild(this.fakeElem); this.fakeElem = null; } } }, { key: 'selectTarget', value: function selectTarget() { this.selectedText = (0, _select2.default)(this.target); this.copyText(); } }, { key: 'copyText', value: function copyText() { var succeeded = void 0; try { succeeded = document.execCommand(this.action); } catch (err) { succeeded = false; } this.handleResult(succeeded); } }, { key: 'handleResult', value: function handleResult(succeeded) { this.emitter.emit(succeeded ? 'success' : 'error', { action: this.action, text: this.selectedText, trigger: this.trigger, clearSelection: this.clearSelection.bind(this) }); } }, { key: 'clearSelection', value: function clearSelection() { if (this.trigger) { this.trigger.focus(); } window.getSelection().removeAllRanges(); } }, { key: 'destroy', value: function destroy() { this.removeFake(); } }, { key: 'action', set: function set() { var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'copy'; this._action = action; if (this._action !== 'copy' && this._action !== 'cut') { throw new Error('Invalid "action" value, use either "copy" or "cut"'); } }, get: function get() { return this._action; } }, { key: 'target', set: function set(target) { if (target !== undefined) { if (target && (typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object' && target.nodeType === 1) { if (this.action === 'copy' && target.hasAttribute('disabled')) { throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute'); } if (this.action === 'cut' && (target.hasAttribute('readonly') || target.hasAttribute('disabled'))) { throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes'); } this._target = target; } else { throw new Error('Invalid "target" value, use a valid Element'); } } }, get: function get() { return this._target; } }]); return ClipboardAction; }(); module.exports = ClipboardAction; }); },{"select":5}],8:[function(require,module,exports){ (function (global, factory) { if (typeof define === "function" && define.amd) { define(['module', './clipboard-action', 'tiny-emitter', 'good-listener'], factory); } else if (typeof exports !== "undefined") { factory(module, require('./clipboard-action'), require('tiny-emitter'), require('good-listener')); } else { var mod = { exports: {} }; factory(mod, global.clipboardAction, global.tinyEmitter, global.goodListener); global.clipboard = mod.exports; } })(this, function (module, _clipboardAction, _tinyEmitter, _goodListener) { 'use strict'; var _clipboardAction2 = _interopRequireDefault(_clipboardAction); var _tinyEmitter2 = _interopRequireDefault(_tinyEmitter); var _goodListener2 = _interopRequireDefault(_goodListener); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Clipboard = function (_Emitter) { _inherits(Clipboard, _Emitter); /** * @param {String|HTMLElement|HTMLCollection|NodeList} trigger * @param {Object} options */ function Clipboard(trigger, options) { _classCallCheck(this, Clipboard); var _this = _possibleConstructorReturn(this, (Clipboard.__proto__ || Object.getPrototypeOf(Clipboard)).call(this)); _this.resolveOptions(options); _this.listenClick(trigger); return _this; } /** * Defines if attributes would be resolved using internal setter functions * or custom functions that were passed in the constructor. * @param {Object} options */ _createClass(Clipboard, [{ key: 'resolveOptions', value: function resolveOptions() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.action = typeof options.action === 'function' ? options.action : this.defaultAction; this.target = typeof options.target === 'function' ? options.target : this.defaultTarget; this.text = typeof options.text === 'function' ? options.text : this.defaultText; this.container = _typeof(options.container) === 'object' ? options.container : document.body; } }, { key: 'listenClick', value: function listenClick(trigger) { var _this2 = this; this.listener = (0, _goodListener2.default)(trigger, 'click', function (e) { return _this2.onClick(e); }); } }, { key: 'onClick', value: function onClick(e) { var trigger = e.delegateTarget || e.currentTarget; if (this.clipboardAction) { this.clipboardAction = null; } this.clipboardAction = new _clipboardAction2.default({ action: this.action(trigger), target: this.target(trigger), text: this.text(trigger), container: this.container, trigger: trigger, emitter: this }); } }, { key: 'defaultAction', value: function defaultAction(trigger) { return getAttributeValue('action', trigger); } }, { key: 'defaultTarget', value: function defaultTarget(trigger) { var selector = getAttributeValue('target', trigger); if (selector) { return document.querySelector(selector); } } }, { key: 'defaultText', value: function defaultText(trigger) { return getAttributeValue('text', trigger); } }, { key: 'destroy', value: function destroy() { this.listener.destroy(); if (this.clipboardAction) { this.clipboardAction.destroy(); this.clipboardAction = null; } } }], [{ key: 'isSupported', value: function isSupported() { var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['copy', 'cut']; var actions = typeof action === 'string' ? [action] : action; var support = !!document.queryCommandSupported; actions.forEach(function (action) { support = support && !!document.queryCommandSupported(action); }); return support; } }]); return Clipboard; }(_tinyEmitter2.default); /** * Helper function to retrieve attribute value. * @param {String} suffix * @param {Element} element */ function getAttributeValue(suffix, element) { var attribute = 'data-clipboard-' + suffix; if (!element.hasAttribute(attribute)) { return; } return element.getAttribute(attribute); } module.exports = Clipboard; }); },{"./clipboard-action":7,"good-listener":4,"tiny-emitter":6}]},{},[8])(8) }); (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["forge"] = factory(); else root["forge"] = factory(); })(typeof self !== 'undefined' ? self : 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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = 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; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 10); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { /** * Node.js module for Forge. * * @author Dave Longley * * Copyright 2011-2016 Digital Bazaar, Inc. */ module.exports = { // default options options: { usePureJavaScript: false } }; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { /** * Utility functions for web applications. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. */ var forge = __webpack_require__(0); /* Utilities API */ var util = module.exports = forge.util = forge.util || {}; // define setImmediate and nextTick (function() { // use native nextTick if(typeof process !== 'undefined' && process.nextTick) { util.nextTick = process.nextTick; if(typeof setImmediate === 'function') { util.setImmediate = setImmediate; } else { // polyfill setImmediate with nextTick, older versions of node // (those w/o setImmediate) won't totally starve IO util.setImmediate = util.nextTick; } return; } // polyfill nextTick with native setImmediate if(typeof setImmediate === 'function') { util.setImmediate = function() { return setImmediate.apply(undefined, arguments); }; util.nextTick = function(callback) { return setImmediate(callback); }; return; } /* Note: A polyfill upgrade pattern is used here to allow combining polyfills. For example, MutationObserver is fast, but blocks UI updates, so it needs to allow UI updates periodically, so it falls back on postMessage or setTimeout. */ // polyfill with setTimeout util.setImmediate = function(callback) { setTimeout(callback, 0); }; // upgrade polyfill to use postMessage if(typeof window !== 'undefined' && typeof window.postMessage === 'function') { var msg = 'forge.setImmediate'; var callbacks = []; util.setImmediate = function(callback) { callbacks.push(callback); // only send message when one hasn't been sent in // the current turn of the event loop if(callbacks.length === 1) { window.postMessage(msg, '*'); } }; function handler(event) { if(event.source === window && event.data === msg) { event.stopPropagation(); var copy = callbacks.slice(); callbacks.length = 0; copy.forEach(function(callback) { callback(); }); } } window.addEventListener('message', handler, true); } // upgrade polyfill to use MutationObserver if(typeof MutationObserver !== 'undefined') { // polyfill with MutationObserver var now = Date.now(); var attr = true; var div = document.createElement('div'); var callbacks = []; new MutationObserver(function() { var copy = callbacks.slice(); callbacks.length = 0; copy.forEach(function(callback) { callback(); }); }).observe(div, {attributes: true}); var oldSetImmediate = util.setImmediate; util.setImmediate = function(callback) { if(Date.now() - now > 15) { now = Date.now(); oldSetImmediate(callback); } else { callbacks.push(callback); // only trigger observer when it hasn't been triggered in // the current turn of the event loop if(callbacks.length === 1) { div.setAttribute('a', attr = !attr); } } }; } util.nextTick = util.setImmediate; })(); // check if running under Node.js util.isNodejs = typeof process !== 'undefined' && process.versions && process.versions.node; // define isArray util.isArray = Array.isArray || function(x) { return Object.prototype.toString.call(x) === '[object Array]'; }; // define isArrayBuffer util.isArrayBuffer = function(x) { return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer; }; // define isArrayBufferView util.isArrayBufferView = function(x) { return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined; }; /** * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for * algorithms where bit manipulation, JavaScript limitations, and/or algorithm * design only allow for byte operations of a limited size. * * @param n number of bits. * * Throw Error if n invalid. */ function _checkBitsParam(n) { if(!(n === 8 || n === 16 || n === 24 || n === 32)) { throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n); } } // TODO: set ByteBuffer to best available backing util.ByteBuffer = ByteStringBuffer; /** Buffer w/BinaryString backing */ /** * Constructor for a binary string backed byte buffer. * * @param [b] the bytes to wrap (either encoded as string, one byte per * character, or as an ArrayBuffer or Typed Array). */ function ByteStringBuffer(b) { // TODO: update to match DataBuffer API // the data in this buffer this.data = ''; // the pointer for reading from this buffer this.read = 0; if(typeof b === 'string') { this.data = b; } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) { // convert native buffer to forge buffer // FIXME: support native buffers internally instead var arr = new Uint8Array(b); try { this.data = String.fromCharCode.apply(null, arr); } catch(e) { for(var i = 0; i < arr.length; ++i) { this.putByte(arr[i]); } } } else if(b instanceof ByteStringBuffer || (typeof b === 'object' && typeof b.data === 'string' && typeof b.read === 'number')) { // copy existing buffer this.data = b.data; this.read = b.read; } // used for v8 optimization this._constructedStringLength = 0; } util.ByteStringBuffer = ByteStringBuffer; /* Note: This is an optimization for V8-based browsers. When V8 concatenates a string, the strings are only joined logically using a "cons string" or "constructed/concatenated string". These containers keep references to one another and can result in very large memory usage. For example, if a 2MB string is constructed by concatenating 4 bytes together at a time, the memory usage will be ~44MB; so ~22x increase. The strings are only joined together when an operation requiring their joining takes place, such as substr(). This function is called when adding data to this buffer to ensure these types of strings are periodically joined to reduce the memory footprint. */ var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { this._constructedStringLength += x; if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { // this substr() should cause the constructed string to join this.data.substr(0, 1); this._constructedStringLength = 0; } }; /** * Gets the number of bytes in this buffer. * * @return the number of bytes in this buffer. */ util.ByteStringBuffer.prototype.length = function() { return this.data.length - this.read; }; /** * Gets whether or not this buffer is empty. * * @return true if this buffer is empty, false if not. */ util.ByteStringBuffer.prototype.isEmpty = function() { return this.length() <= 0; }; /** * Puts a byte in this buffer. * * @param b the byte to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.putByte = function(b) { return this.putBytes(String.fromCharCode(b)); }; /** * Puts a byte in this buffer N times. * * @param b the byte to put. * @param n the number of bytes of value b to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { b = String.fromCharCode(b); var d = this.data; while(n > 0) { if(n & 1) { d += b; } n >>>= 1; if(n > 0) { b += b; } } this.data = d; this._optimizeConstructedString(n); return this; }; /** * Puts bytes in this buffer. * * @param bytes the bytes (as a UTF-8 encoded string) to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.putBytes = function(bytes) { this.data += bytes; this._optimizeConstructedString(bytes.length); return this; }; /** * Puts a UTF-16 encoded string into this buffer. * * @param str the string to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.putString = function(str) { return this.putBytes(util.encodeUtf8(str)); }; /** * Puts a 16-bit integer in this buffer in big-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt16 = function(i) { return this.putBytes( String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; /** * Puts a 24-bit integer in this buffer in big-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt24 = function(i) { return this.putBytes( String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; /** * Puts a 32-bit integer in this buffer in big-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt32 = function(i) { return this.putBytes( String.fromCharCode(i >> 24 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; /** * Puts a 16-bit integer in this buffer in little-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt16Le = function(i) { return this.putBytes( String.fromCharCode(i & 0xFF) + String.fromCharCode(i >> 8 & 0xFF)); }; /** * Puts a 24-bit integer in this buffer in little-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt24Le = function(i) { return this.putBytes( String.fromCharCode(i & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF)); }; /** * Puts a 32-bit integer in this buffer in little-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt32Le = function(i) { return this.putBytes( String.fromCharCode(i & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 24 & 0xFF)); }; /** * Puts an n-bit integer in this buffer in big-endian order. * * @param i the n-bit integer. * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt = function(i, n) { _checkBitsParam(n); var bytes = ''; do { n -= 8; bytes += String.fromCharCode((i >> n) & 0xFF); } while(n > 0); return this.putBytes(bytes); }; /** * Puts a signed n-bit integer in this buffer in big-endian order. Two's * complement representation is used. * * @param i the n-bit integer. * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return this buffer. */ util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { // putInt checks n if(i < 0) { i += 2 << (n - 1); } return this.putInt(i, n); }; /** * Puts the given buffer into this buffer. * * @param buffer the buffer to put into this one. * * @return this buffer. */ util.ByteStringBuffer.prototype.putBuffer = function(buffer) { return this.putBytes(buffer.getBytes()); }; /** * Gets a byte from this buffer and advances the read pointer by 1. * * @return the byte. */ util.ByteStringBuffer.prototype.getByte = function() { return this.data.charCodeAt(this.read++); }; /** * Gets a uint16 from this buffer in big-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.ByteStringBuffer.prototype.getInt16 = function() { var rval = ( this.data.charCodeAt(this.read) << 8 ^ this.data.charCodeAt(this.read + 1)); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in big-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.ByteStringBuffer.prototype.getInt24 = function() { var rval = ( this.data.charCodeAt(this.read) << 16 ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2)); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in big-endian order and advances the read * pointer by 4. * * @return the word. */ util.ByteStringBuffer.prototype.getInt32 = function() { var rval = ( this.data.charCodeAt(this.read) << 24 ^ this.data.charCodeAt(this.read + 1) << 16 ^ this.data.charCodeAt(this.read + 2) << 8 ^ this.data.charCodeAt(this.read + 3)); this.read += 4; return rval; }; /** * Gets a uint16 from this buffer in little-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.ByteStringBuffer.prototype.getInt16Le = function() { var rval = ( this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in little-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.ByteStringBuffer.prototype.getInt24Le = function() { var rval = ( this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in little-endian order and advances the read * pointer by 4. * * @return the word. */ util.ByteStringBuffer.prototype.getInt32Le = function() { var rval = ( this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16 ^ this.data.charCodeAt(this.read + 3) << 24); this.read += 4; return rval; }; /** * Gets an n-bit integer from this buffer in big-endian order and advances the * read pointer by ceil(n/8). * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.ByteStringBuffer.prototype.getInt = function(n) { _checkBitsParam(n); var rval = 0; do { // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. rval = (rval << 8) + this.data.charCodeAt(this.read++); n -= 8; } while(n > 0); return rval; }; /** * Gets a signed n-bit integer from this buffer in big-endian order, using * two's complement, and advances the read pointer by n/8. * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.ByteStringBuffer.prototype.getSignedInt = function(n) { // getInt checks n var x = this.getInt(n); var max = 2 << (n - 2); if(x >= max) { x -= max << 1; } return x; }; /** * Reads bytes out into a UTF-8 string and clears them from the buffer. * * @param count the number of bytes to read, undefined or null for all. * * @return a UTF-8 string of bytes. */ util.ByteStringBuffer.prototype.getBytes = function(count) { var rval; if(count) { // read count bytes count = Math.min(this.length(), count); rval = this.data.slice(this.read, this.read + count); this.read += count; } else if(count === 0) { rval = ''; } else { // read all bytes, optimize to only copy when needed rval = (this.read === 0) ? this.data : this.data.slice(this.read); this.clear(); } return rval; }; /** * Gets a UTF-8 encoded string of the bytes from this buffer without modifying * the read pointer. * * @param count the number of bytes to get, omit to get all. * * @return a string full of UTF-8 encoded characters. */ util.ByteStringBuffer.prototype.bytes = function(count) { return (typeof(count) === 'undefined' ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count)); }; /** * Gets a byte at the given index without modifying the read pointer. * * @param i the byte index. * * @return the byte. */ util.ByteStringBuffer.prototype.at = function(i) { return this.data.charCodeAt(this.read + i); }; /** * Puts a byte at the given index without modifying the read pointer. * * @param i the byte index. * @param b the byte to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.setAt = function(i, b) { this.data = this.data.substr(0, this.read + i) + String.fromCharCode(b) + this.data.substr(this.read + i + 1); return this; }; /** * Gets the last byte without modifying the read pointer. * * @return the last byte. */ util.ByteStringBuffer.prototype.last = function() { return this.data.charCodeAt(this.data.length - 1); }; /** * Creates a copy of this buffer. * * @return the copy. */ util.ByteStringBuffer.prototype.copy = function() { var c = util.createBuffer(this.data); c.read = this.read; return c; }; /** * Compacts this buffer. * * @return this buffer. */ util.ByteStringBuffer.prototype.compact = function() { if(this.read > 0) { this.data = this.data.slice(this.read); this.read = 0; } return this; }; /** * Clears this buffer. * * @return this buffer. */ util.ByteStringBuffer.prototype.clear = function() { this.data = ''; this.read = 0; return this; }; /** * Shortens this buffer by triming bytes off of the end of this buffer. * * @param count the number of bytes to trim off. * * @return this buffer. */ util.ByteStringBuffer.prototype.truncate = function(count) { var len = Math.max(0, this.length() - count); this.data = this.data.substr(this.read, len); this.read = 0; return this; }; /** * Converts this buffer to a hexadecimal string. * * @return a hexadecimal string. */ util.ByteStringBuffer.prototype.toHex = function() { var rval = ''; for(var i = this.read; i < this.data.length; ++i) { var b = this.data.charCodeAt(i); if(b < 16) { rval += '0'; } rval += b.toString(16); } return rval; }; /** * Converts this buffer to a UTF-16 string (standard JavaScript string). * * @return a UTF-16 string. */ util.ByteStringBuffer.prototype.toString = function() { return util.decodeUtf8(this.bytes()); }; /** End Buffer w/BinaryString backing */ /** Buffer w/UInt8Array backing */ /** * FIXME: Experimental. Do not use yet. * * Constructor for an ArrayBuffer-backed byte buffer. * * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a * TypedArray. * * If a string is given, its encoding should be provided as an option, * otherwise it will default to 'binary'. A 'binary' string is encoded such * that each character is one byte in length and size. * * If an ArrayBuffer, DataView, or TypedArray is given, it will be used * *directly* without any copying. Note that, if a write to the buffer requires * more space, the buffer will allocate a new backing ArrayBuffer to * accommodate. The starting read and write offsets for the buffer may be * given as options. * * @param [b] the initial bytes for this buffer. * @param options the options to use: * [readOffset] the starting read offset to use (default: 0). * [writeOffset] the starting write offset to use (default: the * length of the first parameter). * [growSize] the minimum amount, in bytes, to grow the buffer by to * accommodate writes (default: 1024). * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the * first parameter, if it is a string (default: 'binary'). */ function DataBuffer(b, options) { // default options options = options || {}; // pointers for read from/write to buffer this.read = options.readOffset || 0; this.growSize = options.growSize || 1024; var isArrayBuffer = util.isArrayBuffer(b); var isArrayBufferView = util.isArrayBufferView(b); if(isArrayBuffer || isArrayBufferView) { // use ArrayBuffer directly if(isArrayBuffer) { this.data = new DataView(b); } else { // TODO: adjust read/write offset based on the type of view // or specify that this must be done in the options ... that the // offsets are byte-based this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); } this.write = ('writeOffset' in options ? options.writeOffset : this.data.byteLength); return; } // initialize to empty array buffer and add any given bytes using putBytes this.data = new DataView(new ArrayBuffer(0)); this.write = 0; if(b !== null && b !== undefined) { this.putBytes(b); } if('writeOffset' in options) { this.write = options.writeOffset; } } util.DataBuffer = DataBuffer; /** * Gets the number of bytes in this buffer. * * @return the number of bytes in this buffer. */ util.DataBuffer.prototype.length = function() { return this.write - this.read; }; /** * Gets whether or not this buffer is empty. * * @return true if this buffer is empty, false if not. */ util.DataBuffer.prototype.isEmpty = function() { return this.length() <= 0; }; /** * Ensures this buffer has enough empty space to accommodate the given number * of bytes. An optional parameter may be given that indicates a minimum * amount to grow the buffer if necessary. If the parameter is not given, * the buffer will be grown by some previously-specified default amount * or heuristic. * * @param amount the number of bytes to accommodate. * @param [growSize] the minimum amount, in bytes, to grow the buffer by if * necessary. */ util.DataBuffer.prototype.accommodate = function(amount, growSize) { if(this.length() >= amount) { return this; } growSize = Math.max(growSize || this.growSize, amount); // grow buffer var src = new Uint8Array( this.data.buffer, this.data.byteOffset, this.data.byteLength); var dst = new Uint8Array(this.length() + growSize); dst.set(src); this.data = new DataView(dst.buffer); return this; }; /** * Puts a byte in this buffer. * * @param b the byte to put. * * @return this buffer. */ util.DataBuffer.prototype.putByte = function(b) { this.accommodate(1); this.data.setUint8(this.write++, b); return this; }; /** * Puts a byte in this buffer N times. * * @param b the byte to put. * @param n the number of bytes of value b to put. * * @return this buffer. */ util.DataBuffer.prototype.fillWithByte = function(b, n) { this.accommodate(n); for(var i = 0; i < n; ++i) { this.data.setUint8(b); } return this; }; /** * Puts bytes in this buffer. The bytes may be given as a string, an * ArrayBuffer, a DataView, or a TypedArray. * * @param bytes the bytes to put. * @param [encoding] the encoding for the first parameter ('binary', 'utf8', * 'utf16', 'hex'), if it is a string (default: 'binary'). * * @return this buffer. */ util.DataBuffer.prototype.putBytes = function(bytes, encoding) { if(util.isArrayBufferView(bytes)) { var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); var len = src.byteLength - src.byteOffset; this.accommodate(len); var dst = new Uint8Array(this.data.buffer, this.write); dst.set(src); this.write += len; return this; } if(util.isArrayBuffer(bytes)) { var src = new Uint8Array(bytes); this.accommodate(src.byteLength); var dst = new Uint8Array(this.data.buffer); dst.set(src, this.write); this.write += src.byteLength; return this; } // bytes is a util.DataBuffer or equivalent if(bytes instanceof util.DataBuffer || (typeof bytes === 'object' && typeof bytes.read === 'number' && typeof bytes.write === 'number' && util.isArrayBufferView(bytes.data))) { var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); this.accommodate(src.byteLength); var dst = new Uint8Array(bytes.data.byteLength, this.write); dst.set(src); this.write += src.byteLength; return this; } if(bytes instanceof util.ByteStringBuffer) { // copy binary string and process as the same as a string parameter below bytes = bytes.data; encoding = 'binary'; } // string conversion encoding = encoding || 'binary'; if(typeof bytes === 'string') { var view; // decode from string if(encoding === 'hex') { this.accommodate(Math.ceil(bytes.length / 2)); view = new Uint8Array(this.data.buffer, this.write); this.write += util.binary.hex.decode(bytes, view, this.write); return this; } if(encoding === 'base64') { this.accommodate(Math.ceil(bytes.length / 4) * 3); view = new Uint8Array(this.data.buffer, this.write); this.write += util.binary.base64.decode(bytes, view, this.write); return this; } // encode text as UTF-8 bytes if(encoding === 'utf8') { // encode as UTF-8 then decode string as raw binary bytes = util.encodeUtf8(bytes); encoding = 'binary'; } // decode string as raw binary if(encoding === 'binary' || encoding === 'raw') { // one byte per character this.accommodate(bytes.length); view = new Uint8Array(this.data.buffer, this.write); this.write += util.binary.raw.decode(view); return this; } // encode text as UTF-16 bytes if(encoding === 'utf16') { // two bytes per character this.accommodate(bytes.length * 2); view = new Uint16Array(this.data.buffer, this.write); this.write += util.text.utf16.encode(view); return this; } throw new Error('Invalid encoding: ' + encoding); } throw Error('Invalid parameter: ' + bytes); }; /** * Puts the given buffer into this buffer. * * @param buffer the buffer to put into this one. * * @return this buffer. */ util.DataBuffer.prototype.putBuffer = function(buffer) { this.putBytes(buffer); buffer.clear(); return this; }; /** * Puts a string into this buffer. * * @param str the string to put. * @param [encoding] the encoding for the string (default: 'utf16'). * * @return this buffer. */ util.DataBuffer.prototype.putString = function(str) { return this.putBytes(str, 'utf16'); }; /** * Puts a 16-bit integer in this buffer in big-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt16 = function(i) { this.accommodate(2); this.data.setInt16(this.write, i); this.write += 2; return this; }; /** * Puts a 24-bit integer in this buffer in big-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt24 = function(i) { this.accommodate(3); this.data.setInt16(this.write, i >> 8 & 0xFFFF); this.data.setInt8(this.write, i >> 16 & 0xFF); this.write += 3; return this; }; /** * Puts a 32-bit integer in this buffer in big-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt32 = function(i) { this.accommodate(4); this.data.setInt32(this.write, i); this.write += 4; return this; }; /** * Puts a 16-bit integer in this buffer in little-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt16Le = function(i) { this.accommodate(2); this.data.setInt16(this.write, i, true); this.write += 2; return this; }; /** * Puts a 24-bit integer in this buffer in little-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt24Le = function(i) { this.accommodate(3); this.data.setInt8(this.write, i >> 16 & 0xFF); this.data.setInt16(this.write, i >> 8 & 0xFFFF, true); this.write += 3; return this; }; /** * Puts a 32-bit integer in this buffer in little-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt32Le = function(i) { this.accommodate(4); this.data.setInt32(this.write, i, true); this.write += 4; return this; }; /** * Puts an n-bit integer in this buffer in big-endian order. * * @param i the n-bit integer. * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return this buffer. */ util.DataBuffer.prototype.putInt = function(i, n) { _checkBitsParam(n); this.accommodate(n / 8); do { n -= 8; this.data.setInt8(this.write++, (i >> n) & 0xFF); } while(n > 0); return this; }; /** * Puts a signed n-bit integer in this buffer in big-endian order. Two's * complement representation is used. * * @param i the n-bit integer. * @param n the number of bits in the integer. * * @return this buffer. */ util.DataBuffer.prototype.putSignedInt = function(i, n) { _checkBitsParam(n); this.accommodate(n / 8); if(i < 0) { i += 2 << (n - 1); } return this.putInt(i, n); }; /** * Gets a byte from this buffer and advances the read pointer by 1. * * @return the byte. */ util.DataBuffer.prototype.getByte = function() { return this.data.getInt8(this.read++); }; /** * Gets a uint16 from this buffer in big-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.DataBuffer.prototype.getInt16 = function() { var rval = this.data.getInt16(this.read); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in big-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.DataBuffer.prototype.getInt24 = function() { var rval = ( this.data.getInt16(this.read) << 8 ^ this.data.getInt8(this.read + 2)); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in big-endian order and advances the read * pointer by 4. * * @return the word. */ util.DataBuffer.prototype.getInt32 = function() { var rval = this.data.getInt32(this.read); this.read += 4; return rval; }; /** * Gets a uint16 from this buffer in little-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.DataBuffer.prototype.getInt16Le = function() { var rval = this.data.getInt16(this.read, true); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in little-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.DataBuffer.prototype.getInt24Le = function() { var rval = ( this.data.getInt8(this.read) ^ this.data.getInt16(this.read + 1, true) << 8); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in little-endian order and advances the read * pointer by 4. * * @return the word. */ util.DataBuffer.prototype.getInt32Le = function() { var rval = this.data.getInt32(this.read, true); this.read += 4; return rval; }; /** * Gets an n-bit integer from this buffer in big-endian order and advances the * read pointer by n/8. * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.DataBuffer.prototype.getInt = function(n) { _checkBitsParam(n); var rval = 0; do { // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. rval = (rval << 8) + this.data.getInt8(this.read++); n -= 8; } while(n > 0); return rval; }; /** * Gets a signed n-bit integer from this buffer in big-endian order, using * two's complement, and advances the read pointer by n/8. * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.DataBuffer.prototype.getSignedInt = function(n) { // getInt checks n var x = this.getInt(n); var max = 2 << (n - 2); if(x >= max) { x -= max << 1; } return x; }; /** * Reads bytes out into a UTF-8 string and clears them from the buffer. * * @param count the number of bytes to read, undefined or null for all. * * @return a UTF-8 string of bytes. */ util.DataBuffer.prototype.getBytes = function(count) { // TODO: deprecate this method, it is poorly named and // this.toString('binary') replaces it // add a toTypedArray()/toArrayBuffer() function var rval; if(count) { // read count bytes count = Math.min(this.length(), count); rval = this.data.slice(this.read, this.read + count); this.read += count; } else if(count === 0) { rval = ''; } else { // read all bytes, optimize to only copy when needed rval = (this.read === 0) ? this.data : this.data.slice(this.read); this.clear(); } return rval; }; /** * Gets a UTF-8 encoded string of the bytes from this buffer without modifying * the read pointer. * * @param count the number of bytes to get, omit to get all. * * @return a string full of UTF-8 encoded characters. */ util.DataBuffer.prototype.bytes = function(count) { // TODO: deprecate this method, it is poorly named, add "getString()" return (typeof(count) === 'undefined' ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count)); }; /** * Gets a byte at the given index without modifying the read pointer. * * @param i the byte index. * * @return the byte. */ util.DataBuffer.prototype.at = function(i) { return this.data.getUint8(this.read + i); }; /** * Puts a byte at the given index without modifying the read pointer. * * @param i the byte index. * @param b the byte to put. * * @return this buffer. */ util.DataBuffer.prototype.setAt = function(i, b) { this.data.setUint8(i, b); return this; }; /** * Gets the last byte without modifying the read pointer. * * @return the last byte. */ util.DataBuffer.prototype.last = function() { return this.data.getUint8(this.write - 1); }; /** * Creates a copy of this buffer. * * @return the copy. */ util.DataBuffer.prototype.copy = function() { return new util.DataBuffer(this); }; /** * Compacts this buffer. * * @return this buffer. */ util.DataBuffer.prototype.compact = function() { if(this.read > 0) { var src = new Uint8Array(this.data.buffer, this.read); var dst = new Uint8Array(src.byteLength); dst.set(src); this.data = new DataView(dst); this.write -= this.read; this.read = 0; } return this; }; /** * Clears this buffer. * * @return this buffer. */ util.DataBuffer.prototype.clear = function() { this.data = new DataView(new ArrayBuffer(0)); this.read = this.write = 0; return this; }; /** * Shortens this buffer by triming bytes off of the end of this buffer. * * @param count the number of bytes to trim off. * * @return this buffer. */ util.DataBuffer.prototype.truncate = function(count) { this.write = Math.max(0, this.length() - count); this.read = Math.min(this.read, this.write); return this; }; /** * Converts this buffer to a hexadecimal string. * * @return a hexadecimal string. */ util.DataBuffer.prototype.toHex = function() { var rval = ''; for(var i = this.read; i < this.data.byteLength; ++i) { var b = this.data.getUint8(i); if(b < 16) { rval += '0'; } rval += b.toString(16); } return rval; }; /** * Converts this buffer to a string, using the given encoding. If no * encoding is given, 'utf8' (UTF-8) is used. * * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex', * 'base64' (default: 'utf8'). * * @return a string representation of the bytes in this buffer. */ util.DataBuffer.prototype.toString = function(encoding) { var view = new Uint8Array(this.data, this.read, this.length()); encoding = encoding || 'utf8'; // encode to string if(encoding === 'binary' || encoding === 'raw') { return util.binary.raw.encode(view); } if(encoding === 'hex') { return util.binary.hex.encode(view); } if(encoding === 'base64') { return util.binary.base64.encode(view); } // decode to text if(encoding === 'utf8') { return util.text.utf8.decode(view); } if(encoding === 'utf16') { return util.text.utf16.decode(view); } throw new Error('Invalid encoding: ' + encoding); }; /** End Buffer w/UInt8Array backing */ /** * Creates a buffer that stores bytes. A value may be given to put into the * buffer that is either a string of bytes or a UTF-16 string that will * be encoded using UTF-8 (to do the latter, specify 'utf8' as the encoding). * * @param [input] the bytes to wrap (as a string) or a UTF-16 string to encode * as UTF-8. * @param [encoding] (default: 'raw', other: 'utf8'). */ util.createBuffer = function(input, encoding) { // TODO: deprecate, use new ByteBuffer() instead encoding = encoding || 'raw'; if(input !== undefined && encoding === 'utf8') { input = util.encodeUtf8(input); } return new util.ByteBuffer(input); }; /** * Fills a string with a particular value. If you want the string to be a byte * string, pass in String.fromCharCode(theByte). * * @param c the character to fill the string with, use String.fromCharCode * to fill the string with a byte value. * @param n the number of characters of value c to fill with. * * @return the filled string. */ util.fillString = function(c, n) { var s = ''; while(n > 0) { if(n & 1) { s += c; } n >>>= 1; if(n > 0) { c += c; } } return s; }; /** * Performs a per byte XOR between two byte strings and returns the result as a * string of bytes. * * @param s1 first string of bytes. * @param s2 second string of bytes. * @param n the number of bytes to XOR. * * @return the XOR'd result. */ util.xorBytes = function(s1, s2, n) { var s3 = ''; var b = ''; var t = ''; var i = 0; var c = 0; for(; n > 0; --n, ++i) { b = s1.charCodeAt(i) ^ s2.charCodeAt(i); if(c >= 10) { s3 += t; t = ''; c = 0; } t += String.fromCharCode(b); ++c; } s3 += t; return s3; }; /** * Converts a hex string into a 'binary' encoded string of bytes. * * @param hex the hexadecimal string to convert. * * @return the binary-encoded string of bytes. */ util.hexToBytes = function(hex) { // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead." var rval = ''; var i = 0; if(hex.length & 1 == 1) { // odd number of characters, convert first character alone i = 1; rval += String.fromCharCode(parseInt(hex[0], 16)); } // convert 2 characters (1 byte) at a time for(; i < hex.length; i += 2) { rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); } return rval; }; /** * Converts a 'binary' encoded string of bytes to hex. * * @param bytes the byte string to convert. * * @return the string of hexadecimal characters. */ util.bytesToHex = function(bytes) { // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead." return util.createBuffer(bytes).toHex(); }; /** * Converts an 32-bit integer to 4-big-endian byte string. * * @param i the integer. * * @return the byte string. */ util.int32ToBytes = function(i) { return ( String.fromCharCode(i >> 24 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; // base64 characters, reverse mapping var _base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var _base64Idx = [ /*43 -43 = 0*/ /*'+', 1, 2, 3,'/' */ 62, -1, -1, -1, 63, /*'0','1','2','3','4','5','6','7','8','9' */ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, /*15, 16, 17,'=', 19, 20, 21 */ -1, -1, -1, 64, -1, -1, -1, /*65 - 43 = 22*/ /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, /*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, /*91 - 43 = 48 */ /*48, 49, 50, 51, 52, 53 */ -1, -1, -1, -1, -1, -1, /*97 - 43 = 54*/ /*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 ]; /** * Base64 encodes a 'binary' encoded string of bytes. * * @param input the binary encoded string of bytes to base64-encode. * @param maxline the maximum number of encoded characters per line to use, * defaults to none. * * @return the base64-encoded output. */ util.encode64 = function(input, maxline) { // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead." var line = ''; var output = ''; var chr1, chr2, chr3; var i = 0; while(i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); // encode 4 character group line += _base64.charAt(chr1 >> 2); line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); if(isNaN(chr2)) { line += '=='; } else { line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); } if(maxline && line.length > maxline) { output += line.substr(0, maxline) + '\r\n'; line = line.substr(maxline); } } output += line; return output; }; /** * Base64 decodes a string into a 'binary' encoded string of bytes. * * @param input the base64-encoded input. * * @return the binary encoded string. */ util.decode64 = function(input) { // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead." // remove all non-base64 characters input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); var output = ''; var enc1, enc2, enc3, enc4; var i = 0; while(i < input.length) { enc1 = _base64Idx[input.charCodeAt(i++) - 43]; enc2 = _base64Idx[input.charCodeAt(i++) - 43]; enc3 = _base64Idx[input.charCodeAt(i++) - 43]; enc4 = _base64Idx[input.charCodeAt(i++) - 43]; output += String.fromCharCode((enc1 << 2) | (enc2 >> 4)); if(enc3 !== 64) { // decoded at least 2 bytes output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2)); if(enc4 !== 64) { // decoded 3 bytes output += String.fromCharCode(((enc3 & 3) << 6) | enc4); } } } return output; }; /** * UTF-8 encodes the given UTF-16 encoded string (a standard JavaScript * string). Non-ASCII characters will be encoded as multiple bytes according * to UTF-8. * * @param str the string to encode. * * @return the UTF-8 encoded string. */ util.encodeUtf8 = function(str) { return unescape(encodeURIComponent(str)); }; /** * Decodes a UTF-8 encoded string into a UTF-16 string. * * @param str the string to decode. * * @return the UTF-16 encoded string (standard JavaScript string). */ util.decodeUtf8 = function(str) { return decodeURIComponent(escape(str)); }; // binary encoding/decoding tools // FIXME: Experimental. Do not use yet. util.binary = { raw: {}, hex: {}, base64: {} }; /** * Encodes a Uint8Array as a binary-encoded string. This encoding uses * a value between 0 and 255 for each character. * * @param bytes the Uint8Array to encode. * * @return the binary-encoded string. */ util.binary.raw.encode = function(bytes) { return String.fromCharCode.apply(null, bytes); }; /** * Decodes a binary-encoded string to a Uint8Array. This encoding uses * a value between 0 and 255 for each character. * * @param str the binary-encoded string to decode. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.binary.raw.decode = function(str, output, offset) { var out = output; if(!out) { out = new Uint8Array(str.length); } offset = offset || 0; var j = offset; for(var i = 0; i < str.length; ++i) { out[j++] = str.charCodeAt(i); } return output ? (j - offset) : out; }; /** * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or * ByteBuffer as a string of hexadecimal characters. * * @param bytes the bytes to convert. * * @return the string of hexadecimal characters. */ util.binary.hex.encode = util.bytesToHex; /** * Decodes a hex-encoded string to a Uint8Array. * * @param hex the hexadecimal string to convert. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.binary.hex.decode = function(hex, output, offset) { var out = output; if(!out) { out = new Uint8Array(Math.ceil(hex.length / 2)); } offset = offset || 0; var i = 0, j = offset; if(hex.length & 1) { // odd number of characters, convert first character alone i = 1; out[j++] = parseInt(hex[0], 16); } // convert 2 characters (1 byte) at a time for(; i < hex.length; i += 2) { out[j++] = parseInt(hex.substr(i, 2), 16); } return output ? (j - offset) : out; }; /** * Base64-encodes a Uint8Array. * * @param input the Uint8Array to encode. * @param maxline the maximum number of encoded characters per line to use, * defaults to none. * * @return the base64-encoded output string. */ util.binary.base64.encode = function(input, maxline) { var line = ''; var output = ''; var chr1, chr2, chr3; var i = 0; while(i < input.byteLength) { chr1 = input[i++]; chr2 = input[i++]; chr3 = input[i++]; // encode 4 character group line += _base64.charAt(chr1 >> 2); line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); if(isNaN(chr2)) { line += '=='; } else { line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); } if(maxline && line.length > maxline) { output += line.substr(0, maxline) + '\r\n'; line = line.substr(maxline); } } output += line; return output; }; /** * Decodes a base64-encoded string to a Uint8Array. * * @param input the base64-encoded input string. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.binary.base64.decode = function(input, output, offset) { var out = output; if(!out) { out = new Uint8Array(Math.ceil(input.length / 4) * 3); } // remove all non-base64 characters input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); offset = offset || 0; var enc1, enc2, enc3, enc4; var i = 0, j = offset; while(i < input.length) { enc1 = _base64Idx[input.charCodeAt(i++) - 43]; enc2 = _base64Idx[input.charCodeAt(i++) - 43]; enc3 = _base64Idx[input.charCodeAt(i++) - 43]; enc4 = _base64Idx[input.charCodeAt(i++) - 43]; out[j++] = (enc1 << 2) | (enc2 >> 4); if(enc3 !== 64) { // decoded at least 2 bytes out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2); if(enc4 !== 64) { // decoded 3 bytes out[j++] = ((enc3 & 3) << 6) | enc4; } } } // make sure result is the exact decoded length return output ? (j - offset) : out.subarray(0, j); }; // text encoding/decoding tools // FIXME: Experimental. Do not use yet. util.text = { utf8: {}, utf16: {} }; /** * Encodes the given string as UTF-8 in a Uint8Array. * * @param str the string to encode. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.text.utf8.encode = function(str, output, offset) { str = util.encodeUtf8(str); var out = output; if(!out) { out = new Uint8Array(str.length); } offset = offset || 0; var j = offset; for(var i = 0; i < str.length; ++i) { out[j++] = str.charCodeAt(i); } return output ? (j - offset) : out; }; /** * Decodes the UTF-8 contents from a Uint8Array. * * @param bytes the Uint8Array to decode. * * @return the resulting string. */ util.text.utf8.decode = function(bytes) { return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); }; /** * Encodes the given string as UTF-16 in a Uint8Array. * * @param str the string to encode. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.text.utf16.encode = function(str, output, offset) { var out = output; if(!out) { out = new Uint8Array(str.length * 2); } var view = new Uint16Array(out.buffer); offset = offset || 0; var j = offset; var k = offset; for(var i = 0; i < str.length; ++i) { view[k++] = str.charCodeAt(i); j += 2; } return output ? (j - offset) : out; }; /** * Decodes the UTF-16 contents from a Uint8Array. * * @param bytes the Uint8Array to decode. * * @return the resulting string. */ util.text.utf16.decode = function(bytes) { return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); }; /** * Deflates the given data using a flash interface. * * @param api the flash interface. * @param bytes the data. * @param raw true to return only raw deflate data, false to include zlib * header and trailer. * * @return the deflated data as a string. */ util.deflate = function(api, bytes, raw) { bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); // strip zlib header and trailer if necessary if(raw) { // zlib header is 2 bytes (CMF,FLG) where FLG indicates that // there is a 4-byte DICT (alder-32) block before the data if // its 5th bit is set var start = 2; var flg = bytes.charCodeAt(1); if(flg & 0x20) { start = 6; } // zlib trailer is 4 bytes of adler-32 bytes = bytes.substring(start, bytes.length - 4); } return bytes; }; /** * Inflates the given data using a flash interface. * * @param api the flash interface. * @param bytes the data. * @param raw true if the incoming data has no zlib header or trailer and is * raw DEFLATE data. * * @return the inflated data as a string, null on error. */ util.inflate = function(api, bytes, raw) { // TODO: add zlib header and trailer if necessary/possible var rval = api.inflate(util.encode64(bytes)).rval; return (rval === null) ? null : util.decode64(rval); }; /** * Sets a storage object. * * @param api the storage interface. * @param id the storage ID to use. * @param obj the storage object, null to remove. */ var _setStorageObject = function(api, id, obj) { if(!api) { throw new Error('WebStorage not available.'); } var rval; if(obj === null) { rval = api.removeItem(id); } else { // json-encode and base64-encode object obj = util.encode64(JSON.stringify(obj)); rval = api.setItem(id, obj); } // handle potential flash error if(typeof(rval) !== 'undefined' && rval.rval !== true) { var error = new Error(rval.error.message); error.id = rval.error.id; error.name = rval.error.name; throw error; } }; /** * Gets a storage object. * * @param api the storage interface. * @param id the storage ID to use. * * @return the storage object entry or null if none exists. */ var _getStorageObject = function(api, id) { if(!api) { throw new Error('WebStorage not available.'); } // get the existing entry var rval = api.getItem(id); /* Note: We check api.init because we can't do (api == localStorage) on IE because of "Class doesn't support Automation" exception. Only the flash api has an init method so this works too, but we need a better solution in the future. */ // flash returns item wrapped in an object, handle special case if(api.init) { if(rval.rval === null) { if(rval.error) { var error = new Error(rval.error.message); error.id = rval.error.id; error.name = rval.error.name; throw error; } // no error, but also no item rval = null; } else { rval = rval.rval; } } // handle decoding if(rval !== null) { // base64-decode and json-decode data rval = JSON.parse(util.decode64(rval)); } return rval; }; /** * Stores an item in local storage. * * @param api the storage interface. * @param id the storage ID to use. * @param key the key for the item. * @param data the data for the item (any javascript object/primitive). */ var _setItem = function(api, id, key, data) { // get storage object var obj = _getStorageObject(api, id); if(obj === null) { // create a new storage object obj = {}; } // update key obj[key] = data; // set storage object _setStorageObject(api, id, obj); }; /** * Gets an item from local storage. * * @param api the storage interface. * @param id the storage ID to use. * @param key the key for the item. * * @return the item. */ var _getItem = function(api, id, key) { // get storage object var rval = _getStorageObject(api, id); if(rval !== null) { // return data at key rval = (key in rval) ? rval[key] : null; } return rval; }; /** * Removes an item from local storage. * * @param api the storage interface. * @param id the storage ID to use. * @param key the key for the item. */ var _removeItem = function(api, id, key) { // get storage object var obj = _getStorageObject(api, id); if(obj !== null && key in obj) { // remove key delete obj[key]; // see if entry has no keys remaining var empty = true; for(var prop in obj) { empty = false; break; } if(empty) { // remove entry entirely if no keys are left obj = null; } // set storage object _setStorageObject(api, id, obj); } }; /** * Clears the local disk storage identified by the given ID. * * @param api the storage interface. * @param id the storage ID to use. */ var _clearItems = function(api, id) { _setStorageObject(api, id, null); }; /** * Calls a storage function. * * @param func the function to call. * @param args the arguments for the function. * @param location the location argument. * * @return the return value from the function. */ var _callStorageFunction = function(func, args, location) { var rval = null; // default storage types if(typeof(location) === 'undefined') { location = ['web', 'flash']; } // apply storage types in order of preference var type; var done = false; var exception = null; for(var idx in location) { type = location[idx]; try { if(type === 'flash' || type === 'both') { if(args[0] === null) { throw new Error('Flash local storage not available.'); } rval = func.apply(this, args); done = (type === 'flash'); } if(type === 'web' || type === 'both') { args[0] = localStorage; rval = func.apply(this, args); done = true; } } catch(ex) { exception = ex; } if(done) { break; } } if(!done) { throw exception; } return rval; }; /** * Stores an item on local disk. * * The available types of local storage include 'flash', 'web', and 'both'. * * The type 'flash' refers to flash local storage (SharedObject). In order * to use flash local storage, the 'api' parameter must be valid. The type * 'web' refers to WebStorage, if supported by the browser. The type 'both' * refers to storing using both 'flash' and 'web', not just one or the * other. * * The location array should list the storage types to use in order of * preference: * * ['flash']: flash only storage * ['web']: web only storage * ['both']: try to store in both * ['flash','web']: store in flash first, but if not available, 'web' * ['web','flash']: store in web first, but if not available, 'flash' * * The location array defaults to: ['web', 'flash'] * * @param api the flash interface, null to use only WebStorage. * @param id the storage ID to use. * @param key the key for the item. * @param data the data for the item (any javascript object/primitive). * @param location an array with the preferred types of storage to use. */ util.setItem = function(api, id, key, data, location) { _callStorageFunction(_setItem, arguments, location); }; /** * Gets an item on local disk. * * Set setItem() for details on storage types. * * @param api the flash interface, null to use only WebStorage. * @param id the storage ID to use. * @param key the key for the item. * @param location an array with the preferred types of storage to use. * * @return the item. */ util.getItem = function(api, id, key, location) { return _callStorageFunction(_getItem, arguments, location); }; /** * Removes an item on local disk. * * Set setItem() for details on storage types. * * @param api the flash interface. * @param id the storage ID to use. * @param key the key for the item. * @param location an array with the preferred types of storage to use. */ util.removeItem = function(api, id, key, location) { _callStorageFunction(_removeItem, arguments, location); }; /** * Clears the local disk storage identified by the given ID. * * Set setItem() for details on storage types. * * @param api the flash interface if flash is available. * @param id the storage ID to use. * @param location an array with the preferred types of storage to use. */ util.clearItems = function(api, id, location) { _callStorageFunction(_clearItems, arguments, location); }; /** * Parses the scheme, host, and port from an http(s) url. * * @param str the url string. * * @return the parsed url object or null if the url is invalid. */ util.parseUrl = function(str) { // FIXME: this regex looks a bit broken var regex = /^(https?):\/\/([^:&^\/]*):?(\d*)(.*)$/g; regex.lastIndex = 0; var m = regex.exec(str); var url = (m === null) ? null : { full: str, scheme: m[1], host: m[2], port: m[3], path: m[4] }; if(url) { url.fullHost = url.host; if(url.port) { if(url.port !== 80 && url.scheme === 'http') { url.fullHost += ':' + url.port; } else if(url.port !== 443 && url.scheme === 'https') { url.fullHost += ':' + url.port; } } else if(url.scheme === 'http') { url.port = 80; } else if(url.scheme === 'https') { url.port = 443; } url.full = url.scheme + '://' + url.fullHost; } return url; }; /* Storage for query variables */ var _queryVariables = null; /** * Returns the window location query variables. Query is parsed on the first * call and the same object is returned on subsequent calls. The mapping * is from keys to an array of values. Parameters without values will have * an object key set but no value added to the value array. Values are * unescaped. * * ...?k1=v1&k2=v2: * { * "k1": ["v1"], * "k2": ["v2"] * } * * ...?k1=v1&k1=v2: * { * "k1": ["v1", "v2"] * } * * ...?k1=v1&k2: * { * "k1": ["v1"], * "k2": [] * } * * ...?k1=v1&k1: * { * "k1": ["v1"] * } * * ...?k1&k1: * { * "k1": [] * } * * @param query the query string to parse (optional, default to cached * results from parsing window location search query). * * @return object mapping keys to variables. */ util.getQueryVariables = function(query) { var parse = function(q) { var rval = {}; var kvpairs = q.split('&'); for(var i = 0; i < kvpairs.length; i++) { var pos = kvpairs[i].indexOf('='); var key; var val; if(pos > 0) { key = kvpairs[i].substring(0, pos); val = kvpairs[i].substring(pos + 1); } else { key = kvpairs[i]; val = null; } if(!(key in rval)) { rval[key] = []; } // disallow overriding object prototype keys if(!(key in Object.prototype) && val !== null) { rval[key].push(unescape(val)); } } return rval; }; var rval; if(typeof(query) === 'undefined') { // set cached variables if needed if(_queryVariables === null) { if(typeof(window) !== 'undefined' && window.location && window.location.search) { // parse window search query _queryVariables = parse(window.location.search.substring(1)); } else { // no query variables available _queryVariables = {}; } } rval = _queryVariables; } else { // parse given query rval = parse(query); } return rval; }; /** * Parses a fragment into a path and query. This method will take a URI * fragment and break it up as if it were the main URI. For example: * /bar/baz?a=1&b=2 * results in: * { * path: ["bar", "baz"], * query: {"k1": ["v1"], "k2": ["v2"]} * } * * @return object with a path array and query object. */ util.parseFragment = function(fragment) { // default to whole fragment var fp = fragment; var fq = ''; // split into path and query if possible at the first '?' var pos = fragment.indexOf('?'); if(pos > 0) { fp = fragment.substring(0, pos); fq = fragment.substring(pos + 1); } // split path based on '/' and ignore first element if empty var path = fp.split('/'); if(path.length > 0 && path[0] === '') { path.shift(); } // convert query into object var query = (fq === '') ? {} : util.getQueryVariables(fq); return { pathString: fp, queryString: fq, path: path, query: query }; }; /** * Makes a request out of a URI-like request string. This is intended to * be used where a fragment id (after a URI '#') is parsed as a URI with * path and query parts. The string should have a path beginning and * delimited by '/' and optional query parameters following a '?'. The * query should be a standard URL set of key value pairs delimited by * '&'. For backwards compatibility the initial '/' on the path is not * required. The request object has the following API, (fully described * in the method code): * { * path: . * query: , * getPath(i): get part or all of the split path array, * getQuery(k, i): get part or all of a query key array, * getQueryLast(k, _default): get last element of a query key array. * } * * @return object with request parameters. */ util.makeRequest = function(reqString) { var frag = util.parseFragment(reqString); var req = { // full path string path: frag.pathString, // full query string query: frag.queryString, /** * Get path or element in path. * * @param i optional path index. * * @return path or part of path if i provided. */ getPath: function(i) { return (typeof(i) === 'undefined') ? frag.path : frag.path[i]; }, /** * Get query, values for a key, or value for a key index. * * @param k optional query key. * @param i optional query key index. * * @return query, values for a key, or value for a key index. */ getQuery: function(k, i) { var rval; if(typeof(k) === 'undefined') { rval = frag.query; } else { rval = frag.query[k]; if(rval && typeof(i) !== 'undefined') { rval = rval[i]; } } return rval; }, getQueryLast: function(k, _default) { var rval; var vals = req.getQuery(k); if(vals) { rval = vals[vals.length - 1]; } else { rval = _default; } return rval; } }; return req; }; /** * Makes a URI out of a path, an object with query parameters, and a * fragment. Uses jQuery.param() internally for query string creation. * If the path is an array, it will be joined with '/'. * * @param path string path or array of strings. * @param query object with query parameters. (optional) * @param fragment fragment string. (optional) * * @return string object with request parameters. */ util.makeLink = function(path, query, fragment) { // join path parts if needed path = jQuery.isArray(path) ? path.join('/') : path; var qstr = jQuery.param(query || {}); fragment = fragment || ''; return path + ((qstr.length > 0) ? ('?' + qstr) : '') + ((fragment.length > 0) ? ('#' + fragment) : ''); }; /** * Follows a path of keys deep into an object hierarchy and set a value. * If a key does not exist or it's value is not an object, create an * object in it's place. This can be destructive to a object tree if * leaf nodes are given as non-final path keys. * Used to avoid exceptions from missing parts of the path. * * @param object the starting object. * @param keys an array of string keys. * @param value the value to set. */ util.setPath = function(object, keys, value) { // need to start at an object if(typeof(object) === 'object' && object !== null) { var i = 0; var len = keys.length; while(i < len) { var next = keys[i++]; if(i == len) { // last object[next] = value; } else { // more var hasNext = (next in object); if(!hasNext || (hasNext && typeof(object[next]) !== 'object') || (hasNext && object[next] === null)) { object[next] = {}; } object = object[next]; } } } }; /** * Follows a path of keys deep into an object hierarchy and return a value. * If a key does not exist, create an object in it's place. * Used to avoid exceptions from missing parts of the path. * * @param object the starting object. * @param keys an array of string keys. * @param _default value to return if path not found. * * @return the value at the path if found, else default if given, else * undefined. */ util.getPath = function(object, keys, _default) { var i = 0; var len = keys.length; var hasNext = true; while(hasNext && i < len && typeof(object) === 'object' && object !== null) { var next = keys[i++]; hasNext = next in object; if(hasNext) { object = object[next]; } } return (hasNext ? object : _default); }; /** * Follow a path of keys deep into an object hierarchy and delete the * last one. If a key does not exist, do nothing. * Used to avoid exceptions from missing parts of the path. * * @param object the starting object. * @param keys an array of string keys. */ util.deletePath = function(object, keys) { // need to start at an object if(typeof(object) === 'object' && object !== null) { var i = 0; var len = keys.length; while(i < len) { var next = keys[i++]; if(i == len) { // last delete object[next]; } else { // more if(!(next in object) || (typeof(object[next]) !== 'object') || (object[next] === null)) { break; } object = object[next]; } } } }; /** * Check if an object is empty. * * Taken from: * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937 * * @param object the object to check. */ util.isEmpty = function(obj) { for(var prop in obj) { if(obj.hasOwnProperty(prop)) { return false; } } return true; }; /** * Format with simple printf-style interpolation. * * %%: literal '%' * %s,%o: convert next argument into a string. * * @param format the string to format. * @param ... arguments to interpolate into the format string. */ util.format = function(format) { var re = /%./g; // current match var match; // current part var part; // current arg index var argi = 0; // collected parts to recombine later var parts = []; // last index found var last = 0; // loop while matches remain while((match = re.exec(format))) { part = format.substring(last, re.lastIndex - 2); // don't add empty strings (ie, parts between %s%s) if(part.length > 0) { parts.push(part); } last = re.lastIndex; // switch on % code var code = match[0][1]; switch(code) { case 's': case 'o': // check if enough arguments were given if(argi < arguments.length) { parts.push(arguments[argi++ + 1]); } else { parts.push(''); } break; // FIXME: do proper formating for numbers, etc //case 'f': //case 'd': case '%': parts.push('%'); break; default: parts.push('<%' + code + '?>'); } } // add trailing part of format string parts.push(format.substring(last)); return parts.join(''); }; /** * Formats a number. * * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/ */ util.formatNumber = function(number, decimals, dec_point, thousands_sep) { // http://kevin.vanzonneveld.net // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfix by: Michael White (http://crestidg.com) // + bugfix by: Benjamin Lupton // + bugfix by: Allan Jensen (http://www.winternet.no) // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // * example 1: number_format(1234.5678, 2, '.', ''); // * returns 1: 1234.57 var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; var d = dec_point === undefined ? ',' : dec_point; var t = thousands_sep === undefined ? '.' : thousands_sep, s = n < 0 ? '-' : ''; var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + ''; var j = (i.length > 3) ? i.length % 3 : 0; return s + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); }; /** * Formats a byte size. * * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/ */ util.formatSize = function(size) { if(size >= 1073741824) { size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB'; } else if(size >= 1048576) { size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB'; } else if(size >= 1024) { size = util.formatNumber(size / 1024, 0) + ' KiB'; } else { size = util.formatNumber(size, 0) + ' bytes'; } return size; }; /** * Converts an IPv4 or IPv6 string representation into bytes (in network order). * * @param ip the IPv4 or IPv6 address to convert. * * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't * be parsed. */ util.bytesFromIP = function(ip) { if(ip.indexOf('.') !== -1) { return util.bytesFromIPv4(ip); } if(ip.indexOf(':') !== -1) { return util.bytesFromIPv6(ip); } return null; }; /** * Converts an IPv4 string representation into bytes (in network order). * * @param ip the IPv4 address to convert. * * @return the 4-byte address or null if the address can't be parsed. */ util.bytesFromIPv4 = function(ip) { ip = ip.split('.'); if(ip.length !== 4) { return null; } var b = util.createBuffer(); for(var i = 0; i < ip.length; ++i) { var num = parseInt(ip[i], 10); if(isNaN(num)) { return null; } b.putByte(num); } return b.getBytes(); }; /** * Converts an IPv6 string representation into bytes (in network order). * * @param ip the IPv6 address to convert. * * @return the 16-byte address or null if the address can't be parsed. */ util.bytesFromIPv6 = function(ip) { var blanks = 0; ip = ip.split(':').filter(function(e) { if(e.length === 0) ++blanks; return true; }); var zeros = (8 - ip.length + blanks) * 2; var b = util.createBuffer(); for(var i = 0; i < 8; ++i) { if(!ip[i] || ip[i].length === 0) { b.fillWithByte(0, zeros); zeros = 0; continue; } var bytes = util.hexToBytes(ip[i]); if(bytes.length < 2) { b.putByte(0); } b.putBytes(bytes); } return b.getBytes(); }; /** * Converts 4-bytes into an IPv4 string representation or 16-bytes into * an IPv6 string representation. The bytes must be in network order. * * @param bytes the bytes to convert. * * @return the IPv4 or IPv6 string representation if 4 or 16 bytes, * respectively, are given, otherwise null. */ util.bytesToIP = function(bytes) { if(bytes.length === 4) { return util.bytesToIPv4(bytes); } if(bytes.length === 16) { return util.bytesToIPv6(bytes); } return null; }; /** * Converts 4-bytes into an IPv4 string representation. The bytes must be * in network order. * * @param bytes the bytes to convert. * * @return the IPv4 string representation or null for an invalid # of bytes. */ util.bytesToIPv4 = function(bytes) { if(bytes.length !== 4) { return null; } var ip = []; for(var i = 0; i < bytes.length; ++i) { ip.push(bytes.charCodeAt(i)); } return ip.join('.'); }; /** * Converts 16-bytes into an IPv16 string representation. The bytes must be * in network order. * * @param bytes the bytes to convert. * * @return the IPv16 string representation or null for an invalid # of bytes. */ util.bytesToIPv6 = function(bytes) { if(bytes.length !== 16) { return null; } var ip = []; var zeroGroups = []; var zeroMaxGroup = 0; for(var i = 0; i < bytes.length; i += 2) { var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); // canonicalize zero representation while(hex[0] === '0' && hex !== '0') { hex = hex.substr(1); } if(hex === '0') { var last = zeroGroups[zeroGroups.length - 1]; var idx = ip.length; if(!last || idx !== last.end + 1) { zeroGroups.push({start: idx, end: idx}); } else { last.end = idx; if((last.end - last.start) > (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) { zeroMaxGroup = zeroGroups.length - 1; } } } ip.push(hex); } if(zeroGroups.length > 0) { var group = zeroGroups[zeroMaxGroup]; // only shorten group of length > 0 if(group.end - group.start > 0) { ip.splice(group.start, group.end - group.start + 1, ''); if(group.start === 0) { ip.unshift(''); } if(group.end === 7) { ip.push(''); } } } return ip.join(':'); }; /** * Estimates the number of processes that can be run concurrently. If * creating Web Workers, keep in mind that the main JavaScript process needs * its own core. * * @param options the options to use: * update true to force an update (not use the cached value). * @param callback(err, max) called once the operation completes. */ util.estimateCores = function(options, callback) { if(typeof options === 'function') { callback = options; options = {}; } options = options || {}; if('cores' in util && !options.update) { return callback(null, util.cores); } if(typeof navigator !== 'undefined' && 'hardwareConcurrency' in navigator && navigator.hardwareConcurrency > 0) { util.cores = navigator.hardwareConcurrency; return callback(null, util.cores); } if(typeof Worker === 'undefined') { // workers not available util.cores = 1; return callback(null, util.cores); } if(typeof Blob === 'undefined') { // can't estimate, default to 2 util.cores = 2; return callback(null, util.cores); } // create worker concurrency estimation code as blob var blobUrl = URL.createObjectURL(new Blob(['(', function() { self.addEventListener('message', function(e) { // run worker for 4 ms var st = Date.now(); var et = st + 4; while(Date.now() < et); self.postMessage({st: st, et: et}); }); }.toString(), ')()'], {type: 'application/javascript'})); // take 5 samples using 16 workers sample([], 5, 16); function sample(max, samples, numWorkers) { if(samples === 0) { // get overlap average var avg = Math.floor(max.reduce(function(avg, x) { return avg + x; }, 0) / max.length); util.cores = Math.max(1, avg); URL.revokeObjectURL(blobUrl); return callback(null, util.cores); } map(numWorkers, function(err, results) { max.push(reduce(numWorkers, results)); sample(max, samples - 1, numWorkers); }); } function map(numWorkers, callback) { var workers = []; var results = []; for(var i = 0; i < numWorkers; ++i) { var worker = new Worker(blobUrl); worker.addEventListener('message', function(e) { results.push(e.data); if(results.length === numWorkers) { for(var i = 0; i < numWorkers; ++i) { workers[i].terminate(); } callback(null, results); } }); workers.push(worker); } for(var i = 0; i < numWorkers; ++i) { workers[i].postMessage(i); } } function reduce(numWorkers, results) { // find overlapping time windows var overlaps = []; for(var n = 0; n < numWorkers; ++n) { var r1 = results[n]; var overlap = overlaps[n] = []; for(var i = 0; i < numWorkers; ++i) { if(n === i) { continue; } var r2 = results[i]; if((r1.st > r2.st && r1.st < r2.et) || (r2.st > r1.st && r2.st < r1.et)) { overlap.push(i); } } } // get maximum overlaps ... don't include overlapping worker itself // as the main JS process was also being scheduled during the work and // would have to be subtracted from the estimate anyway return overlaps.reduce(function(max, overlap) { return Math.max(max, overlap.length); }, 0); } }; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { /** * Node.js module for Forge message digests. * * @author Dave Longley * * Copyright 2011-2017 Digital Bazaar, Inc. */ var forge = __webpack_require__(0); module.exports = forge.md = forge.md || {}; forge.md.algorithms = forge.md.algorithms || {}; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { /** * An API for getting cryptographically-secure random bytes. The bytes are * generated using the Fortuna algorithm devised by Bruce Schneier and * Niels Ferguson. * * Getting strong random bytes is not yet easy to do in javascript. The only * truish random entropy that can be collected is from the mouse, keyboard, or * from timing with respect to page loads, etc. This generator makes a poor * attempt at providing random bytes when those sources haven't yet provided * enough entropy to initially seed or to reseed the PRNG. * * @author Dave Longley * * Copyright (c) 2009-2014 Digital Bazaar, Inc. */ var forge = __webpack_require__(0); __webpack_require__(6); __webpack_require__(9); __webpack_require__(17); __webpack_require__(1); (function() { // forge.random already defined if(forge.random && forge.random.getBytes) { module.exports = forge.random; return; } (function(jQuery) { // the default prng plugin, uses AES-128 var prng_aes = {}; var _prng_aes_output = new Array(4); var _prng_aes_buffer = forge.util.createBuffer(); prng_aes.formatKey = function(key) { // convert the key into 32-bit integers var tmp = forge.util.createBuffer(key); key = new Array(4); key[0] = tmp.getInt32(); key[1] = tmp.getInt32(); key[2] = tmp.getInt32(); key[3] = tmp.getInt32(); // return the expanded key return forge.aes._expandKey(key, false); }; prng_aes.formatSeed = function(seed) { // convert seed into 32-bit integers var tmp = forge.util.createBuffer(seed); seed = new Array(4); seed[0] = tmp.getInt32(); seed[1] = tmp.getInt32(); seed[2] = tmp.getInt32(); seed[3] = tmp.getInt32(); return seed; }; prng_aes.cipher = function(key, seed) { forge.aes._updateBlock(key, seed, _prng_aes_output, false); _prng_aes_buffer.putInt32(_prng_aes_output[0]); _prng_aes_buffer.putInt32(_prng_aes_output[1]); _prng_aes_buffer.putInt32(_prng_aes_output[2]); _prng_aes_buffer.putInt32(_prng_aes_output[3]); return _prng_aes_buffer.getBytes(); }; prng_aes.increment = function(seed) { // FIXME: do we care about carry or signed issues? ++seed[3]; return seed; }; prng_aes.md = forge.md.sha256; /** * Creates a new PRNG. */ function spawnPrng() { var ctx = forge.prng.create(prng_aes); /** * Gets random bytes. If a native secure crypto API is unavailable, this * method tries to make the bytes more unpredictable by drawing from data that * can be collected from the user of the browser, eg: mouse movement. * * If a callback is given, this method will be called asynchronously. * * @param count the number of random bytes to get. * @param [callback(err, bytes)] called once the operation completes. * * @return the random bytes in a string. */ ctx.getBytes = function(count, callback) { return ctx.generate(count, callback); }; /** * Gets random bytes asynchronously. If a native secure crypto API is * unavailable, this method tries to make the bytes more unpredictable by * drawing from data that can be collected from the user of the browser, * eg: mouse movement. * * @param count the number of random bytes to get. * * @return the random bytes in a string. */ ctx.getBytesSync = function(count) { return ctx.generate(count); }; return ctx; } // create default prng context var _ctx = spawnPrng(); // add other sources of entropy only if window.crypto.getRandomValues is not // available -- otherwise this source will be automatically used by the prng var getRandomValues = null; if(typeof window !== 'undefined') { var _crypto = window.crypto || window.msCrypto; if(_crypto && _crypto.getRandomValues) { getRandomValues = function(arr) { return _crypto.getRandomValues(arr); }; } } if(forge.options.usePureJavaScript || (!forge.util.isNodejs && !getRandomValues)) { // if this is a web worker, do not use weak entropy, instead register to // receive strong entropy asynchronously from the main thread if(typeof window === 'undefined' || window.document === undefined) { // FIXME: } // get load time entropy _ctx.collectInt(+new Date(), 32); // add some entropy from navigator object if(typeof(navigator) !== 'undefined') { var _navBytes = ''; for(var key in navigator) { try { if(typeof(navigator[key]) == 'string') { _navBytes += navigator[key]; } } catch(e) { /* Some navigator keys might not be accessible, e.g. the geolocation attribute throws an exception if touched in Mozilla chrome:// context. Silently ignore this and just don't use this as a source of entropy. */ } } _ctx.collect(_navBytes); _navBytes = null; } // add mouse and keyboard collectors if jquery is available if(jQuery) { // set up mouse entropy capture jQuery().mousemove(function(e) { // add mouse coords _ctx.collectInt(e.clientX, 16); _ctx.collectInt(e.clientY, 16); }); // set up keyboard entropy capture jQuery().keypress(function(e) { _ctx.collectInt(e.charCode, 8); }); } } /* Random API */ if(!forge.random) { forge.random = _ctx; } else { // extend forge.random with _ctx for(var key in _ctx) { forge.random[key] = _ctx[key]; } } // expose spawn PRNG forge.random.createInstance = spawnPrng; module.exports = forge.random; })(typeof(jQuery) !== 'undefined' ? jQuery : null); })(); /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { /** * Hash-based Message Authentication Code implementation. Requires a message * digest object that can be obtained, for example, from forge.md.sha1 or * forge.md.md5. * * @author Dave Longley * * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved. */ var forge = __webpack_require__(0); __webpack_require__(2); __webpack_require__(1); /* HMAC API */ var hmac = module.exports = forge.hmac = forge.hmac || {}; /** * Creates an HMAC object that uses the given message digest object. * * @return an HMAC object. */ hmac.create = function() { // the hmac key to use var _key = null; // the message digest to use var _md = null; // the inner padding var _ipadding = null; // the outer padding var _opadding = null; // hmac context var ctx = {}; /** * Starts or restarts the HMAC with the given key and message digest. * * @param md the message digest to use, null to reuse the previous one, * a string to use builtin 'sha1', 'md5', 'sha256'. * @param key the key to use as a string, array of bytes, byte buffer, * or null to reuse the previous key. */ ctx.start = function(md, key) { if(md !== null) { if(typeof md === 'string') { // create builtin message digest md = md.toLowerCase(); if(md in forge.md.algorithms) { _md = forge.md.algorithms[md].create(); } else { throw new Error('Unknown hash algorithm "' + md + '"'); } } else { // store message digest _md = md; } } if(key === null) { // reuse previous key key = _key; } else { if(typeof key === 'string') { // convert string into byte buffer key = forge.util.createBuffer(key); } else if(forge.util.isArray(key)) { // convert byte array into byte buffer var tmp = key; key = forge.util.createBuffer(); for(var i = 0; i < tmp.length; ++i) { key.putByte(tmp[i]); } } // if key is longer than blocksize, hash it var keylen = key.length(); if(keylen > _md.blockLength) { _md.start(); _md.update(key.bytes()); key = _md.digest(); } // mix key into inner and outer padding // ipadding = [0x36 * blocksize] ^ key // opadding = [0x5C * blocksize] ^ key _ipadding = forge.util.createBuffer(); _opadding = forge.util.createBuffer(); keylen = key.length(); for(var i = 0; i < keylen; ++i) { var tmp = key.at(i); _ipadding.putByte(0x36 ^ tmp); _opadding.putByte(0x5C ^ tmp); } // if key is shorter than blocksize, add additional padding if(keylen < _md.blockLength) { var tmp = _md.blockLength - keylen; for(var i = 0; i < tmp; ++i) { _ipadding.putByte(0x36); _opadding.putByte(0x5C); } } _key = key; _ipadding = _ipadding.bytes(); _opadding = _opadding.bytes(); } // digest is done like so: hash(opadding | hash(ipadding | message)) // prepare to do inner hash // hash(ipadding | message) _md.start(); _md.update(_ipadding); }; /** * Updates the HMAC with the given message bytes. * * @param bytes the bytes to update with. */ ctx.update = function(bytes) { _md.update(bytes); }; /** * Produces the Message Authentication Code (MAC). * * @return a byte buffer containing the digest value. */ ctx.getMac = function() { // digest is done like so: hash(opadding | hash(ipadding | message)) // here we do the outer hashing var inner = _md.digest().bytes(); _md.start(); _md.update(_opadding); _md.update(inner); return _md.digest(); }; // alias for getMac ctx.digest = ctx.getMac; return ctx; }; /***/ }), /* 5 */ /***/ (function(module, exports) { /* (ignored) */ /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { /** * Advanced Encryption Standard (AES) implementation. * * This implementation is based on the public domain library 'jscrypto' which * was written by: * * Emily Stark (estark@stanford.edu) * Mike Hamburg (mhamburg@stanford.edu) * Dan Boneh (dabo@cs.stanford.edu) * * Parts of this code are based on the OpenSSL implementation of AES: * http://www.openssl.org * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. */ var forge = __webpack_require__(0); __webpack_require__(12); __webpack_require__(13); __webpack_require__(1); /* AES API */ module.exports = forge.aes = forge.aes || {}; /** * Deprecated. Instead, use: * * var cipher = forge.cipher.createCipher('AES-', key); * cipher.start({iv: iv}); * * Creates an AES cipher object to encrypt data using the given symmetric key. * The output will be stored in the 'output' member of the returned cipher. * * The key and iv may be given as a string of bytes, an array of bytes, * a byte buffer, or an array of 32-bit words. * * @param key the symmetric key to use. * @param iv the initialization vector to use. * @param output the buffer to write to, null to create one. * @param mode the cipher mode to use (default: 'CBC'). * * @return the cipher. */ forge.aes.startEncrypting = function(key, iv, output, mode) { var cipher = _createCipher({ key: key, output: output, decrypt: false, mode: mode }); cipher.start(iv); return cipher; }; /** * Deprecated. Instead, use: * * var cipher = forge.cipher.createCipher('AES-', key); * * Creates an AES cipher object to encrypt data using the given symmetric key. * * The key may be given as a string of bytes, an array of bytes, a * byte buffer, or an array of 32-bit words. * * @param key the symmetric key to use. * @param mode the cipher mode to use (default: 'CBC'). * * @return the cipher. */ forge.aes.createEncryptionCipher = function(key, mode) { return _createCipher({ key: key, output: null, decrypt: false, mode: mode }); }; /** * Deprecated. Instead, use: * * var decipher = forge.cipher.createDecipher('AES-', key); * decipher.start({iv: iv}); * * Creates an AES cipher object to decrypt data using the given symmetric key. * The output will be stored in the 'output' member of the returned cipher. * * The key and iv may be given as a string of bytes, an array of bytes, * a byte buffer, or an array of 32-bit words. * * @param key the symmetric key to use. * @param iv the initialization vector to use. * @param output the buffer to write to, null to create one. * @param mode the cipher mode to use (default: 'CBC'). * * @return the cipher. */ forge.aes.startDecrypting = function(key, iv, output, mode) { var cipher = _createCipher({ key: key, output: output, decrypt: true, mode: mode }); cipher.start(iv); return cipher; }; /** * Deprecated. Instead, use: * * var decipher = forge.cipher.createDecipher('AES-', key); * * Creates an AES cipher object to decrypt data using the given symmetric key. * * The key may be given as a string of bytes, an array of bytes, a * byte buffer, or an array of 32-bit words. * * @param key the symmetric key to use. * @param mode the cipher mode to use (default: 'CBC'). * * @return the cipher. */ forge.aes.createDecryptionCipher = function(key, mode) { return _createCipher({ key: key, output: null, decrypt: true, mode: mode }); }; /** * Creates a new AES cipher algorithm object. * * @param name the name of the algorithm. * @param mode the mode factory function. * * @return the AES algorithm object. */ forge.aes.Algorithm = function(name, mode) { if(!init) { initialize(); } var self = this; self.name = name; self.mode = new mode({ blockSize: 16, cipher: { encrypt: function(inBlock, outBlock) { return _updateBlock(self._w, inBlock, outBlock, false); }, decrypt: function(inBlock, outBlock) { return _updateBlock(self._w, inBlock, outBlock, true); } } }); self._init = false; }; /** * Initializes this AES algorithm by expanding its key. * * @param options the options to use. * key the key to use with this algorithm. * decrypt true if the algorithm should be initialized for decryption, * false for encryption. */ forge.aes.Algorithm.prototype.initialize = function(options) { if(this._init) { return; } var key = options.key; var tmp; /* Note: The key may be a string of bytes, an array of bytes, a byte buffer, or an array of 32-bit integers. If the key is in bytes, then it must be 16, 24, or 32 bytes in length. If it is in 32-bit integers, it must be 4, 6, or 8 integers long. */ if(typeof key === 'string' && (key.length === 16 || key.length === 24 || key.length === 32)) { // convert key string into byte buffer key = forge.util.createBuffer(key); } else if(forge.util.isArray(key) && (key.length === 16 || key.length === 24 || key.length === 32)) { // convert key integer array into byte buffer tmp = key; key = forge.util.createBuffer(); for(var i = 0; i < tmp.length; ++i) { key.putByte(tmp[i]); } } // convert key byte buffer into 32-bit integer array if(!forge.util.isArray(key)) { tmp = key; key = []; // key lengths of 16, 24, 32 bytes allowed var len = tmp.length(); if(len === 16 || len === 24 || len === 32) { len = len >>> 2; for(var i = 0; i < len; ++i) { key.push(tmp.getInt32()); } } } // key must be an array of 32-bit integers by now if(!forge.util.isArray(key) || !(key.length === 4 || key.length === 6 || key.length === 8)) { throw new Error('Invalid key parameter.'); } // encryption operation is always used for these modes var mode = this.mode.name; var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1); // do key expansion this._w = _expandKey(key, options.decrypt && !encryptOp); this._init = true; }; /** * Expands a key. Typically only used for testing. * * @param key the symmetric key to expand, as an array of 32-bit words. * @param decrypt true to expand for decryption, false for encryption. * * @return the expanded key. */ forge.aes._expandKey = function(key, decrypt) { if(!init) { initialize(); } return _expandKey(key, decrypt); }; /** * Updates a single block. Typically only used for testing. * * @param w the expanded key to use. * @param input an array of block-size 32-bit words. * @param output an array of block-size 32-bit words. * @param decrypt true to decrypt, false to encrypt. */ forge.aes._updateBlock = _updateBlock; /** Register AES algorithms **/ registerAlgorithm('AES-ECB', forge.cipher.modes.ecb); registerAlgorithm('AES-CBC', forge.cipher.modes.cbc); registerAlgorithm('AES-CFB', forge.cipher.modes.cfb); registerAlgorithm('AES-OFB', forge.cipher.modes.ofb); registerAlgorithm('AES-CTR', forge.cipher.modes.ctr); registerAlgorithm('AES-GCM', forge.cipher.modes.gcm); function registerAlgorithm(name, mode) { var factory = function() { return new forge.aes.Algorithm(name, mode); }; forge.cipher.registerAlgorithm(name, factory); } /** AES implementation **/ var init = false; // not yet initialized var Nb = 4; // number of words comprising the state (AES = 4) var sbox; // non-linear substitution table used in key expansion var isbox; // inversion of sbox var rcon; // round constant word array var mix; // mix-columns table var imix; // inverse mix-columns table /** * Performs initialization, ie: precomputes tables to optimize for speed. * * One way to understand how AES works is to imagine that 'addition' and * 'multiplication' are interfaces that require certain mathematical * properties to hold true (ie: they are associative) but they might have * different implementations and produce different kinds of results ... * provided that their mathematical properties remain true. AES defines * its own methods of addition and multiplication but keeps some important * properties the same, ie: associativity and distributivity. The * explanation below tries to shed some light on how AES defines addition * and multiplication of bytes and 32-bit words in order to perform its * encryption and decryption algorithms. * * The basics: * * The AES algorithm views bytes as binary representations of polynomials * that have either 1 or 0 as the coefficients. It defines the addition * or subtraction of two bytes as the XOR operation. It also defines the * multiplication of two bytes as a finite field referred to as GF(2^8) * (Note: 'GF' means "Galois Field" which is a field that contains a finite * number of elements so GF(2^8) has 256 elements). * * This means that any two bytes can be represented as binary polynomials; * when they multiplied together and modularly reduced by an irreducible * polynomial of the 8th degree, the results are the field GF(2^8). The * specific irreducible polynomial that AES uses in hexadecimal is 0x11b. * This multiplication is associative with 0x01 as the identity: * * (b * 0x01 = GF(b, 0x01) = b). * * The operation GF(b, 0x02) can be performed at the byte level by left * shifting b once and then XOR'ing it (to perform the modular reduction) * with 0x11b if b is >= 128. Repeated application of the multiplication * of 0x02 can be used to implement the multiplication of any two bytes. * * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these * factors can each be multiplied by 0x57 and then added together. To do * the multiplication, values for 0x57 multiplied by each of these 3 factors * can be precomputed and stored in a table. To add them, the values from * the table are XOR'd together. * * AES also defines addition and multiplication of words, that is 4-byte * numbers represented as polynomials of 3 degrees where the coefficients * are the values of the bytes. * * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0. * * Addition is performed by XOR'ing like powers of x. Multiplication * is performed in two steps, the first is an algebriac expansion as * you would do normally (where addition is XOR). But the result is * a polynomial larger than 3 degrees and thus it cannot fit in a word. So * next the result is modularly reduced by an AES-specific polynomial of * degree 4 which will always produce a polynomial of less than 4 degrees * such that it will fit in a word. In AES, this polynomial is x^4 + 1. * * The modular product of two polynomials 'a' and 'b' is thus: * * d(x) = d3x^3 + d2x^2 + d1x + d0 * with * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3) * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3) * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3) * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3) * * As a matrix: * * [d0] = [a0 a3 a2 a1][b0] * [d1] [a1 a0 a3 a2][b1] * [d2] [a2 a1 a0 a3][b2] * [d3] [a3 a2 a1 a0][b3] * * Special polynomials defined by AES (0x02 == {02}): * a(x) = {03}x^3 + {01}x^2 + {01}x + {02} * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}. * * These polynomials are used in the MixColumns() and InverseMixColumns() * operations, respectively, to cause each element in the state to affect * the output (referred to as diffusing). * * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the * polynomial x3. * * The ShiftRows() method modifies the last 3 rows in the state (where * the state is 4 words with 4 bytes per word) by shifting bytes cyclically. * The 1st byte in the second row is moved to the end of the row. The 1st * and 2nd bytes in the third row are moved to the end of the row. The 1st, * 2nd, and 3rd bytes are moved in the fourth row. * * More details on how AES arithmetic works: * * In the polynomial representation of binary numbers, XOR performs addition * and subtraction and multiplication in GF(2^8) denoted as GF(a, b) * corresponds with the multiplication of polynomials modulo an irreducible * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply * polynomial 'a' with polynomial 'b' and then do a modular reduction by * an AES-specific irreducible polynomial of degree 8. * * A polynomial is irreducible if its only divisors are one and itself. For * the AES algorithm, this irreducible polynomial is: * * m(x) = x^8 + x^4 + x^3 + x + 1, * * or {01}{1b} in hexadecimal notation, where each coefficient is a bit: * 100011011 = 283 = 0x11b. * * For example, GF(0x57, 0x83) = 0xc1 because * * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1 * 0x85 = 131 = 10000101 = x^7 + x + 1 * * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1) * = x^13 + x^11 + x^9 + x^8 + x^7 + * x^7 + x^5 + x^3 + x^2 + x + * x^6 + x^4 + x^2 + x + 1 * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y * y modulo (x^8 + x^4 + x^3 + x + 1) * = x^7 + x^6 + 1. * * The modular reduction by m(x) guarantees the result will be a binary * polynomial of less than degree 8, so that it can fit in a byte. * * The operation to multiply a binary polynomial b with x (the polynomial * x in binary representation is 00000010) is: * * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1 * * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the * most significant bit is 0 in b) then the result is already reduced. If * it is 1, then we can reduce it by subtracting m(x) via an XOR. * * It follows that multiplication by x (00000010 or 0x02) can be implemented * by performing a left shift followed by a conditional bitwise XOR with * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by * higher powers of x can be implemented by repeated application of xtime(). * * By adding intermediate results, multiplication by any constant can be * implemented. For instance: * * GF(0x57, 0x13) = 0xfe because: * * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1) * * Note: We XOR with 0x11b instead of 0x1b because in javascript our * datatype for b can be larger than 1 byte, so a left shift will not * automatically eliminate bits that overflow a byte ... by XOR'ing the * overflow bit with 1 (the extra one from 0x11b) we zero it out. * * GF(0x57, 0x02) = xtime(0x57) = 0xae * GF(0x57, 0x04) = xtime(0xae) = 0x47 * GF(0x57, 0x08) = xtime(0x47) = 0x8e * GF(0x57, 0x10) = xtime(0x8e) = 0x07 * * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10)) * * And by the distributive property (since XOR is addition and GF() is * multiplication): * * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10) * = 0x57 ^ 0xae ^ 0x07 * = 0xfe. */ function initialize() { init = true; /* Populate the Rcon table. These are the values given by [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02) in the field of GF(2^8), where i starts at 1. rcon[0] = [0x00, 0x00, 0x00, 0x00] rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1 rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2 ... rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36 We only store the first byte because it is the only one used. */ rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36]; // compute xtime table which maps i onto GF(i, 0x02) var xtime = new Array(256); for(var i = 0; i < 128; ++i) { xtime[i] = i << 1; xtime[i + 128] = (i + 128) << 1 ^ 0x11B; } // compute all other tables sbox = new Array(256); isbox = new Array(256); mix = new Array(4); imix = new Array(4); for(var i = 0; i < 4; ++i) { mix[i] = new Array(256); imix[i] = new Array(256); } var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; for(var i = 0; i < 256; ++i) { /* We need to generate the SubBytes() sbox and isbox tables so that we can perform byte substitutions. This requires us to traverse all of the elements in GF, find their multiplicative inverses, and apply to each the following affine transformation: bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^ b(i + 7) mod 8 ^ ci for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the ith bit of a byte c with the value {63} or {01100011}. It is possible to traverse every possible value in a Galois field using what is referred to as a 'generator'. There are many generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully traverse GF we iterate 255 times, multiplying by our generator each time. On each iteration we can determine the multiplicative inverse for the current element. Suppose there is an element in GF 'e'. For a given generator 'g', e = g^x. The multiplicative inverse of e is g^(255 - x). It turns out that if use the inverse of a generator as another generator it will produce all of the corresponding multiplicative inverses at the same time. For this reason, we choose 5 as our inverse generator because it only requires 2 multiplies and 1 add and its inverse, 82, requires relatively few operations as well. In order to apply the affine transformation, the multiplicative inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and 'x'. Then 's' is left shifted and the high bit of 's' is made the low bit. The resulting value is stored in 's'. Then 'x' is XOR'd with 's' and stored in 'x'. On each subsequent iteration the same operation is performed. When 4 iterations are complete, 'x' is XOR'd with 'c' (0x63) and the transformed value is stored in 'x'. For example: s = 01000001 x = 01000001 iteration 1: s = 10000010, x ^= s iteration 2: s = 00000101, x ^= s iteration 3: s = 00001010, x ^= s iteration 4: s = 00010100, x ^= s x ^= 0x63 This can be done with a loop where s = (s << 1) | (s >> 7). However, it can also be done by using a single 16-bit (in this case 32-bit) number 'sx'. Since XOR is an associative operation, we can set 'sx' to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times. The most significant bits will flow into the high 8 bit positions and be correctly XOR'd with one another. All that remains will be to cycle the high 8 bits by XOR'ing them all with the lower 8 bits afterwards. At the same time we're populating sbox and isbox we can precompute the multiplication we'll need to do to do MixColumns() later. */ // apply affine transformation sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4); sx = (sx >> 8) ^ (sx & 255) ^ 0x63; // update tables sbox[e] = sx; isbox[sx] = e; /* Mixing columns is done using matrix multiplication. The columns that are to be mixed are each a single word in the current state. The state has Nb columns (4 columns). Therefore each column is a 4 byte word. So to mix the columns in a single column 'c' where its rows are r0, r1, r2, and r3, we use the following matrix multiplication: [2 3 1 1]*[r0,c]=[r'0,c] [1 2 3 1] [r1,c] [r'1,c] [1 1 2 3] [r2,c] [r'2,c] [3 1 1 2] [r3,c] [r'3,c] r0, r1, r2, and r3 are each 1 byte of one of the words in the state (a column). To do matrix multiplication for each mixed column c' we multiply the corresponding row from the left matrix with the corresponding column from the right matrix. In total, we get 4 equations: r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c As usual, the multiplication is as previously defined and the addition is XOR. In order to optimize mixing columns we can store the multiplication results in tables. If you think of the whole column as a word (it might help to visualize by mentally rotating the equations above by counterclockwise 90 degrees) then you can see that it would be useful to map the multiplications performed on each byte (r0, r1, r2, r3) onto a word as well. For instance, we could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the highest 8 bits and 3*r0 in the lowest 8 bits (with the other two respectively in the middle). This means that a table can be constructed that uses r0 as an index to the word. We can do the same with r1, r2, and r3, creating a total of 4 tables. To construct a full c', we can just look up each byte of c in their respective tables and XOR the results together. Also, to build each table we only have to calculate the word for 2,1,1,3 for every byte ... which we can do on each iteration of this loop since we will iterate over every byte. After we have calculated 2,1,1,3 we can get the results for the other tables by cycling the byte at the end to the beginning. For instance we can take the result of table 2,1,1,3 and produce table 3,2,1,1 by moving the right most byte to the left most position just like how you can imagine the 3 moved out of 2,1,1,3 and to the front to produce 3,2,1,1. There is another optimization in that the same multiples of the current element we need in order to advance our generator to the next iteration can be reused in performing the 2,1,1,3 calculation. We also calculate the inverse mix column tables, with e,9,d,b being the inverse of 2,1,1,3. When we're done, and we need to actually mix columns, the first byte of each state word should be put through mix[0] (2,1,1,3), the second through mix[1] (3,2,1,1) and so forth. Then they should be XOR'd together to produce the fully mixed column. */ // calculate mix and imix table values sx2 = xtime[sx]; e2 = xtime[e]; e4 = xtime[e2]; e8 = xtime[e4]; me = (sx2 << 24) ^ // 2 (sx << 16) ^ // 1 (sx << 8) ^ // 1 (sx ^ sx2); // 3 ime = (e2 ^ e4 ^ e8) << 24 ^ // E (14) (e ^ e8) << 16 ^ // 9 (e ^ e4 ^ e8) << 8 ^ // D (13) (e ^ e2 ^ e8); // B (11) // produce each of the mix tables by rotating the 2,1,1,3 value for(var n = 0; n < 4; ++n) { mix[n][e] = me; imix[n][sx] = ime; // cycle the right most byte to the left most position // ie: 2,1,1,3 becomes 3,2,1,1 me = me << 24 | me >>> 8; ime = ime << 24 | ime >>> 8; } // get next element and inverse if(e === 0) { // 1 is the inverse of 1 e = ei = 1; } else { // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator) // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator) e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; ei ^= xtime[xtime[ei]]; } } } /** * Generates a key schedule using the AES key expansion algorithm. * * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion * routine to generate a key schedule. The Key Expansion generates a total * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words, * and each of the Nr rounds requires Nb words of key data. The resulting * key schedule consists of a linear array of 4-byte words, denoted [wi ], * with i in the range 0 ≤ i < Nb(Nr + 1). * * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk) * AES-128 (Nb=4, Nk=4, Nr=10) * AES-192 (Nb=4, Nk=6, Nr=12) * AES-256 (Nb=4, Nk=8, Nr=14) * Note: Nr=Nk+6. * * Nb is the number of columns (32-bit words) comprising the State (or * number of bytes in a block). For AES, Nb=4. * * @param key the key to schedule (as an array of 32-bit words). * @param decrypt true to modify the key schedule to decrypt, false not to. * * @return the generated key schedule. */ function _expandKey(key, decrypt) { // copy the key's words to initialize the key schedule var w = key.slice(0); /* RotWord() will rotate a word, moving the first byte to the last byte's position (shifting the other bytes left). We will be getting the value of Rcon at i / Nk. 'i' will iterate from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will increase by 1. We use a counter iNk to keep track of this. */ // go through the rounds expanding the key var temp, iNk = 1; var Nk = w.length; var Nr1 = Nk + 6 + 1; var end = Nb * Nr1; for(var i = Nk; i < end; ++i) { temp = w[i - 1]; if(i % Nk === 0) { // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk] temp = sbox[temp >>> 16 & 255] << 24 ^ sbox[temp >>> 8 & 255] << 16 ^ sbox[temp & 255] << 8 ^ sbox[temp >>> 24] ^ (rcon[iNk] << 24); iNk++; } else if(Nk > 6 && (i % Nk === 4)) { // temp = SubWord(temp) temp = sbox[temp >>> 24] << 24 ^ sbox[temp >>> 16 & 255] << 16 ^ sbox[temp >>> 8 & 255] << 8 ^ sbox[temp & 255]; } w[i] = w[i - Nk] ^ temp; } /* When we are updating a cipher block we always use the code path for encryption whether we are decrypting or not (to shorten code and simplify the generation of look up tables). However, because there are differences in the decryption algorithm, other than just swapping in different look up tables, we must transform our key schedule to account for these changes: 1. The decryption algorithm gets its key rounds in reverse order. 2. The decryption algorithm adds the round key before mixing columns instead of afterwards. We don't need to modify our key schedule to handle the first case, we can just traverse the key schedule in reverse order when decrypting. The second case requires a little work. The tables we built for performing rounds will take an input and then perform SubBytes() and MixColumns() or, for the decrypt version, InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires us to AddRoundKey() before InvMixColumns(). This means we'll need to apply some transformations to the round key to inverse-mix its columns so they'll be correct for moving AddRoundKey() to after the state has had its columns inverse-mixed. To inverse-mix the columns of the state when we're decrypting we use a lookup table that will apply InvSubBytes() and InvMixColumns() at the same time. However, the round key's bytes are not inverse-substituted in the decryption algorithm. To get around this problem, we can first substitute the bytes in the round key so that when we apply the transformation via the InvSubBytes()+InvMixColumns() table, it will undo our substitution leaving us with the original value that we want -- and then inverse-mix that value. This change will correctly alter our key schedule so that we can XOR each round key with our already transformed decryption state. This allows us to use the same code path as the encryption algorithm. We make one more change to the decryption key. Since the decryption algorithm runs in reverse from the encryption algorithm, we reverse the order of the round keys to avoid having to iterate over the key schedule backwards when running the encryption algorithm later in decryption mode. In addition to reversing the order of the round keys, we also swap each round key's 2nd and 4th rows. See the comments section where rounds are performed for more details about why this is done. These changes are done inline with the other substitution described above. */ if(decrypt) { var tmp; var m0 = imix[0]; var m1 = imix[1]; var m2 = imix[2]; var m3 = imix[3]; var wnew = w.slice(0); end = w.length; for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { // do not sub the first or last round key (round keys are Nb // words) as no column mixing is performed before they are added, // but do change the key order if(i === 0 || i === (end - Nb)) { wnew[i] = w[wi]; wnew[i + 1] = w[wi + 3]; wnew[i + 2] = w[wi + 2]; wnew[i + 3] = w[wi + 1]; } else { // substitute each round key byte because the inverse-mix // table will inverse-substitute it (effectively cancel the // substitution because round key bytes aren't sub'd in // decryption mode) and swap indexes 3 and 1 for(var n = 0; n < Nb; ++n) { tmp = w[wi + n]; wnew[i + (3&-n)] = m0[sbox[tmp >>> 24]] ^ m1[sbox[tmp >>> 16 & 255]] ^ m2[sbox[tmp >>> 8 & 255]] ^ m3[sbox[tmp & 255]]; } } } w = wnew; } return w; } /** * Updates a single block (16 bytes) using AES. The update will either * encrypt or decrypt the block. * * @param w the key schedule. * @param input the input block (an array of 32-bit words). * @param output the updated output block. * @param decrypt true to decrypt the block, false to encrypt it. */ function _updateBlock(w, input, output, decrypt) { /* Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) begin byte state[4,Nb] state = in AddRoundKey(state, w[0, Nb-1]) for round = 1 step 1 to Nr–1 SubBytes(state) ShiftRows(state) MixColumns(state) AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) end for SubBytes(state) ShiftRows(state) AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) out = state end InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) begin byte state[4,Nb] state = in AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) for round = Nr-1 step -1 downto 1 InvShiftRows(state) InvSubBytes(state) AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) InvMixColumns(state) end for InvShiftRows(state) InvSubBytes(state) AddRoundKey(state, w[0, Nb-1]) out = state end */ // Encrypt: AddRoundKey(state, w[0, Nb-1]) // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) var Nr = w.length / 4 - 1; var m0, m1, m2, m3, sub; if(decrypt) { m0 = imix[0]; m1 = imix[1]; m2 = imix[2]; m3 = imix[3]; sub = isbox; } else { m0 = mix[0]; m1 = mix[1]; m2 = mix[2]; m3 = mix[3]; sub = sbox; } var a, b, c, d, a2, b2, c2; a = input[0] ^ w[0]; b = input[decrypt ? 3 : 1] ^ w[1]; c = input[2] ^ w[2]; d = input[decrypt ? 1 : 3] ^ w[3]; var i = 3; /* In order to share code we follow the encryption algorithm when both encrypting and decrypting. To account for the changes required in the decryption algorithm, we use different lookup tables when decrypting and use a modified key schedule to account for the difference in the order of transformations applied when performing rounds. We also get key rounds in reverse order (relative to encryption). */ for(var round = 1; round < Nr; ++round) { /* As described above, we'll be using table lookups to perform the column mixing. Each column is stored as a word in the state (the array 'input' has one column as a word at each index). In order to mix a column, we perform these transformations on each row in c, which is 1 byte in each word. The new column for c0 is c'0: m0 m1 m2 m3 r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0 r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0 r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0 r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0 So using mix tables where c0 is a word with r0 being its upper 8 bits and r3 being its lower 8 bits: m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0] ... m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3] Therefore to mix the columns in each word in the state we do the following (& 255 omitted for brevity): c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] However, before mixing, the algorithm requires us to perform ShiftRows(). The ShiftRows() transformation cyclically shifts the last 3 rows of the state over different offsets. The first row (r = 0) is not shifted. s'_r,c = s_r,(c + shift(r, Nb) mod Nb for 0 < r < 4 and 0 <= c < Nb and shift(1, 4) = 1 shift(2, 4) = 2 shift(3, 4) = 3. This causes the first byte in r = 1 to be moved to the end of the row, the first 2 bytes in r = 2 to be moved to the end of the row, the first 3 bytes in r = 3 to be moved to the end of the row: r1: [c0 c1 c2 c3] => [c1 c2 c3 c0] r2: [c0 c1 c2 c3] [c2 c3 c0 c1] r3: [c0 c1 c2 c3] [c3 c0 c1 c2] We can make these substitutions inline with our column mixing to generate an updated set of equations to produce each word in the state (note the columns have changed positions): c0 c1 c2 c3 => c0 c1 c2 c3 c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte) c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes) c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes) Therefore: c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3 c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3 c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3 c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3 c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0 c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0 c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0 c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0 ... and so forth for c'2 and c'3. The important distinction is that the columns are cycling, with c0 being used with the m0 map when calculating c0, but c1 being used with the m0 map when calculating c1 ... and so forth. When performing the inverse we transform the mirror image and skip the bottom row, instead of the top one, and move upwards: c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes) c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption c3 c2 c1 c0 c3 c2 c1 c0 If you compare the resulting matrices for ShiftRows()+MixColumns() and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are different (in encrypt mode vs. decrypt mode). So in order to use the same code to handle both encryption and decryption, we will need to do some mapping. If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be a row number in the state, then the resulting matrix in encryption mode for applying the above transformations would be: r1: a b c d r2: b c d a r3: c d a b r4: d a b c If we did the same in decryption mode we would get: r1: a d c b r2: b a d c r3: c b a d r4: d c b a If instead we swap d and b (set b=c3 and d=c1), then we get: r1: a b c d r2: d a b c r3: c d a b r4: b c d a Now the 1st and 3rd rows are the same as the encryption matrix. All we need to do then to make the mapping exactly the same is to swap the 2nd and 4th rows when in decryption mode. To do this without having to do it on each iteration, we swapped the 2nd and 4th rows in the decryption key schedule. We also have to do the swap above when we first pull in the input and when we set the final output. */ a2 = m0[a >>> 24] ^ m1[b >>> 16 & 255] ^ m2[c >>> 8 & 255] ^ m3[d & 255] ^ w[++i]; b2 = m0[b >>> 24] ^ m1[c >>> 16 & 255] ^ m2[d >>> 8 & 255] ^ m3[a & 255] ^ w[++i]; c2 = m0[c >>> 24] ^ m1[d >>> 16 & 255] ^ m2[a >>> 8 & 255] ^ m3[b & 255] ^ w[++i]; d = m0[d >>> 24] ^ m1[a >>> 16 & 255] ^ m2[b >>> 8 & 255] ^ m3[c & 255] ^ w[++i]; a = a2; b = b2; c = c2; } /* Encrypt: SubBytes(state) ShiftRows(state) AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) Decrypt: InvShiftRows(state) InvSubBytes(state) AddRoundKey(state, w[0, Nb-1]) */ // Note: rows are shifted inline output[0] = (sub[a >>> 24] << 24) ^ (sub[b >>> 16 & 255] << 16) ^ (sub[c >>> 8 & 255] << 8) ^ (sub[d & 255]) ^ w[++i]; output[decrypt ? 3 : 1] = (sub[b >>> 24] << 24) ^ (sub[c >>> 16 & 255] << 16) ^ (sub[d >>> 8 & 255] << 8) ^ (sub[a & 255]) ^ w[++i]; output[2] = (sub[c >>> 24] << 24) ^ (sub[d >>> 16 & 255] << 16) ^ (sub[a >>> 8 & 255] << 8) ^ (sub[b & 255]) ^ w[++i]; output[decrypt ? 1 : 3] = (sub[d >>> 24] << 24) ^ (sub[a >>> 16 & 255] << 16) ^ (sub[b >>> 8 & 255] << 8) ^ (sub[c & 255]) ^ w[++i]; } /** * Deprecated. Instead, use: * * forge.cipher.createCipher('AES-', key); * forge.cipher.createDecipher('AES-', key); * * Creates a deprecated AES cipher object. This object's mode will default to * CBC (cipher-block-chaining). * * The key and iv may be given as a string of bytes, an array of bytes, a * byte buffer, or an array of 32-bit words. * * @param options the options to use. * key the symmetric key to use. * output the buffer to write to. * decrypt true for decryption, false for encryption. * mode the cipher mode to use (default: 'CBC'). * * @return the cipher. */ function _createCipher(options) { options = options || {}; var mode = (options.mode || 'CBC').toUpperCase(); var algorithm = 'AES-' + mode; var cipher; if(options.decrypt) { cipher = forge.cipher.createDecipher(algorithm, options.key); } else { cipher = forge.cipher.createCipher(algorithm, options.key); } // backwards compatible start API var start = cipher.start; cipher.start = function(iv, options) { // backwards compatibility: support second arg as output buffer var output = null; if(options instanceof forge.util.ByteBuffer) { output = options; options = {}; } options = options || {}; options.output = output; options.iv = iv; start.call(cipher, options); }; return cipher; } /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { /** * Object IDs for ASN.1. * * @author Dave Longley * * Copyright (c) 2010-2013 Digital Bazaar, Inc. */ var forge = __webpack_require__(0); forge.pki = forge.pki || {}; var oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {}; // set id to name mapping and name to id mapping function _IN(id, name) { oids[id] = name; oids[name] = id; } // set id to name mapping only function _I_(id, name) { oids[id] = name; } // algorithm OIDs _IN('1.2.840.113549.1.1.1', 'rsaEncryption'); // Note: md2 & md4 not implemented //_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption'); //_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption'); _IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption'); _IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption'); _IN('1.2.840.113549.1.1.7', 'RSAES-OAEP'); _IN('1.2.840.113549.1.1.8', 'mgf1'); _IN('1.2.840.113549.1.1.9', 'pSpecified'); _IN('1.2.840.113549.1.1.10', 'RSASSA-PSS'); _IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption'); _IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption'); _IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption'); _IN('1.3.14.3.2.7', 'desCBC'); _IN('1.3.14.3.2.26', 'sha1'); _IN('2.16.840.1.101.3.4.2.1', 'sha256'); _IN('2.16.840.1.101.3.4.2.2', 'sha384'); _IN('2.16.840.1.101.3.4.2.3', 'sha512'); _IN('1.2.840.113549.2.5', 'md5'); // pkcs#7 content types _IN('1.2.840.113549.1.7.1', 'data'); _IN('1.2.840.113549.1.7.2', 'signedData'); _IN('1.2.840.113549.1.7.3', 'envelopedData'); _IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData'); _IN('1.2.840.113549.1.7.5', 'digestedData'); _IN('1.2.840.113549.1.7.6', 'encryptedData'); // pkcs#9 oids _IN('1.2.840.113549.1.9.1', 'emailAddress'); _IN('1.2.840.113549.1.9.2', 'unstructuredName'); _IN('1.2.840.113549.1.9.3', 'contentType'); _IN('1.2.840.113549.1.9.4', 'messageDigest'); _IN('1.2.840.113549.1.9.5', 'signingTime'); _IN('1.2.840.113549.1.9.6', 'counterSignature'); _IN('1.2.840.113549.1.9.7', 'challengePassword'); _IN('1.2.840.113549.1.9.8', 'unstructuredAddress'); _IN('1.2.840.113549.1.9.14', 'extensionRequest'); _IN('1.2.840.113549.1.9.20', 'friendlyName'); _IN('1.2.840.113549.1.9.21', 'localKeyId'); _IN('1.2.840.113549.1.9.22.1', 'x509Certificate'); // pkcs#12 safe bags _IN('1.2.840.113549.1.12.10.1.1', 'keyBag'); _IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag'); _IN('1.2.840.113549.1.12.10.1.3', 'certBag'); _IN('1.2.840.113549.1.12.10.1.4', 'crlBag'); _IN('1.2.840.113549.1.12.10.1.5', 'secretBag'); _IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag'); // password-based-encryption for pkcs#12 _IN('1.2.840.113549.1.5.13', 'pkcs5PBES2'); _IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2'); _IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4'); _IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4'); _IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC'); _IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC'); _IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC'); _IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC'); // hmac OIDs _IN('1.2.840.113549.2.7', 'hmacWithSHA1'); _IN('1.2.840.113549.2.8', 'hmacWithSHA224'); _IN('1.2.840.113549.2.9', 'hmacWithSHA256'); _IN('1.2.840.113549.2.10', 'hmacWithSHA384'); _IN('1.2.840.113549.2.11', 'hmacWithSHA512'); // symmetric key algorithm oids _IN('1.2.840.113549.3.7', 'des-EDE3-CBC'); _IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC'); _IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC'); _IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC'); // certificate issuer/subject OIDs _IN('2.5.4.3', 'commonName'); _IN('2.5.4.5', 'serialName'); _IN('2.5.4.6', 'countryName'); _IN('2.5.4.7', 'localityName'); _IN('2.5.4.8', 'stateOrProvinceName'); _IN('2.5.4.10', 'organizationName'); _IN('2.5.4.11', 'organizationalUnitName'); // X.509 extension OIDs _IN('2.16.840.1.113730.1.1', 'nsCertType'); _I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35 _I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15 _I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32 _I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15 _I_('2.5.29.5', 'policyMapping'); // deprecated use .33 _I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30 _I_('2.5.29.7', 'subjectAltName'); // deprecated use .17 _I_('2.5.29.8', 'issuerAltName'); // deprecated use .18 _I_('2.5.29.9', 'subjectDirectoryAttributes'); _I_('2.5.29.10', 'basicConstraints'); // deprecated use .19 _I_('2.5.29.11', 'nameConstraints'); // deprecated use .30 _I_('2.5.29.12', 'policyConstraints'); // deprecated use .36 _I_('2.5.29.13', 'basicConstraints'); // deprecated use .19 _IN('2.5.29.14', 'subjectKeyIdentifier'); _IN('2.5.29.15', 'keyUsage'); _I_('2.5.29.16', 'privateKeyUsagePeriod'); _IN('2.5.29.17', 'subjectAltName'); _IN('2.5.29.18', 'issuerAltName'); _IN('2.5.29.19', 'basicConstraints'); _I_('2.5.29.20', 'cRLNumber'); _I_('2.5.29.21', 'cRLReason'); _I_('2.5.29.22', 'expirationDate'); _I_('2.5.29.23', 'instructionCode'); _I_('2.5.29.24', 'invalidityDate'); _I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31 _I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28 _I_('2.5.29.27', 'deltaCRLIndicator'); _I_('2.5.29.28', 'issuingDistributionPoint'); _I_('2.5.29.29', 'certificateIssuer'); _I_('2.5.29.30', 'nameConstraints'); _IN('2.5.29.31', 'cRLDistributionPoints'); _IN('2.5.29.32', 'certificatePolicies'); _I_('2.5.29.33', 'policyMappings'); _I_('2.5.29.34', 'policyConstraints'); // deprecated use .36 _IN('2.5.29.35', 'authorityKeyIdentifier'); _I_('2.5.29.36', 'policyConstraints'); _IN('2.5.29.37', 'extKeyUsage'); _I_('2.5.29.46', 'freshestCRL'); _I_('2.5.29.54', 'inhibitAnyPolicy'); // extKeyUsage purposes _IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList'); _IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess'); _IN('1.3.6.1.5.5.7.3.1', 'serverAuth'); _IN('1.3.6.1.5.5.7.3.2', 'clientAuth'); _IN('1.3.6.1.5.5.7.3.3', 'codeSigning'); _IN('1.3.6.1.5.5.7.3.4', 'emailProtection'); _IN('1.3.6.1.5.5.7.3.8', 'timeStamping'); /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. /* Licensing (LICENSE) ------------------- This software is covered under the following copyright: */ /* * Copyright (c) 2003-2005 Tom Wu * All Rights Reserved. * * 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" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * In addition, the following condition applies: * * All redistributions must retain an intact copy of this copyright notice * and disclaimer. */ /* Address all questions regarding this license to: Tom Wu tjw@cs.Stanford.EDU */ var forge = __webpack_require__(0); module.exports = forge.jsbn = forge.jsbn || {}; // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { this.data = []; if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } forge.jsbn.BigInteger = BigInteger; // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this.data[i++]+w.data[j]+c; c = Math.floor(v/0x4000000); w.data[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this.data[i]&0x7fff; var h = this.data[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w.data[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this.data[i]&0x3fff; var h = this.data[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w.data[j]+c; c = (l>>28)+(m>>14)+xh*h; w.data[j++] = l&0xfffffff; } return c; } // node.js (no browser) if(typeof(navigator) === 'undefined') { BigInteger.prototype.am = am3; dbits = 28; } else if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<= 0; --i) r.data[i] = this.data[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this.data[0] = x; else if(x < -1) this.data[0] = x+this.DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this.data[this.t++] = x; else if(sh+k > this.DB) { this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); } else this.data[this.t-1] |= x<= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1< 0) { if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); } while(i >= 0) { if(p < k) { d = (this.data[i]&((1<>(p+=this.DB-k); } else { d = (this.data[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r += int2char(d); } } return m?r:"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return (this.s<0)?-r:r; while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i]; for(i = n-1; i >= 0; --i) r.data[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<= 0; --i) { r.data[i+ds+1] = (this.data[i]>>cbs)|c; c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0; r.data[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<>bs; for(var i = ds+1; i < this.t; ++i) { r.data[i-ds-1] |= (this.data[i]&bm)<>bs; } if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this.data[i]; r.data[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a.data[i]; r.data[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r.data[i++] = this.DV+c; else if(c > 0) r.data[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r.data[i] = 0; for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r.data[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x.data[i],r,2*i,0,1); if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r.data[i+x.t] -= x.DV; r.data[i+x.t+1] = 1; } } if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm.data[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y.data[ys-1]; if(y0 == 0) return; var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<= 0) { r.data[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y.data[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2); if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r.data[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this.data[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x.data[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x.data[i]*mp mod DV var j = x.data[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x.data[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; } } x.clamp(); x.drShiftTo(this.m.t,x); if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = "x^2/R mod m"; x != r function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (protected) true iff this is even function bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e,z) { if(e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; g.copyTo(r); while(--i >= 0) { z.sqrTo(r,r2); if((e&(1< 0) z.mulTo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e,m) { var z; if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e,z); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.isEven = bnpIsEven; BigInteger.prototype.exp = bnpExp; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.modPowInt = bnModPowInt; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // jsbn2 lib //Copyright (c) 2005-2009 Tom Wu //All Rights Reserved. //See "LICENSE" for details (See jsbn.js for LICENSE). //Extended JavaScript BN functions, required for RSA private ops. //Version 1.1: new BigInteger("0", 10) returns "proper" zero //(public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } //(public) return value as integer function bnIntValue() { if(this.s < 0) { if(this.t == 1) return this.data[0]-this.DV; else if(this.t == 0) return -1; } else if(this.t == 1) return this.data[0]; else if(this.t == 0) return 0; // assumes 16 < DB < 32 return ((this.data[1]&((1<<(32-this.DB))-1))<>24; } //(public) return value as short (assumes DB>=16) function bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; } //(protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } //(public) 0 if this == 0, 1 if this > 0 function bnSigNum() { if(this.s < 0) return -1; else if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0; else return 1; } //(protected) convert to radix string function bnpToRadix(b) { if(b == null) b = 10; if(this.signum() == 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); var a = Math.pow(b,cs); var d = nbv(a), y = nbi(), z = nbi(), r = ""; this.divRemTo(d,y,z); while(y.signum() > 0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } //(protected) convert from radix string function bnpFromRadix(s,b) { this.fromInt(0); if(b == null) b = 10; var cs = this.chunkSize(b); var d = Math.pow(b,cs), mi = false, j = 0, w = 0; for(var i = 0; i < s.length; ++i) { var x = intAt(s,i); if(x < 0) { if(s.charAt(i) == "-" && this.signum() == 0) mi = true; continue; } w = b*w+x; if(++j >= cs) { this.dMultiply(d); this.dAddOffset(w,0); j = 0; w = 0; } } if(j > 0) { this.dMultiply(Math.pow(b,j)); this.dAddOffset(w,0); } if(mi) BigInteger.ZERO.subTo(this,this); } //(protected) alternate constructor function bnpFromNumber(a,b,c) { if("number" == typeof b) { // new BigInteger(int,int,RNG) if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); if(!this.testBit(a-1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); if(this.isEven()) this.dAddOffset(1,0); // force odd while(!this.isProbablePrime(b)) { this.dAddOffset(2,0); if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); } } } else { // new BigInteger(int,RNG) var x = new Array(), t = a&7; x.length = (a>>3)+1; b.nextBytes(x); if(t > 0) x[0] &= ((1< 0) { if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p) r[k++] = d|(this.s<<(this.DB-p)); while(i >= 0) { if(p < 8) { d = (this.data[i]&((1<>(p+=this.DB-8); } else { d = (this.data[i]>>(p-=8))&0xff; if(p <= 0) { p += this.DB; --i; } } if((d&0x80) != 0) d |= -256; if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; if(k > 0 || d != this.s) r[k++] = d; } } return r; } function bnEquals(a) { return(this.compareTo(a)==0); } function bnMin(a) { return(this.compareTo(a)<0)?this:a; } function bnMax(a) { return(this.compareTo(a)>0)?this:a; } //(protected) r = this op a (bitwise) function bnpBitwiseTo(a,op,r) { var i, f, m = Math.min(a.t,this.t); for(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]); if(a.t < this.t) { f = a.s&this.DM; for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f); r.t = this.t; } else { f = this.s&this.DM; for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]); r.t = a.t; } r.s = op(this.s,a.s); r.clamp(); } //(public) this & a function op_and(x,y) { return x&y; } function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } //(public) this | a function op_or(x,y) { return x|y; } function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } //(public) this ^ a function op_xor(x,y) { return x^y; } function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } //(public) this & ~a function op_andnot(x,y) { return x&~y; } function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } //(public) ~this function bnNot() { var r = nbi(); for(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i]; r.t = this.t; r.s = ~this.s; return r; } //(public) this << n function bnShiftLeft(n) { var r = nbi(); if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); return r; } //(public) this >> n function bnShiftRight(n) { var r = nbi(); if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); return r; } //return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if(x == 0) return -1; var r = 0; if((x&0xffff) == 0) { x >>= 16; r += 16; } if((x&0xff) == 0) { x >>= 8; r += 8; } if((x&0xf) == 0) { x >>= 4; r += 4; } if((x&3) == 0) { x >>= 2; r += 2; } if((x&1) == 0) ++r; return r; } //(public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for(var i = 0; i < this.t; ++i) if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]); if(this.s < 0) return this.t*this.DB; return -1; } //return number of 1 bits in x function cbit(x) { var r = 0; while(x != 0) { x &= x-1; ++r; } return r; } //(public) return number of set bits function bnBitCount() { var r = 0, x = this.s&this.DM; for(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x); return r; } //(public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n/this.DB); if(j >= this.t) return(this.s!=0); return((this.data[j]&(1<<(n%this.DB)))!=0); } //(protected) this op (1<>= this.DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this.data[i]; r.data[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a.data[i]; r.data[i++] = c&this.DM; c >>= this.DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r.data[i++] = c; else if(c < -1) r.data[i++] = this.DV+c; r.t = i; r.clamp(); } //(public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } //(public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } //(public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } //(public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } //(public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } //(public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return new Array(q,r); } //(protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this.data[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } //(protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this.data[this.t++] = 0; this.data[w] += n; while(this.data[w] >= this.DV) { this.data[w] -= this.DV; if(++w >= this.t) this.data[this.t++] = 0; ++this.data[w]; } } //A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; //(public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } //(protected) r = lower n words of "this * a", a.t <= n //"this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r.data[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i); r.clamp(); } //(protected) r = "this * a" without lower n words, n > 0 //"this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r.data[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } //Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } //x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } //r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } //r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; //(public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e.data[j])-1; while(j >= 0) { if(i >= k1) w = (e.data[j]>>(i-k1))&km; else { w = (e.data[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e.data[j]&(1< 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } //(protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this.data[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n; return r; } //(public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; //(public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x.data[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } //(protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); var prng = bnGetPrng(); var a; for(var i = 0; i < t; ++i) { // select witness 'a' at random from between 1 and n1 do { a = new BigInteger(this.bitLength(), prng); } while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // get pseudo random number generator function bnGetPrng() { // create prng with api that matches BigInteger secure random return { // x is an array to fill with bytes nextBytes: function(x) { for(var i = 0; i < x.length; ++i) { x[i] = Math.floor(Math.random() * 0x0100); } } }; } //protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; //public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; //BigInteger interfaces not implemented in jsbn: //BigInteger(int signum, byte[] magnitude) //double doubleValue() //float floatValue() //int hashCode() //long longValue() //static BigInteger valueOf(long val) /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { /** * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation. * * See FIPS 180-2 for details. * * @author Dave Longley * * Copyright (c) 2010-2015 Digital Bazaar, Inc. */ var forge = __webpack_require__(0); __webpack_require__(2); __webpack_require__(1); var sha256 = module.exports = forge.sha256 = forge.sha256 || {}; forge.md.sha256 = forge.md.algorithms.sha256 = sha256; /** * Creates a SHA-256 message digest object. * * @return a message digest object. */ sha256.create = function() { // do initialization as necessary if(!_initialized) { _init(); } // SHA-256 state contains eight 32-bit integers var _state = null; // input buffer var _input = forge.util.createBuffer(); // used for word storage var _w = new Array(64); // message digest object var md = { algorithm: 'sha256', blockLength: 64, digestLength: 32, // 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: 8 }; /** * 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.messageLength64 for backwards-compatibility) md.fullMessageLength = md.messageLength64 = []; var int32s = md.messageLengthSize / 4; for(var i = 0; i < int32s; ++i) { md.fullMessageLength.push(0); } _input = forge.util.createBuffer(); _state = { h0: 0x6A09E667, h1: 0xBB67AE85, h2: 0x3C6EF372, h3: 0xA54FF53A, h4: 0x510E527F, h5: 0x9B05688C, h6: 0x1F83D9AB, h7: 0x5BE0CD19 }; 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(_state, _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-256 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 448 mod 512. In other words, the data to be digested must be a multiple of 512 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 8 bytes (64 bits), that means that the last segment of the data must have 56 bytes (448 bits) of message and padding. Therefore, the length of the message plus the padding must be congruent to 448 mod 512 because 512 - 128 = 448. 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 448 mod 512, then 512 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 next, carry; var bits = md.fullMessageLength[0] * 8; for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { next = md.fullMessageLength[i + 1] * 8; carry = (next / 0x100000000) >>> 0; bits += carry; finalBlock.putInt32(bits >>> 0); bits = next >>> 0; } finalBlock.putInt32(bits); var s2 = { h0: _state.h0, h1: _state.h1, h2: _state.h2, h3: _state.h3, h4: _state.h4, h5: _state.h5, h6: _state.h6, h7: _state.h7 }; _update(s2, _w, finalBlock); var rval = forge.util.createBuffer(); rval.putInt32(s2.h0); rval.putInt32(s2.h1); rval.putInt32(s2.h2); rval.putInt32(s2.h3); rval.putInt32(s2.h4); rval.putInt32(s2.h5); rval.putInt32(s2.h6); rval.putInt32(s2.h7); return rval; }; return md; }; // sha-256 padding bytes not initialized yet var _padding = null; var _initialized = false; // table of constants var _k = null; /** * Initializes the constant tables. */ function _init() { // create padding _padding = String.fromCharCode(128); _padding += forge.util.fillString(String.fromCharCode(0x00), 64); // create K table for SHA-256 _k = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]; // now initialized _initialized = true; } /** * Updates a SHA-256 state with the given byte buffer. * * @param s the SHA-256 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 (64 byte) chunks var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; var len = bytes.length(); while(len >= 64) { // the w array will be populated with sixteen 32-bit big-endian words // and then extended into 64 32-bit words according to SHA-256 for(i = 0; i < 16; ++i) { w[i] = bytes.getInt32(); } for(; i < 64; ++i) { // XOR word 2 words ago rot right 17, rot right 19, shft right 10 t1 = w[i - 2]; t1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10); // XOR word 15 words ago rot right 7, rot right 18, shft right 3 t2 = w[i - 15]; t2 = ((t2 >>> 7) | (t2 << 25)) ^ ((t2 >>> 18) | (t2 << 14)) ^ (t2 >>> 3); // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32 w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0; } // initialize hash value for this chunk a = s.h0; b = s.h1; c = s.h2; d = s.h3; e = s.h4; f = s.h5; g = s.h6; h = s.h7; // round function for(i = 0; i < 64; ++i) { // Sum1(e) s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); // Ch(e, f, g) (optimized the same way as SHA-1) ch = g ^ (e & (f ^ g)); // Sum0(a) s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); // Maj(a, b, c) (optimized the same way as SHA-1) maj = (a & b) | (c & (a ^ b)); // main algorithm t1 = h + s1 + ch + _k[i] + w[i]; t2 = s0 + maj; h = g; g = f; f = e; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug // can't truncate with `| 0` e = (d + t1) >>> 0; d = c; c = b; b = a; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug // can't truncate with `| 0` a = (t1 + t2) >>> 0; } // update hash state s.h0 = (s.h0 + a) | 0; s.h1 = (s.h1 + b) | 0; s.h2 = (s.h2 + c) | 0; s.h3 = (s.h3 + d) | 0; s.h4 = (s.h4 + e) | 0; s.h5 = (s.h5 + f) | 0; s.h6 = (s.h6 + g) | 0; s.h7 = (s.h7 + h) | 0; len -= 64; } } /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(11); __webpack_require__(6); __webpack_require__(14); __webpack_require__(4); __webpack_require__(9); __webpack_require__(3); module.exports = __webpack_require__(0); /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { /** * Password-Based Key-Derivation Function #2 implementation. * * See RFC 2898 for details. * * @author Dave Longley * * Copyright (c) 2010-2013 Digital Bazaar, Inc. */ var forge = __webpack_require__(0); __webpack_require__(4); __webpack_require__(2); __webpack_require__(1); var pkcs5 = forge.pkcs5 = forge.pkcs5 || {}; var crypto; if(forge.util.isNodejs && !forge.options.usePureJavaScript) { crypto = __webpack_require__(5); } /** * Derives a key from a password. * * @param p the password as a binary-encoded string of bytes. * @param s the salt as a binary-encoded string of bytes. * @param c the iteration count, a positive integer. * @param dkLen the intended length, in bytes, of the derived key, * (max: 2^32 - 1) * hash length of the PRF. * @param [md] the message digest (or algorithm identifier as a string) to use * in the PRF, defaults to SHA-1. * @param [callback(err, key)] presence triggers asynchronous version, called * once the operation completes. * * @return the derived key, as a binary-encoded string of bytes, for the * synchronous version (if no callback is specified). */ module.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function( p, s, c, dkLen, md, callback) { if(typeof md === 'function') { callback = md; md = null; } // use native implementation if possible and not disabled, note that // some node versions only support SHA-1, others allow digest to be changed if(forge.util.isNodejs && !forge.options.usePureJavaScript && crypto.pbkdf2 && (md === null || typeof md !== 'object') && (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) { if(typeof md !== 'string') { // default prf to SHA-1 md = 'sha1'; } p = new Buffer(p, 'binary'); s = new Buffer(s, 'binary'); if(!callback) { if(crypto.pbkdf2Sync.length === 4) { return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary'); } return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary'); } if(crypto.pbkdf2Sync.length === 4) { return crypto.pbkdf2(p, s, c, dkLen, function(err, key) { if(err) { return callback(err); } callback(null, key.toString('binary')); }); } return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) { if(err) { return callback(err); } callback(null, key.toString('binary')); }); } if(typeof md === 'undefined' || md === null) { // default prf to SHA-1 md = 'sha1'; } if(typeof md === 'string') { if(!(md in forge.md.algorithms)) { throw new Error('Unknown hash algorithm: ' + md); } md = forge.md[md].create(); } var hLen = md.digestLength; /* 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and stop. */ if(dkLen > (0xFFFFFFFF * hLen)) { var err = new Error('Derived key is too long.'); if(callback) { return callback(err); } throw err; } /* 2. Let len be the number of hLen-octet blocks in the derived key, rounding up, and let r be the number of octets in the last block: len = CEIL(dkLen / hLen), r = dkLen - (len - 1) * hLen. */ var len = Math.ceil(dkLen / hLen); var r = dkLen - (len - 1) * hLen; /* 3. For each block of the derived key apply the function F defined below to the password P, the salt S, the iteration count c, and the block index to compute the block: T_1 = F(P, S, c, 1), T_2 = F(P, S, c, 2), ... T_len = F(P, S, c, len), where the function F is defined as the exclusive-or sum of the first c iterates of the underlying pseudorandom function PRF applied to the password P and the concatenation of the salt S and the block index i: F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c where u_1 = PRF(P, S || INT(i)), u_2 = PRF(P, u_1), ... u_c = PRF(P, u_{c-1}). Here, INT(i) is a four-octet encoding of the integer i, most significant octet first. */ var prf = forge.hmac.create(); prf.start(md, p); var dk = ''; var xor, u_c, u_c1; // sync version if(!callback) { for(var i = 1; i <= len; ++i) { // PRF(P, S || INT(i)) (first iteration) prf.start(null, null); prf.update(s); prf.update(forge.util.int32ToBytes(i)); xor = u_c1 = prf.digest().getBytes(); // PRF(P, u_{c-1}) (other iterations) for(var j = 2; j <= c; ++j) { prf.start(null, null); prf.update(u_c1); u_c = prf.digest().getBytes(); // F(p, s, c, i) xor = forge.util.xorBytes(xor, u_c, hLen); u_c1 = u_c; } /* 4. Concatenate the blocks and extract the first dkLen octets to produce a derived key DK: DK = T_1 || T_2 || ... || T_len<0..r-1> */ dk += (i < len) ? xor : xor.substr(0, r); } /* 5. Output the derived key DK. */ return dk; } // async version var i = 1, j; function outer() { if(i > len) { // done return callback(null, dk); } // PRF(P, S || INT(i)) (first iteration) prf.start(null, null); prf.update(s); prf.update(forge.util.int32ToBytes(i)); xor = u_c1 = prf.digest().getBytes(); // PRF(P, u_{c-1}) (other iterations) j = 2; inner(); } function inner() { if(j <= c) { prf.start(null, null); prf.update(u_c1); u_c = prf.digest().getBytes(); // F(p, s, c, i) xor = forge.util.xorBytes(xor, u_c, hLen); u_c1 = u_c; ++j; return forge.util.setImmediate(inner); } /* 4. Concatenate the blocks and extract the first dkLen octets to produce a derived key DK: DK = T_1 || T_2 || ... || T_len<0..r-1> */ dk += (i < len) ? xor : xor.substr(0, r); ++i; outer(); } outer(); }; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { /** * Cipher base API. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. */ var forge = __webpack_require__(0); __webpack_require__(1); module.exports = forge.cipher = forge.cipher || {}; // registered algorithms forge.cipher.algorithms = forge.cipher.algorithms || {}; /** * Creates a cipher object that can be used to encrypt data using the given * algorithm and key. The algorithm may be provided as a string value for a * previously registered algorithm or it may be given as a cipher algorithm * API object. * * @param algorithm the algorithm to use, either a string or an algorithm API * object. * @param key the key to use, as a binary-encoded string of bytes or a * byte buffer. * * @return the cipher. */ forge.cipher.createCipher = function(algorithm, key) { var api = algorithm; if(typeof api === 'string') { api = forge.cipher.getAlgorithm(api); if(api) { api = api(); } } if(!api) { throw new Error('Unsupported algorithm: ' + algorithm); } // assume block cipher return new forge.cipher.BlockCipher({ algorithm: api, key: key, decrypt: false }); }; /** * Creates a decipher object that can be used to decrypt data using the given * algorithm and key. The algorithm may be provided as a string value for a * previously registered algorithm or it may be given as a cipher algorithm * API object. * * @param algorithm the algorithm to use, either a string or an algorithm API * object. * @param key the key to use, as a binary-encoded string of bytes or a * byte buffer. * * @return the cipher. */ forge.cipher.createDecipher = function(algorithm, key) { var api = algorithm; if(typeof api === 'string') { api = forge.cipher.getAlgorithm(api); if(api) { api = api(); } } if(!api) { throw new Error('Unsupported algorithm: ' + algorithm); } // assume block cipher return new forge.cipher.BlockCipher({ algorithm: api, key: key, decrypt: true }); }; /** * Registers an algorithm by name. If the name was already registered, the * algorithm API object will be overwritten. * * @param name the name of the algorithm. * @param algorithm the algorithm API object. */ forge.cipher.registerAlgorithm = function(name, algorithm) { name = name.toUpperCase(); forge.cipher.algorithms[name] = algorithm; }; /** * Gets a registered algorithm by name. * * @param name the name of the algorithm. * * @return the algorithm, if found, null if not. */ forge.cipher.getAlgorithm = function(name) { name = name.toUpperCase(); if(name in forge.cipher.algorithms) { return forge.cipher.algorithms[name]; } return null; }; var BlockCipher = forge.cipher.BlockCipher = function(options) { this.algorithm = options.algorithm; this.mode = this.algorithm.mode; this.blockSize = this.mode.blockSize; this._finish = false; this._input = null; this.output = null; this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; this._decrypt = options.decrypt; this.algorithm.initialize(options); }; /** * Starts or restarts the encryption or decryption process, whichever * was previously configured. * * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in * bytes, then it must be Nb (16) bytes in length. If the IV is given in as * 32-bit integers, then it must be 4 integers long. * * Note: an IV is not required or used in ECB mode. * * For GCM-mode, the IV must be given as a binary-encoded string of bytes or * a byte buffer. The number of bytes should be 12 (96 bits) as recommended * by NIST SP-800-38D but another length may be given. * * @param options the options to use: * iv the initialization vector to use as a binary-encoded string of * bytes, null to reuse the last ciphered block from a previous * update() (this "residue" method is for legacy support only). * additionalData additional authentication data as a binary-encoded * string of bytes, for 'GCM' mode, (default: none). * tagLength desired length of authentication tag, in bits, for * 'GCM' mode (0-128, default: 128). * tag the authentication tag to check if decrypting, as a * binary-encoded string of bytes. * output the output the buffer to write to, null to create one. */ BlockCipher.prototype.start = function(options) { options = options || {}; var opts = {}; for(var key in options) { opts[key] = options[key]; } opts.decrypt = this._decrypt; this._finish = false; this._input = forge.util.createBuffer(); this.output = options.output || forge.util.createBuffer(); this.mode.start(opts); }; /** * Updates the next block according to the cipher mode. * * @param input the buffer to read from. */ BlockCipher.prototype.update = function(input) { if(input) { // input given, so empty it into the input buffer this._input.putBuffer(input); } // do cipher operation until it needs more input and not finished while(!this._op.call(this.mode, this._input, this.output, this._finish) && !this._finish) {} // free consumed memory from input buffer this._input.compact(); }; /** * Finishes encrypting or decrypting. * * @param pad a padding function to use in CBC mode, null for default, * signature(blockSize, buffer, decrypt). * * @return true if successful, false on error. */ BlockCipher.prototype.finish = function(pad) { // backwards-compatibility w/deprecated padding API // Note: will overwrite padding functions even after another start() call if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) { this.mode.pad = function(input) { return pad(this.blockSize, input, false); }; this.mode.unpad = function(output) { return pad(this.blockSize, output, true); }; } // build options for padding and afterFinish functions var options = {}; options.decrypt = this._decrypt; // get # of bytes that won't fill a block options.overflow = this._input.length() % this.blockSize; if(!this._decrypt && this.mode.pad) { if(!this.mode.pad(this._input, options)) { return false; } } // do final update this._finish = true; this.update(); if(this._decrypt && this.mode.unpad) { if(!this.mode.unpad(this.output, options)) { return false; } } if(this.mode.afterFinish) { if(!this.mode.afterFinish(this.output, options)) { return false; } } return true; }; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { /** * Supported cipher modes. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. */ var forge = __webpack_require__(0); __webpack_require__(1); forge.cipher = forge.cipher || {}; // supported cipher modes var modes = module.exports = forge.cipher.modes = forge.cipher.modes || {}; /** Electronic codebook (ECB) (Don't use this; it's not secure) **/ modes.ecb = function(options) { options = options || {}; this.name = 'ECB'; this.cipher = options.cipher; this.blockSize = options.blockSize || 16; this._ints = this.blockSize / 4; this._inBlock = new Array(this._ints); this._outBlock = new Array(this._ints); }; modes.ecb.prototype.start = function(options) {}; modes.ecb.prototype.encrypt = function(input, output, finish) { // not enough input to encrypt if(input.length() < this.blockSize && !(finish && input.length() > 0)) { return true; } // get next block for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = input.getInt32(); } // encrypt block this.cipher.encrypt(this._inBlock, this._outBlock); // write output for(var i = 0; i < this._ints; ++i) { output.putInt32(this._outBlock[i]); } }; modes.ecb.prototype.decrypt = function(input, output, finish) { // not enough input to decrypt if(input.length() < this.blockSize && !(finish && input.length() > 0)) { return true; } // get next block for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = input.getInt32(); } // decrypt block this.cipher.decrypt(this._inBlock, this._outBlock); // write output for(var i = 0; i < this._ints; ++i) { output.putInt32(this._outBlock[i]); } }; modes.ecb.prototype.pad = function(input, options) { // add PKCS#7 padding to block (each pad byte is the // value of the number of pad bytes) var padding = (input.length() === this.blockSize ? this.blockSize : (this.blockSize - input.length())); input.fillWithByte(padding, padding); return true; }; modes.ecb.prototype.unpad = function(output, options) { // check for error: input data not a multiple of blockSize if(options.overflow > 0) { return false; } // ensure padding byte count is valid var len = output.length(); var count = output.at(len - 1); if(count > (this.blockSize << 2)) { return false; } // trim off padding bytes output.truncate(count); return true; }; /** Cipher-block Chaining (CBC) **/ modes.cbc = function(options) { options = options || {}; this.name = 'CBC'; this.cipher = options.cipher; this.blockSize = options.blockSize || 16; this._ints = this.blockSize / 4; this._inBlock = new Array(this._ints); this._outBlock = new Array(this._ints); }; modes.cbc.prototype.start = function(options) { // Note: legacy support for using IV residue (has security flaws) // if IV is null, reuse block from previous processing if(options.iv === null) { // must have a previous block if(!this._prev) { throw new Error('Invalid IV parameter.'); } this._iv = this._prev.slice(0); } else if(!('iv' in options)) { throw new Error('Invalid IV parameter.'); } else { // save IV as "previous" block this._iv = transformIV(options.iv); this._prev = this._iv.slice(0); } }; modes.cbc.prototype.encrypt = function(input, output, finish) { // not enough input to encrypt if(input.length() < this.blockSize && !(finish && input.length() > 0)) { return true; } // get next block // CBC XOR's IV (or previous block) with plaintext for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = this._prev[i] ^ input.getInt32(); } // encrypt block this.cipher.encrypt(this._inBlock, this._outBlock); // write output, save previous block for(var i = 0; i < this._ints; ++i) { output.putInt32(this._outBlock[i]); } this._prev = this._outBlock; }; modes.cbc.prototype.decrypt = function(input, output, finish) { // not enough input to decrypt if(input.length() < this.blockSize && !(finish && input.length() > 0)) { return true; } // get next block for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = input.getInt32(); } // decrypt block this.cipher.decrypt(this._inBlock, this._outBlock); // write output, save previous ciphered block // CBC XOR's IV (or previous block) with ciphertext for(var i = 0; i < this._ints; ++i) { output.putInt32(this._prev[i] ^ this._outBlock[i]); } this._prev = this._inBlock.slice(0); }; modes.cbc.prototype.pad = function(input, options) { // add PKCS#7 padding to block (each pad byte is the // value of the number of pad bytes) var padding = (input.length() === this.blockSize ? this.blockSize : (this.blockSize - input.length())); input.fillWithByte(padding, padding); return true; }; modes.cbc.prototype.unpad = function(output, options) { // check for error: input data not a multiple of blockSize if(options.overflow > 0) { return false; } // ensure padding byte count is valid var len = output.length(); var count = output.at(len - 1); if(count > (this.blockSize << 2)) { return false; } // trim off padding bytes output.truncate(count); return true; }; /** Cipher feedback (CFB) **/ modes.cfb = function(options) { options = options || {}; this.name = 'CFB'; this.cipher = options.cipher; this.blockSize = options.blockSize || 16; this._ints = this.blockSize / 4; this._inBlock = null; this._outBlock = new Array(this._ints); this._partialBlock = new Array(this._ints); this._partialOutput = forge.util.createBuffer(); this._partialBytes = 0; }; modes.cfb.prototype.start = function(options) { if(!('iv' in options)) { throw new Error('Invalid IV parameter.'); } // use IV as first input this._iv = transformIV(options.iv); this._inBlock = this._iv.slice(0); this._partialBytes = 0; }; modes.cfb.prototype.encrypt = function(input, output, finish) { // not enough input to encrypt var inputLength = input.length(); if(inputLength === 0) { return true; } // encrypt block this.cipher.encrypt(this._inBlock, this._outBlock); // handle full block if(this._partialBytes === 0 && inputLength >= this.blockSize) { // XOR input with output, write input as output for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; output.putInt32(this._inBlock[i]); } return; } // handle partial block var partialBytes = (this.blockSize - inputLength) % this.blockSize; if(partialBytes > 0) { partialBytes = this.blockSize - partialBytes; } // XOR input with output, write input as partial output this._partialOutput.clear(); for(var i = 0; i < this._ints; ++i) { this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; this._partialOutput.putInt32(this._partialBlock[i]); } if(partialBytes > 0) { // block still incomplete, restore input buffer input.read -= this.blockSize; } else { // block complete, update input block for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = this._partialBlock[i]; } } // skip any previous partial bytes if(this._partialBytes > 0) { this._partialOutput.getBytes(this._partialBytes); } if(partialBytes > 0 && !finish) { output.putBytes(this._partialOutput.getBytes( partialBytes - this._partialBytes)); this._partialBytes = partialBytes; return true; } output.putBytes(this._partialOutput.getBytes( inputLength - this._partialBytes)); this._partialBytes = 0; }; modes.cfb.prototype.decrypt = function(input, output, finish) { // not enough input to decrypt var inputLength = input.length(); if(inputLength === 0) { return true; } // encrypt block (CFB always uses encryption mode) this.cipher.encrypt(this._inBlock, this._outBlock); // handle full block if(this._partialBytes === 0 && inputLength >= this.blockSize) { // XOR input with output, write input as output for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = input.getInt32(); output.putInt32(this._inBlock[i] ^ this._outBlock[i]); } return; } // handle partial block var partialBytes = (this.blockSize - inputLength) % this.blockSize; if(partialBytes > 0) { partialBytes = this.blockSize - partialBytes; } // XOR input with output, write input as partial output this._partialOutput.clear(); for(var i = 0; i < this._ints; ++i) { this._partialBlock[i] = input.getInt32(); this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); } if(partialBytes > 0) { // block still incomplete, restore input buffer input.read -= this.blockSize; } else { // block complete, update input block for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = this._partialBlock[i]; } } // skip any previous partial bytes if(this._partialBytes > 0) { this._partialOutput.getBytes(this._partialBytes); } if(partialBytes > 0 && !finish) { output.putBytes(this._partialOutput.getBytes( partialBytes - this._partialBytes)); this._partialBytes = partialBytes; return true; } output.putBytes(this._partialOutput.getBytes( inputLength - this._partialBytes)); this._partialBytes = 0; }; /** Output feedback (OFB) **/ modes.ofb = function(options) { options = options || {}; this.name = 'OFB'; this.cipher = options.cipher; this.blockSize = options.blockSize || 16; this._ints = this.blockSize / 4; this._inBlock = null; this._outBlock = new Array(this._ints); this._partialOutput = forge.util.createBuffer(); this._partialBytes = 0; }; modes.ofb.prototype.start = function(options) { if(!('iv' in options)) { throw new Error('Invalid IV parameter.'); } // use IV as first input this._iv = transformIV(options.iv); this._inBlock = this._iv.slice(0); this._partialBytes = 0; }; modes.ofb.prototype.encrypt = function(input, output, finish) { // not enough input to encrypt var inputLength = input.length(); if(input.length() === 0) { return true; } // encrypt block (OFB always uses encryption mode) this.cipher.encrypt(this._inBlock, this._outBlock); // handle full block if(this._partialBytes === 0 && inputLength >= this.blockSize) { // XOR input with output and update next input for(var i = 0; i < this._ints; ++i) { output.putInt32(input.getInt32() ^ this._outBlock[i]); this._inBlock[i] = this._outBlock[i]; } return; } // handle partial block var partialBytes = (this.blockSize - inputLength) % this.blockSize; if(partialBytes > 0) { partialBytes = this.blockSize - partialBytes; } // XOR input with output this._partialOutput.clear(); for(var i = 0; i < this._ints; ++i) { this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); } if(partialBytes > 0) { // block still incomplete, restore input buffer input.read -= this.blockSize; } else { // block complete, update input block for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = this._outBlock[i]; } } // skip any previous partial bytes if(this._partialBytes > 0) { this._partialOutput.getBytes(this._partialBytes); } if(partialBytes > 0 && !finish) { output.putBytes(this._partialOutput.getBytes( partialBytes - this._partialBytes)); this._partialBytes = partialBytes; return true; } output.putBytes(this._partialOutput.getBytes( inputLength - this._partialBytes)); this._partialBytes = 0; }; modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; /** Counter (CTR) **/ modes.ctr = function(options) { options = options || {}; this.name = 'CTR'; this.cipher = options.cipher; this.blockSize = options.blockSize || 16; this._ints = this.blockSize / 4; this._inBlock = null; this._outBlock = new Array(this._ints); this._partialOutput = forge.util.createBuffer(); this._partialBytes = 0; }; modes.ctr.prototype.start = function(options) { if(!('iv' in options)) { throw new Error('Invalid IV parameter.'); } // use IV as first input this._iv = transformIV(options.iv); this._inBlock = this._iv.slice(0); this._partialBytes = 0; }; modes.ctr.prototype.encrypt = function(input, output, finish) { // not enough input to encrypt var inputLength = input.length(); if(inputLength === 0) { return true; } // encrypt block (CTR always uses encryption mode) this.cipher.encrypt(this._inBlock, this._outBlock); // handle full block if(this._partialBytes === 0 && inputLength >= this.blockSize) { // XOR input with output for(var i = 0; i < this._ints; ++i) { output.putInt32(input.getInt32() ^ this._outBlock[i]); } } else { // handle partial block var partialBytes = (this.blockSize - inputLength) % this.blockSize; if(partialBytes > 0) { partialBytes = this.blockSize - partialBytes; } // XOR input with output this._partialOutput.clear(); for(var i = 0; i < this._ints; ++i) { this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); } if(partialBytes > 0) { // block still incomplete, restore input buffer input.read -= this.blockSize; } // skip any previous partial bytes if(this._partialBytes > 0) { this._partialOutput.getBytes(this._partialBytes); } if(partialBytes > 0 && !finish) { output.putBytes(this._partialOutput.getBytes( partialBytes - this._partialBytes)); this._partialBytes = partialBytes; return true; } output.putBytes(this._partialOutput.getBytes( inputLength - this._partialBytes)); this._partialBytes = 0; } // block complete, increment counter (input block) inc32(this._inBlock); }; modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; /** Galois/Counter Mode (GCM) **/ modes.gcm = function(options) { options = options || {}; this.name = 'GCM'; this.cipher = options.cipher; this.blockSize = options.blockSize || 16; this._ints = this.blockSize / 4; this._inBlock = new Array(this._ints); this._outBlock = new Array(this._ints); this._partialOutput = forge.util.createBuffer(); this._partialBytes = 0; // R is actually this value concatenated with 120 more zero bits, but // we only XOR against R so the other zeros have no effect -- we just // apply this value to the first integer in a block this._R = 0xE1000000; }; modes.gcm.prototype.start = function(options) { if(!('iv' in options)) { throw new Error('Invalid IV parameter.'); } // ensure IV is a byte buffer var iv = forge.util.createBuffer(options.iv); // no ciphered data processed yet this._cipherLength = 0; // default additional data is none var additionalData; if('additionalData' in options) { additionalData = forge.util.createBuffer(options.additionalData); } else { additionalData = forge.util.createBuffer(); } // default tag length is 128 bits if('tagLength' in options) { this._tagLength = options.tagLength; } else { this._tagLength = 128; } // if tag is given, ensure tag matches tag length this._tag = null; if(options.decrypt) { // save tag to check later this._tag = forge.util.createBuffer(options.tag).getBytes(); if(this._tag.length !== (this._tagLength / 8)) { throw new Error('Authentication tag does not match tag length.'); } } // create tmp storage for hash calculation this._hashBlock = new Array(this._ints); // no tag generated yet this.tag = null; // generate hash subkey // (apply block cipher to "zero" block) this._hashSubkey = new Array(this._ints); this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); // generate table M // use 4-bit tables (32 component decomposition of a 16 byte value) // 8-bit tables take more space and are known to have security // vulnerabilities (in native implementations) this.componentBits = 4; this._m = this.generateHashTable(this._hashSubkey, this.componentBits); // Note: support IV length different from 96 bits? (only supporting // 96 bits is recommended by NIST SP-800-38D) // generate J_0 var ivLength = iv.length(); if(ivLength === 12) { // 96-bit IV this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; } else { // IV is NOT 96-bits this._j0 = [0, 0, 0, 0]; while(iv.length() > 0) { this._j0 = this.ghash( this._hashSubkey, this._j0, [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]); } this._j0 = this.ghash( this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8))); } // generate ICB (initial counter block) this._inBlock = this._j0.slice(0); inc32(this._inBlock); this._partialBytes = 0; // consume authentication data additionalData = forge.util.createBuffer(additionalData); // save additional data length as a BE 64-bit number this._aDataLength = from64To32(additionalData.length() * 8); // pad additional data to 128 bit (16 byte) block size var overflow = additionalData.length() % this.blockSize; if(overflow) { additionalData.fillWithByte(0, this.blockSize - overflow); } this._s = [0, 0, 0, 0]; while(additionalData.length() > 0) { this._s = this.ghash(this._hashSubkey, this._s, [ additionalData.getInt32(), additionalData.getInt32(), additionalData.getInt32(), additionalData.getInt32() ]); } }; modes.gcm.prototype.encrypt = function(input, output, finish) { // not enough input to encrypt var inputLength = input.length(); if(inputLength === 0) { return true; } // encrypt block this.cipher.encrypt(this._inBlock, this._outBlock); // handle full block if(this._partialBytes === 0 && inputLength >= this.blockSize) { // XOR input with output for(var i = 0; i < this._ints; ++i) { output.putInt32(this._outBlock[i] ^= input.getInt32()); } this._cipherLength += this.blockSize; } else { // handle partial block var partialBytes = (this.blockSize - inputLength) % this.blockSize; if(partialBytes > 0) { partialBytes = this.blockSize - partialBytes; } // XOR input with output this._partialOutput.clear(); for(var i = 0; i < this._ints; ++i) { this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); } if(partialBytes === 0 || finish) { // handle overflow prior to hashing if(finish) { // get block overflow var overflow = inputLength % this.blockSize; this._cipherLength += overflow; // truncate for hash function this._partialOutput.truncate(this.blockSize - overflow); } else { this._cipherLength += this.blockSize; } // get output block for hashing for(var i = 0; i < this._ints; ++i) { this._outBlock[i] = this._partialOutput.getInt32(); } this._partialOutput.read -= this.blockSize; } // skip any previous partial bytes if(this._partialBytes > 0) { this._partialOutput.getBytes(this._partialBytes); } if(partialBytes > 0 && !finish) { // block still incomplete, restore input buffer, get partial output, // and return early input.read -= this.blockSize; output.putBytes(this._partialOutput.getBytes( partialBytes - this._partialBytes)); this._partialBytes = partialBytes; return true; } output.putBytes(this._partialOutput.getBytes( inputLength - this._partialBytes)); this._partialBytes = 0; } // update hash block S this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); // increment counter (input block) inc32(this._inBlock); }; modes.gcm.prototype.decrypt = function(input, output, finish) { // not enough input to decrypt var inputLength = input.length(); if(inputLength < this.blockSize && !(finish && inputLength > 0)) { return true; } // encrypt block (GCM always uses encryption mode) this.cipher.encrypt(this._inBlock, this._outBlock); // increment counter (input block) inc32(this._inBlock); // update hash block S this._hashBlock[0] = input.getInt32(); this._hashBlock[1] = input.getInt32(); this._hashBlock[2] = input.getInt32(); this._hashBlock[3] = input.getInt32(); this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); // XOR hash input with output for(var i = 0; i < this._ints; ++i) { output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); } // increment cipher data length if(inputLength < this.blockSize) { this._cipherLength += inputLength % this.blockSize; } else { this._cipherLength += this.blockSize; } }; modes.gcm.prototype.afterFinish = function(output, options) { var rval = true; // handle overflow if(options.decrypt && options.overflow) { output.truncate(this.blockSize - options.overflow); } // handle authentication tag this.tag = forge.util.createBuffer(); // concatenate additional data length with cipher length var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); // include lengths in hash this._s = this.ghash(this._hashSubkey, this._s, lengths); // do GCTR(J_0, S) var tag = []; this.cipher.encrypt(this._j0, tag); for(var i = 0; i < this._ints; ++i) { this.tag.putInt32(this._s[i] ^ tag[i]); } // trim tag to length this.tag.truncate(this.tag.length() % (this._tagLength / 8)); // check authentication tag if(options.decrypt && this.tag.bytes() !== this._tag) { rval = false; } return rval; }; /** * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois * field multiplication. The field, GF(2^128), is defined by the polynomial: * * x^128 + x^7 + x^2 + x + 1 * * Which is represented in little-endian binary form as: 11100001 (0xe1). When * the value of a coefficient is 1, a bit is set. The value R, is the * concatenation of this value and 120 zero bits, yielding a 128-bit value * which matches the block size. * * This function will multiply two elements (vectors of bytes), X and Y, in * the field GF(2^128). The result is initialized to zero. For each bit of * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd) * by the current value of Y. For each bit, the value of Y will be raised by * a power of x (multiplied by the polynomial x). This can be achieved by * shifting Y once to the right. If the current value of Y, prior to being * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial. * Otherwise, we must divide by R after shifting to find the remainder. * * @param x the first block to multiply by the second. * @param y the second block to multiply by the first. * * @return the block result of the multiplication. */ modes.gcm.prototype.multiply = function(x, y) { var z_i = [0, 0, 0, 0]; var v_i = y.slice(0); // calculate Z_128 (block has 128 bits) for(var i = 0; i < 128; ++i) { // if x_i is 0, Z_{i+1} = Z_i (unchanged) // else Z_{i+1} = Z_i ^ V_i // get x_i by finding 32-bit int position, then left shift 1 by remainder var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32)); if(x_i) { z_i[0] ^= v_i[0]; z_i[1] ^= v_i[1]; z_i[2] ^= v_i[2]; z_i[3] ^= v_i[3]; } // if LSB(V_i) is 1, V_i = V_i >> 1 // else V_i = (V_i >> 1) ^ R this.pow(v_i, v_i); } return z_i; }; modes.gcm.prototype.pow = function(x, out) { // if LSB(x) is 1, x = x >>> 1 // else x = (x >>> 1) ^ R var lsb = x[3] & 1; // always do x >>> 1: // starting with the rightmost integer, shift each integer to the right // one bit, pulling in the bit from the integer to the left as its top // most bit (do this for the last 3 integers) for(var i = 3; i > 0; --i) { out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31); } // shift the first integer normally out[0] = x[0] >>> 1; // if lsb was not set, then polynomial had a degree of 127 and doesn't // need to divided; otherwise, XOR with R to find the remainder; we only // need to XOR the first integer since R technically ends w/120 zero bits if(lsb) { out[0] ^= this._R; } }; modes.gcm.prototype.tableMultiply = function(x) { // assumes 4-bit tables are used var z = [0, 0, 0, 0]; for(var i = 0; i < 32; ++i) { var idx = (i / 8) | 0; var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF; var ah = this._m[i][x_i]; z[0] ^= ah[0]; z[1] ^= ah[1]; z[2] ^= ah[2]; z[3] ^= ah[3]; } return z; }; /** * A continuing version of the GHASH algorithm that operates on a single * block. The hash block, last hash value (Ym) and the new block to hash * are given. * * @param h the hash block. * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash. * @param x the block to hash. * * @return the hashed value (Ym). */ modes.gcm.prototype.ghash = function(h, y, x) { y[0] ^= x[0]; y[1] ^= x[1]; y[2] ^= x[2]; y[3] ^= x[3]; return this.tableMultiply(y); //return this.multiply(y, h); }; /** * Precomputes a table for multiplying against the hash subkey. This * mechanism provides a substantial speed increase over multiplication * performed without a table. The table-based multiplication this table is * for solves X * H by multiplying each component of X by H and then * composing the results together using XOR. * * This function can be used to generate tables with different bit sizes * for the components, however, this implementation assumes there are * 32 components of X (which is a 16 byte vector), therefore each component * takes 4-bits (so the table is constructed with bits=4). * * @param h the hash subkey. * @param bits the bit size for a component. */ modes.gcm.prototype.generateHashTable = function(h, bits) { // TODO: There are further optimizations that would use only the // first table M_0 (or some variant) along with a remainder table; // this can be explored in the future var multiplier = 8 / bits; var perInt = 4 * multiplier; var size = 16 * multiplier; var m = new Array(size); for(var i = 0; i < size; ++i) { var tmp = [0, 0, 0, 0]; var idx = (i / perInt) | 0; var shft = ((perInt - 1 - (i % perInt)) * bits); tmp[idx] = (1 << (bits - 1)) << shft; m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); } return m; }; /** * Generates a table for multiplying against the hash subkey for one * particular component (out of all possible component values). * * @param mid the pre-multiplied value for the middle key of the table. * @param bits the bit size for a component. */ modes.gcm.prototype.generateSubHashTable = function(mid, bits) { // compute the table quickly by minimizing the number of // POW operations -- they only need to be performed for powers of 2, // all other entries can be composed from those powers using XOR var size = 1 << bits; var half = size >>> 1; var m = new Array(size); m[half] = mid.slice(0); var i = half >>> 1; while(i > 0) { // raise m0[2 * i] and store in m0[i] this.pow(m[2 * i], m[i] = []); i >>= 1; } i = 2; while(i < half) { for(var j = 1; j < i; ++j) { var m_i = m[i]; var m_j = m[j]; m[i + j] = [ m_i[0] ^ m_j[0], m_i[1] ^ m_j[1], m_i[2] ^ m_j[2], m_i[3] ^ m_j[3] ]; } i *= 2; } m[0] = [0, 0, 0, 0]; /* Note: We could avoid storing these by doing composition during multiply calculate top half using composition by speed is preferred. */ for(i = half + 1; i < size; ++i) { var c = m[i ^ half]; m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; } return m; }; /** Utility functions */ function transformIV(iv) { if(typeof iv === 'string') { // convert iv string into byte buffer iv = forge.util.createBuffer(iv); } if(forge.util.isArray(iv) && iv.length > 4) { // convert iv byte array into byte buffer var tmp = iv; iv = forge.util.createBuffer(); for(var i = 0; i < tmp.length; ++i) { iv.putByte(tmp[i]); } } if(!forge.util.isArray(iv)) { // convert iv byte buffer into 32-bit integer array iv = [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]; } return iv; } function inc32(block) { // increment last 32 bits of block only block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF; } function from64To32(num) { // convert 64-bit number to two BE Int32s return [(num / 0x100000000) | 0, num & 0xFFFFFFFF]; } /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { /** * Javascript implementation of basic RSA algorithms. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. * * The only algorithm currently supported for PKI is RSA. * * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier * and a subjectPublicKey of type bit string. * * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters * for the algorithm, if any. In the case of RSA, there aren't any. * * SubjectPublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * subjectPublicKey BIT STRING * } * * AlgorithmIdentifer ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL * } * * For an RSA public key, the subjectPublicKey is: * * RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER -- e * } * * PrivateKeyInfo ::= SEQUENCE { * version Version, * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, * privateKey PrivateKey, * attributes [0] IMPLICIT Attributes OPTIONAL * } * * Version ::= INTEGER * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier * PrivateKey ::= OCTET STRING * Attributes ::= SET OF Attribute * * An RSA private key as the following structure: * * RSAPrivateKey ::= SEQUENCE { * version Version, * modulus INTEGER, -- n * publicExponent INTEGER, -- e * privateExponent INTEGER, -- d * prime1 INTEGER, -- p * prime2 INTEGER, -- q * exponent1 INTEGER, -- d mod (p-1) * exponent2 INTEGER, -- d mod (q-1) * coefficient INTEGER -- (inverse of q) mod p * } * * Version ::= INTEGER * * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1 */ var forge = __webpack_require__(0); __webpack_require__(15); __webpack_require__(8); __webpack_require__(7); __webpack_require__(16); __webpack_require__(19); __webpack_require__(3); __webpack_require__(1); if(typeof BigInteger === 'undefined') { var BigInteger = forge.jsbn.BigInteger; } // shortcut for asn.1 API var asn1 = forge.asn1; /* * RSA encryption and decryption, see RFC 2313. */ forge.pki = forge.pki || {}; module.exports = forge.pki.rsa = forge.rsa = forge.rsa || {}; var pki = forge.pki; // for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; // validator for a PrivateKeyInfo structure var privateKeyValidator = { // PrivateKeyInfo name: 'PrivateKeyInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ // Version (INTEGER) name: 'PrivateKeyInfo.version', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyVersion' }, { // privateKeyAlgorithm name: 'PrivateKeyInfo.privateKeyAlgorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'AlgorithmIdentifier.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'privateKeyOid' }] }, { // PrivateKey name: 'PrivateKeyInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OCTETSTRING, constructed: false, capture: 'privateKey' }] }; // validator for an RSA private key var rsaPrivateKeyValidator = { // RSAPrivateKey name: 'RSAPrivateKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ // Version (INTEGER) name: 'RSAPrivateKey.version', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyVersion' }, { // modulus (n) name: 'RSAPrivateKey.modulus', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyModulus' }, { // publicExponent (e) name: 'RSAPrivateKey.publicExponent', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyPublicExponent' }, { // privateExponent (d) name: 'RSAPrivateKey.privateExponent', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyPrivateExponent' }, { // prime1 (p) name: 'RSAPrivateKey.prime1', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyPrime1' }, { // prime2 (q) name: 'RSAPrivateKey.prime2', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyPrime2' }, { // exponent1 (d mod (p-1)) name: 'RSAPrivateKey.exponent1', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyExponent1' }, { // exponent2 (d mod (q-1)) name: 'RSAPrivateKey.exponent2', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyExponent2' }, { // coefficient ((inverse of q) mod p) name: 'RSAPrivateKey.coefficient', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyCoefficient' }] }; // validator for an RSA public key var rsaPublicKeyValidator = { // RSAPublicKey name: 'RSAPublicKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ // modulus (n) name: 'RSAPublicKey.modulus', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'publicKeyModulus' }, { // publicExponent (e) name: 'RSAPublicKey.exponent', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'publicKeyExponent' }] }; // validator for an SubjectPublicKeyInfo structure // Note: Currently only works with an RSA public key var publicKeyValidator = forge.pki.rsa.publicKeyValidator = { name: 'SubjectPublicKeyInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, captureAsn1: 'subjectPublicKeyInfo', value: [{ name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'AlgorithmIdentifier.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'publicKeyOid' }] }, { // subjectPublicKey name: 'SubjectPublicKeyInfo.subjectPublicKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.BITSTRING, constructed: false, value: [{ // RSAPublicKey name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, optional: true, captureAsn1: 'rsaPublicKey' }] }] }; /** * Wrap digest in DigestInfo object. * * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447. * * DigestInfo ::= SEQUENCE { * digestAlgorithm DigestAlgorithmIdentifier, * digest Digest * } * * DigestAlgorithmIdentifier ::= AlgorithmIdentifier * Digest ::= OCTET STRING * * @param md the message digest object with the hash to sign. * * @return the encoded message (ready for RSA encrytion) */ var emsaPkcs1v15encode = function(md) { // get the oid for the algorithm var oid; if(md.algorithm in pki.oids) { oid = pki.oids[md.algorithm]; } else { var error = new Error('Unknown message digest algorithm.'); error.algorithm = md.algorithm; throw error; } var oidBytes = asn1.oidToDer(oid).getBytes(); // create the digest info var digestInfo = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); var digestAlgorithm = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); digestAlgorithm.value.push(asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes)); digestAlgorithm.value.push(asn1.create( asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')); var digest = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, md.digest().getBytes()); digestInfo.value.push(digestAlgorithm); digestInfo.value.push(digest); // encode digest info return asn1.toDer(digestInfo).getBytes(); }; /** * Performs x^c mod n (RSA encryption or decryption operation). * * @param x the number to raise and mod. * @param key the key to use. * @param pub true if the key is public, false if private. * * @return the result of x^c mod n. */ var _modPow = function(x, key, pub) { if(pub) { return x.modPow(key.e, key.n); } if(!key.p || !key.q) { // allow calculation without CRT params (slow) return x.modPow(key.d, key.n); } // pre-compute dP, dQ, and qInv if necessary if(!key.dP) { key.dP = key.d.mod(key.p.subtract(BigInteger.ONE)); } if(!key.dQ) { key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE)); } if(!key.qInv) { key.qInv = key.q.modInverse(key.p); } /* Chinese remainder theorem (CRT) states: Suppose n1, n2, ..., nk are positive integers which are pairwise coprime (n1 and n2 have no common factors other than 1). For any integers x1, x2, ..., xk there exists an integer x solving the system of simultaneous congruences (where ~= means modularly congruent so a ~= b mod n means a mod n = b mod n): x ~= x1 mod n1 x ~= x2 mod n2 ... x ~= xk mod nk This system of congruences has a single simultaneous solution x between 0 and n - 1. Furthermore, each xk solution and x itself is congruent modulo the product n = n1*n2*...*nk. So x1 mod n = x2 mod n = xk mod n = x mod n. The single simultaneous solution x can be solved with the following equation: x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni. Where x is less than n, xi = x mod ni. For RSA we are only concerned with k = 2. The modulus n = pq, where p and q are coprime. The RSA decryption algorithm is: y = x^d mod n Given the above: x1 = x^d mod p r1 = n/p = q s1 = q^-1 mod p x2 = x^d mod q r2 = n/q = p s2 = p^-1 mod q So y = (x1r1s1 + x2r2s2) mod n = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n According to Fermat's Little Theorem, if the modulus P is prime, for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P. Since A is not divisible by P it follows that if: N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore: A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort to calculate). In order to calculate x^d mod p more quickly the exponent d mod (p - 1) is stored in the RSA private key (the same is done for x^d mod q). These values are referred to as dP and dQ respectively. Therefore we now have: y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n Since we'll be reducing x^dP by modulo p (same for q) we can also reduce x by p (and q respectively) before hand. Therefore, let xp = ((x mod p)^dP mod p), and xq = ((x mod q)^dQ mod q), yielding: y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n This can be further reduced to a simple algorithm that only requires 1 inverse (the q inverse is used) to be used and stored. The algorithm is called Garner's algorithm. If qInv is the inverse of q, we simply calculate: y = (qInv*(xp - xq) mod p) * q + xq However, there are two further complications. First, we need to ensure that xp > xq to prevent signed BigIntegers from being used so we add p until this is true (since we will be mod'ing with p anyway). Then, there is a known timing attack on algorithms using the CRT. To mitigate this risk, "cryptographic blinding" should be used. This requires simply generating a random number r between 0 and n-1 and its inverse and multiplying x by r^e before calculating y and then multiplying y by r^-1 afterwards. Note that r must be coprime with n (gcd(r, n) === 1) in order to have an inverse. */ // cryptographic blinding var r; do { r = new BigInteger( forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)), 16); } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE)); x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); // calculate xp and xq var xp = x.mod(key.p).modPow(key.dP, key.p); var xq = x.mod(key.q).modPow(key.dQ, key.q); // xp must be larger than xq to avoid signed bit usage while(xp.compareTo(xq) < 0) { xp = xp.add(key.p); } // do last step var y = xp.subtract(xq) .multiply(key.qInv).mod(key.p) .multiply(key.q).add(xq); // remove effect of random for cryptographic blinding y = y.multiply(r.modInverse(key.n)).mod(key.n); return y; }; /** * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or * 'encrypt' on a public key object instead. * * Performs RSA encryption. * * The parameter bt controls whether to put padding bytes before the * message passed in. Set bt to either true or false to disable padding * completely (in order to handle e.g. EMSA-PSS encoding seperately before), * signaling whether the encryption operation is a public key operation * (i.e. encrypting data) or not, i.e. private key operation (data signing). * * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01 * (for signing) or 0x02 (for encryption). The key operation mode (private * or public) is derived from this flag in that case). * * @param m the message to encrypt as a byte string. * @param key the RSA key to use. * @param bt for PKCS#1 v1.5 padding, the block type to use * (0x01 for private key, 0x02 for public), * to disable padding: true = public key, false = private key. * * @return the encrypted bytes as a string. */ pki.rsa.encrypt = function(m, key, bt) { var pub = bt; var eb; // get the length of the modulus in bytes var k = Math.ceil(key.n.bitLength() / 8); if(bt !== false && bt !== true) { // legacy, default to PKCS#1 v1.5 padding pub = (bt === 0x02); eb = _encodePkcs1_v1_5(m, key, bt); } else { eb = forge.util.createBuffer(); eb.putBytes(m); } // load encryption block as big integer 'x' // FIXME: hex conversion inefficient, get BigInteger w/byte strings var x = new BigInteger(eb.toHex(), 16); // do RSA encryption var y = _modPow(x, key, pub); // convert y into the encrypted data byte string, if y is shorter in // bytes than k, then prepend zero bytes to fill up ed // FIXME: hex conversion inefficient, get BigInteger w/byte strings var yhex = y.toString(16); var ed = forge.util.createBuffer(); var zeros = k - Math.ceil(yhex.length / 2); while(zeros > 0) { ed.putByte(0x00); --zeros; } ed.putBytes(forge.util.hexToBytes(yhex)); return ed.getBytes(); }; /** * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or * 'verify' on a public key object instead. * * Performs RSA decryption. * * The parameter ml controls whether to apply PKCS#1 v1.5 padding * or not. Set ml = false to disable padding removal completely * (in order to handle e.g. EMSA-PSS later on) and simply pass back * the RSA encryption block. * * @param ed the encrypted data to decrypt in as a byte string. * @param key the RSA key to use. * @param pub true for a public key operation, false for private. * @param ml the message length, if known, false to disable padding. * * @return the decrypted message as a byte string. */ pki.rsa.decrypt = function(ed, key, pub, ml) { // get the length of the modulus in bytes var k = Math.ceil(key.n.bitLength() / 8); // error if the length of the encrypted data ED is not k if(ed.length !== k) { var error = new Error('Encrypted message length is invalid.'); error.length = ed.length; error.expected = k; throw error; } // convert encrypted data into a big integer // FIXME: hex conversion inefficient, get BigInteger w/byte strings var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16); // y must be less than the modulus or it wasn't the result of // a previous mod operation (encryption) using that modulus if(y.compareTo(key.n) >= 0) { throw new Error('Encrypted message is invalid.'); } // do RSA decryption var x = _modPow(y, key, pub); // create the encryption block, if x is shorter in bytes than k, then // prepend zero bytes to fill up eb // FIXME: hex conversion inefficient, get BigInteger w/byte strings var xhex = x.toString(16); var eb = forge.util.createBuffer(); var zeros = k - Math.ceil(xhex.length / 2); while(zeros > 0) { eb.putByte(0x00); --zeros; } eb.putBytes(forge.util.hexToBytes(xhex)); if(ml !== false) { // legacy, default to PKCS#1 v1.5 padding return _decodePkcs1_v1_5(eb.getBytes(), key, pub); } // return message return eb.getBytes(); }; /** * Creates an RSA key-pair generation state object. It is used to allow * key-generation to be performed in steps. It also allows for a UI to * display progress updates. * * @param bits the size for the private key in bits, defaults to 2048. * @param e the public exponent to use, defaults to 65537 (0x10001). * @param [options] the options to use. * prng a custom crypto-secure pseudo-random number generator to use, * that must define "getBytesSync". * algorithm the algorithm to use (default: 'PRIMEINC'). * * @return the state object to use to generate the key-pair. */ pki.rsa.createKeyPairGenerationState = function(bits, e, options) { // TODO: migrate step-based prime generation code to forge.prime // set default bits if(typeof(bits) === 'string') { bits = parseInt(bits, 10); } bits = bits || 2048; // create prng with api that matches BigInteger secure random options = options || {}; var prng = options.prng || forge.random; var rng = { // x is an array to fill with bytes nextBytes: function(x) { var b = prng.getBytesSync(x.length); for(var i = 0; i < x.length; ++i) { x[i] = b.charCodeAt(i); } } }; var algorithm = options.algorithm || 'PRIMEINC'; // create PRIMEINC algorithm state var rval; if(algorithm === 'PRIMEINC') { rval = { algorithm: algorithm, state: 0, bits: bits, rng: rng, eInt: e || 65537, e: new BigInteger(null), p: null, q: null, qBits: bits >> 1, pBits: bits - (bits >> 1), pqState: 0, num: null, keys: null }; rval.e.fromInt(rval.eInt); } else { throw new Error('Invalid key generation algorithm: ' + algorithm); } return rval; }; /** * Attempts to runs the key-generation algorithm for at most n seconds * (approximately) using the given state. When key-generation has completed, * the keys will be stored in state.keys. * * To use this function to update a UI while generating a key or to prevent * causing browser lockups/warnings, set "n" to a value other than 0. A * simple pattern for generating a key and showing a progress indicator is: * * var state = pki.rsa.createKeyPairGenerationState(2048); * var step = function() { * // step key-generation, run algorithm for 100 ms, repeat * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) { * setTimeout(step, 1); * } else { * // key-generation complete * // TODO: turn off progress indicator here * // TODO: use the generated key-pair in "state.keys" * } * }; * // TODO: turn on progress indicator here * setTimeout(step, 0); * * @param state the state to use. * @param n the maximum number of milliseconds to run the algorithm for, 0 * to run the algorithm to completion. * * @return true if the key-generation completed, false if not. */ pki.rsa.stepKeyPairGenerationState = function(state, n) { // set default algorithm if not set if(!('algorithm' in state)) { state.algorithm = 'PRIMEINC'; } // TODO: migrate step-based prime generation code to forge.prime // TODO: abstract as PRIMEINC algorithm // do key generation (based on Tom Wu's rsa.js, see jsbn.js license) // with some minor optimizations and designed to run in steps // local state vars var THIRTY = new BigInteger(null); THIRTY.fromInt(30); var deltaIdx = 0; var op_or = function(x, y) { return x|y; }; // keep stepping until time limit is reached or done var t1 = +new Date(); var t2; var total = 0; while(state.keys === null && (n <= 0 || total < n)) { // generate p or q if(state.state === 0) { /* Note: All primes are of the form: 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i When we generate a random number, we always align it at 30k + 1. Each time the number is determined not to be prime we add to get to the next 'i', eg: if the number was at 30k + 1 we add 6. */ var bits = (state.p === null) ? state.pBits : state.qBits; var bits1 = bits - 1; // get a random number if(state.pqState === 0) { state.num = new BigInteger(bits, state.rng); // force MSB set if(!state.num.testBit(bits1)) { state.num.bitwiseTo( BigInteger.ONE.shiftLeft(bits1), op_or, state.num); } // align number on 30k+1 boundary state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); deltaIdx = 0; ++state.pqState; } else if(state.pqState === 1) { // try to make the number a prime if(state.num.bitLength() > bits) { // overflow, try again state.pqState = 0; // do primality test } else if(state.num.isProbablePrime( _getMillerRabinTests(state.num.bitLength()))) { ++state.pqState; } else { // get next potential prime state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); } } else if(state.pqState === 2) { // ensure number is coprime with e state.pqState = (state.num.subtract(BigInteger.ONE).gcd(state.e) .compareTo(BigInteger.ONE) === 0) ? 3 : 0; } else if(state.pqState === 3) { // store p or q state.pqState = 0; if(state.p === null) { state.p = state.num; } else { state.q = state.num; } // advance state if both p and q are ready if(state.p !== null && state.q !== null) { ++state.state; } state.num = null; } } else if(state.state === 1) { // ensure p is larger than q (swap them if not) if(state.p.compareTo(state.q) < 0) { state.num = state.p; state.p = state.q; state.q = state.num; } ++state.state; } else if(state.state === 2) { // compute phi: (p - 1)(q - 1) (Euler's totient function) state.p1 = state.p.subtract(BigInteger.ONE); state.q1 = state.q.subtract(BigInteger.ONE); state.phi = state.p1.multiply(state.q1); ++state.state; } else if(state.state === 3) { // ensure e and phi are coprime if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) { // phi and e are coprime, advance ++state.state; } else { // phi and e aren't coprime, so generate a new p and q state.p = null; state.q = null; state.state = 0; } } else if(state.state === 4) { // create n, ensure n is has the right number of bits state.n = state.p.multiply(state.q); // ensure n is right number of bits if(state.n.bitLength() === state.bits) { // success, advance ++state.state; } else { // failed, get new q state.q = null; state.state = 0; } } else if(state.state === 5) { // set keys var d = state.e.modInverse(state.phi); state.keys = { privateKey: pki.rsa.setPrivateKey( state.n, state.e, d, state.p, state.q, d.mod(state.p1), d.mod(state.q1), state.q.modInverse(state.p)), publicKey: pki.rsa.setPublicKey(state.n, state.e) }; } // update timing t2 = +new Date(); total += t2 - t1; t1 = t2; } return state.keys !== null; }; /** * Generates an RSA public-private key pair in a single call. * * To generate a key-pair in steps (to allow for progress updates and to * prevent blocking or warnings in slow browsers) then use the key-pair * generation state functions. * * To generate a key-pair asynchronously (either through web-workers, if * available, or by breaking up the work on the main thread), pass a * callback function. * * @param [bits] the size for the private key in bits, defaults to 2048. * @param [e] the public exponent to use, defaults to 65537. * @param [options] options for key-pair generation, if given then 'bits' * and 'e' must *not* be given: * bits the size for the private key in bits, (default: 2048). * e the public exponent to use, (default: 65537 (0x10001)). * workerScript the worker script URL. * workers the number of web workers (if supported) to use, * (default: 2). * workLoad the size of the work load, ie: number of possible prime * numbers for each web worker to check per work assignment, * (default: 100). * prng a custom crypto-secure pseudo-random number generator to use, * that must define "getBytesSync". * algorithm the algorithm to use (default: 'PRIMEINC'). * @param [callback(err, keypair)] called once the operation completes. * * @return an object with privateKey and publicKey properties. */ pki.rsa.generateKeyPair = function(bits, e, options, callback) { // (bits), (options), (callback) if(arguments.length === 1) { if(typeof bits === 'object') { options = bits; bits = undefined; } else if(typeof bits === 'function') { callback = bits; bits = undefined; } } else if(arguments.length === 2) { // (bits, e), (bits, options), (bits, callback), (options, callback) if(typeof bits === 'number') { if(typeof e === 'function') { callback = e; e = undefined; } else if(typeof e !== 'number') { options = e; e = undefined; } } else { options = bits; callback = e; bits = undefined; e = undefined; } } else if(arguments.length === 3) { // (bits, e, options), (bits, e, callback), (bits, options, callback) if(typeof e === 'number') { if(typeof options === 'function') { callback = options; options = undefined; } } else { callback = options; options = e; e = undefined; } } options = options || {}; if(bits === undefined) { bits = options.bits || 2048; } if(e === undefined) { e = options.e || 0x10001; } // if native code is permitted and a callback is given, use native // key generation code if available and if parameters are acceptable if(!forge.options.usePureJavaScript && callback && bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) { if(_detectSubtleCrypto('generateKey') && _detectSubtleCrypto('exportKey')) { // use standard native generateKey return window.crypto.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: bits, publicExponent: _intToUint8Array(e), hash: {name: 'SHA-256'} }, true /* key can be exported*/, ['sign', 'verify']) .then(function(pair) { return window.crypto.subtle.exportKey('pkcs8', pair.privateKey); // avoiding catch(function(err) {...}) to support IE <= 8 }).then(undefined, function(err) { callback(err); }).then(function(pkcs8) { if(pkcs8) { var privateKey = pki.privateKeyFromAsn1( asn1.fromDer(forge.util.createBuffer(pkcs8))); callback(null, { privateKey: privateKey, publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) }); } }); } if(_detectSubtleMsCrypto('generateKey') && _detectSubtleMsCrypto('exportKey')) { var genOp = window.msCrypto.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: bits, publicExponent: _intToUint8Array(e), hash: {name: 'SHA-256'} }, true /* key can be exported*/, ['sign', 'verify']); genOp.oncomplete = function(e) { var pair = e.target.result; var exportOp = window.msCrypto.subtle.exportKey( 'pkcs8', pair.privateKey); exportOp.oncomplete = function(e) { var pkcs8 = e.target.result; var privateKey = pki.privateKeyFromAsn1( asn1.fromDer(forge.util.createBuffer(pkcs8))); callback(null, { privateKey: privateKey, publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) }); }; exportOp.onerror = function(err) { callback(err); }; }; genOp.onerror = function(err) { callback(err); }; return; } } // use JavaScript implementation var state = pki.rsa.createKeyPairGenerationState(bits, e, options); if(!callback) { pki.rsa.stepKeyPairGenerationState(state, 0); return state.keys; } _generateKeyPair(state, options, callback); }; /** * Sets an RSA public key from BigIntegers modulus and exponent. * * @param n the modulus. * @param e the exponent. * * @return the public key. */ pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) { var key = { n: n, e: e }; /** * Encrypts the given data with this public key. Newer applications * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for * legacy applications. * * @param data the byte string to encrypt. * @param scheme the encryption scheme to use: * 'RSAES-PKCS1-V1_5' (default), * 'RSA-OAEP', * 'RAW', 'NONE', or null to perform raw RSA encryption, * an object with an 'encode' property set to a function * with the signature 'function(data, key)' that returns * a binary-encoded string representing the encoded data. * @param schemeOptions any scheme-specific options. * * @return the encrypted byte string. */ key.encrypt = function(data, scheme, schemeOptions) { if(typeof scheme === 'string') { scheme = scheme.toUpperCase(); } else if(scheme === undefined) { scheme = 'RSAES-PKCS1-V1_5'; } if(scheme === 'RSAES-PKCS1-V1_5') { scheme = { encode: function(m, key, pub) { return _encodePkcs1_v1_5(m, key, 0x02).getBytes(); } }; } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { scheme = { encode: function(m, key) { return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions); } }; } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { scheme = { encode: function(e) { return e; } }; } else if(typeof scheme === 'string') { throw new Error('Unsupported encryption scheme: "' + scheme + '".'); } // do scheme-based encoding then rsa encryption var e = scheme.encode(data, key, true); return pki.rsa.encrypt(e, key, true); }; /** * Verifies the given signature against the given digest. * * PKCS#1 supports multiple (currently two) signature schemes: * RSASSA-PKCS1-V1_5 and RSASSA-PSS. * * By default this implementation uses the "old scheme", i.e. * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the * signature is an OCTET STRING that holds a DigestInfo. * * DigestInfo ::= SEQUENCE { * digestAlgorithm DigestAlgorithmIdentifier, * digest Digest * } * DigestAlgorithmIdentifier ::= AlgorithmIdentifier * Digest ::= OCTET STRING * * To perform PSS signature verification, provide an instance * of Forge PSS object as the scheme parameter. * * @param digest the message digest hash to compare against the signature, * as a binary-encoded string. * @param signature the signature to verify, as a binary-encoded string. * @param scheme signature verification scheme to use: * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, * a Forge PSS object for RSASSA-PSS, * 'NONE' or null for none, DigestInfo will not be expected, but * PKCS#1 v1.5 padding will still be used. * * @return true if the signature was verified, false if not. */ key.verify = function(digest, signature, scheme) { if(typeof scheme === 'string') { scheme = scheme.toUpperCase(); } else if(scheme === undefined) { scheme = 'RSASSA-PKCS1-V1_5'; } if(scheme === 'RSASSA-PKCS1-V1_5') { scheme = { verify: function(digest, d) { // remove padding d = _decodePkcs1_v1_5(d, key, true); // d is ASN.1 BER-encoded DigestInfo var obj = asn1.fromDer(d); // compare the given digest to the decrypted one return digest === obj.value[1].value; } }; } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { scheme = { verify: function(digest, d) { // remove padding d = _decodePkcs1_v1_5(d, key, true); return digest === d; } }; } // do rsa decryption w/o any decoding, then verify -- which does decoding var d = pki.rsa.decrypt(signature, key, true, false); return scheme.verify(digest, d, key.n.bitLength()); }; return key; }; /** * Sets an RSA private key from BigIntegers modulus, exponent, primes, * prime exponents, and modular multiplicative inverse. * * @param n the modulus. * @param e the public exponent. * @param d the private exponent ((inverse of e) mod n). * @param p the first prime. * @param q the second prime. * @param dP exponent1 (d mod (p-1)). * @param dQ exponent2 (d mod (q-1)). * @param qInv ((inverse of q) mod p) * * @return the private key. */ pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function( n, e, d, p, q, dP, dQ, qInv) { var key = { n: n, e: e, d: d, p: p, q: q, dP: dP, dQ: dQ, qInv: qInv }; /** * Decrypts the given data with this private key. The decryption scheme * must match the one used to encrypt the data. * * @param data the byte string to decrypt. * @param scheme the decryption scheme to use: * 'RSAES-PKCS1-V1_5' (default), * 'RSA-OAEP', * 'RAW', 'NONE', or null to perform raw RSA decryption. * @param schemeOptions any scheme-specific options. * * @return the decrypted byte string. */ key.decrypt = function(data, scheme, schemeOptions) { if(typeof scheme === 'string') { scheme = scheme.toUpperCase(); } else if(scheme === undefined) { scheme = 'RSAES-PKCS1-V1_5'; } // do rsa decryption w/o any decoding var d = pki.rsa.decrypt(data, key, false, false); if(scheme === 'RSAES-PKCS1-V1_5') { scheme = { decode: _decodePkcs1_v1_5 }; } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { scheme = { decode: function(d, key) { return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions); } }; } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { scheme = { decode: function(d) { return d; } }; } else { throw new Error('Unsupported encryption scheme: "' + scheme + '".'); } // decode according to scheme return scheme.decode(d, key, false); }; /** * Signs the given digest, producing a signature. * * PKCS#1 supports multiple (currently two) signature schemes: * RSASSA-PKCS1-V1_5 and RSASSA-PSS. * * By default this implementation uses the "old scheme", i.e. * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide * an instance of Forge PSS object as the scheme parameter. * * @param md the message digest object with the hash to sign. * @param scheme the signature scheme to use: * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, * a Forge PSS object for RSASSA-PSS, * 'NONE' or null for none, DigestInfo will not be used but * PKCS#1 v1.5 padding will still be used. * * @return the signature as a byte string. */ key.sign = function(md, scheme) { /* Note: The internal implementation of RSA operations is being transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy code like the use of an encoding block identifier 'bt' will eventually be removed. */ // private key operation var bt = false; if(typeof scheme === 'string') { scheme = scheme.toUpperCase(); } if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') { scheme = { encode: emsaPkcs1v15encode }; bt = 0x01; } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { scheme = { encode: function() { return md; } }; bt = 0x01; } // encode and then encrypt var d = scheme.encode(md, key.n.bitLength()); return pki.rsa.encrypt(d, key, bt); }; return key; }; /** * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object. * * @param rsaKey the ASN.1 RSAPrivateKey. * * @return the ASN.1 PrivateKeyInfo. */ pki.wrapRsaPrivateKey = function(rsaKey) { // PrivateKeyInfo return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // version (0) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(0).getBytes()), // privateKeyAlgorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ]), // PrivateKey asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(rsaKey).getBytes()) ]); }; /** * Converts a private key from an ASN.1 object. * * @param obj the ASN.1 representation of a PrivateKeyInfo containing an * RSAPrivateKey or an RSAPrivateKey. * * @return the private key. */ pki.privateKeyFromAsn1 = function(obj) { // get PrivateKeyInfo var capture = {}; var errors = []; if(asn1.validate(obj, privateKeyValidator, capture, errors)) { obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey)); } // get RSAPrivateKey capture = {}; errors = []; if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) { var error = new Error('Cannot read private key. ' + 'ASN.1 object does not contain an RSAPrivateKey.'); error.errors = errors; throw error; } // Note: Version is currently ignored. // capture.privateKeyVersion // FIXME: inefficient, get a BigInteger that uses byte strings var n, e, d, p, q, dP, dQ, qInv; n = forge.util.createBuffer(capture.privateKeyModulus).toHex(); e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex(); d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); p = forge.util.createBuffer(capture.privateKeyPrime1).toHex(); q = forge.util.createBuffer(capture.privateKeyPrime2).toHex(); dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex(); dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex(); qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex(); // set private key return pki.setRsaPrivateKey( new BigInteger(n, 16), new BigInteger(e, 16), new BigInteger(d, 16), new BigInteger(p, 16), new BigInteger(q, 16), new BigInteger(dP, 16), new BigInteger(dQ, 16), new BigInteger(qInv, 16)); }; /** * Converts a private key to an ASN.1 RSAPrivateKey. * * @param key the private key. * * @return the ASN.1 representation of an RSAPrivateKey. */ pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) { // RSAPrivateKey return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // version (0 = only 2 primes, 1 multiple primes) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(0).getBytes()), // modulus (n) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.n)), // publicExponent (e) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.e)), // privateExponent (d) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.d)), // privateKeyPrime1 (p) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.p)), // privateKeyPrime2 (q) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.q)), // privateKeyExponent1 (dP) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.dP)), // privateKeyExponent2 (dQ) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.dQ)), // coefficient (qInv) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.qInv)) ]); }; /** * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey. * * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey. * * @return the public key. */ pki.publicKeyFromAsn1 = function(obj) { // get SubjectPublicKeyInfo var capture = {}; var errors = []; if(asn1.validate(obj, publicKeyValidator, capture, errors)) { // get oid var oid = asn1.derToOid(capture.publicKeyOid); if(oid !== pki.oids.rsaEncryption) { var error = new Error('Cannot read public key. Unknown OID.'); error.oid = oid; throw error; } obj = capture.rsaPublicKey; } // get RSA params errors = []; if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) { var error = new Error('Cannot read public key. ' + 'ASN.1 object does not contain an RSAPublicKey.'); error.errors = errors; throw error; } // FIXME: inefficient, get a BigInteger that uses byte strings var n = forge.util.createBuffer(capture.publicKeyModulus).toHex(); var e = forge.util.createBuffer(capture.publicKeyExponent).toHex(); // set public key return pki.setRsaPublicKey( new BigInteger(n, 16), new BigInteger(e, 16)); }; /** * Converts a public key to an ASN.1 SubjectPublicKeyInfo. * * @param key the public key. * * @return the asn1 representation of a SubjectPublicKeyInfo. */ pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) { // SubjectPublicKeyInfo return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // AlgorithmIdentifier asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // algorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), // parameters (null) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ]), // subjectPublicKey asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ pki.publicKeyToRSAPublicKey(key) ]) ]); }; /** * Converts a public key to an ASN.1 RSAPublicKey. * * @param key the public key. * * @return the asn1 representation of a RSAPublicKey. */ pki.publicKeyToRSAPublicKey = function(key) { // RSAPublicKey return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // modulus (n) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.n)), // publicExponent (e) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.e)) ]); }; /** * Encodes a message using PKCS#1 v1.5 padding. * * @param m the message to encode. * @param key the RSA key to use. * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02 * (for encryption). * * @return the padded byte buffer. */ function _encodePkcs1_v1_5(m, key, bt) { var eb = forge.util.createBuffer(); // get the length of the modulus in bytes var k = Math.ceil(key.n.bitLength() / 8); /* use PKCS#1 v1.5 padding */ if(m.length > (k - 11)) { var error = new Error('Message is too long for PKCS#1 v1.5 padding.'); error.length = m.length; error.max = k - 11; throw error; } /* A block type BT, a padding string PS, and the data D shall be formatted into an octet string EB, the encryption block: EB = 00 || BT || PS || 00 || D The block type BT shall be a single octet indicating the structure of the encryption block. For this version of the document it shall have value 00, 01, or 02. For a private-key operation, the block type shall be 00 or 01. For a public-key operation, it shall be 02. The padding string PS shall consist of k-3-||D|| octets. For block type 00, the octets shall have value 00; for block type 01, they shall have value FF; and for block type 02, they shall be pseudorandomly generated and nonzero. This makes the length of the encryption block EB equal to k. */ // build the encryption block eb.putByte(0x00); eb.putByte(bt); // create the padding var padNum = k - 3 - m.length; var padByte; // private key op if(bt === 0x00 || bt === 0x01) { padByte = (bt === 0x00) ? 0x00 : 0xFF; for(var i = 0; i < padNum; ++i) { eb.putByte(padByte); } } else { // public key op // pad with random non-zero values while(padNum > 0) { var numZeros = 0; var padBytes = forge.random.getBytes(padNum); for(var i = 0; i < padNum; ++i) { padByte = padBytes.charCodeAt(i); if(padByte === 0) { ++numZeros; } else { eb.putByte(padByte); } } padNum = numZeros; } } // zero followed by message eb.putByte(0x00); eb.putBytes(m); return eb; } /** * Decodes a message using PKCS#1 v1.5 padding. * * @param em the message to decode. * @param key the RSA key to use. * @param pub true if the key is a public key, false if it is private. * @param ml the message length, if specified. * * @return the decoded bytes. */ function _decodePkcs1_v1_5(em, key, pub, ml) { // get the length of the modulus in bytes var k = Math.ceil(key.n.bitLength() / 8); /* It is an error if any of the following conditions occurs: 1. The encryption block EB cannot be parsed unambiguously. 2. The padding string PS consists of fewer than eight octets or is inconsisent with the block type BT. 3. The decryption process is a public-key operation and the block type BT is not 00 or 01, or the decryption process is a private-key operation and the block type is not 02. */ // parse the encryption block var eb = forge.util.createBuffer(em); var first = eb.getByte(); var bt = eb.getByte(); if(first !== 0x00 || (pub && bt !== 0x00 && bt !== 0x01) || (!pub && bt != 0x02) || (pub && bt === 0x00 && typeof(ml) === 'undefined')) { throw new Error('Encryption block is invalid.'); } var padNum = 0; if(bt === 0x00) { // check all padding bytes for 0x00 padNum = k - 3 - ml; for(var i = 0; i < padNum; ++i) { if(eb.getByte() !== 0x00) { throw new Error('Encryption block is invalid.'); } } } else if(bt === 0x01) { // find the first byte that isn't 0xFF, should be after all padding padNum = 0; while(eb.length() > 1) { if(eb.getByte() !== 0xFF) { --eb.read; break; } ++padNum; } } else if(bt === 0x02) { // look for 0x00 byte padNum = 0; while(eb.length() > 1) { if(eb.getByte() === 0x00) { --eb.read; break; } ++padNum; } } // zero must be 0x00 and padNum must be (k - 3 - message length) var zero = eb.getByte(); if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) { throw new Error('Encryption block is invalid.'); } return eb.getBytes(); } /** * Runs the key-generation algorithm asynchronously, either in the background * via Web Workers, or using the main thread and setImmediate. * * @param state the key-pair generation state. * @param [options] options for key-pair generation: * workerScript the worker script URL. * workers the number of web workers (if supported) to use, * (default: 2, -1 to use estimated cores minus one). * workLoad the size of the work load, ie: number of possible prime * numbers for each web worker to check per work assignment, * (default: 100). * @param callback(err, keypair) called once the operation completes. */ function _generateKeyPair(state, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } options = options || {}; var opts = { algorithm: { name: options.algorithm || 'PRIMEINC', options: { workers: options.workers || 2, workLoad: options.workLoad || 100, workerScript: options.workerScript } } }; if('prng' in options) { opts.prng = options.prng; } generate(); function generate() { // find p and then q (done in series to simplify) getPrime(state.pBits, function(err, num) { if(err) { return callback(err); } state.p = num; if(state.q !== null) { return finish(err, state.q); } getPrime(state.qBits, finish); }); } function getPrime(bits, callback) { forge.prime.generateProbablePrime(bits, opts, callback); } function finish(err, num) { if(err) { return callback(err); } // set q state.q = num; // ensure p is larger than q (swap them if not) if(state.p.compareTo(state.q) < 0) { var tmp = state.p; state.p = state.q; state.q = tmp; } // ensure p is coprime with e if(state.p.subtract(BigInteger.ONE).gcd(state.e) .compareTo(BigInteger.ONE) !== 0) { state.p = null; generate(); return; } // ensure q is coprime with e if(state.q.subtract(BigInteger.ONE).gcd(state.e) .compareTo(BigInteger.ONE) !== 0) { state.q = null; getPrime(state.qBits, finish); return; } // compute phi: (p - 1)(q - 1) (Euler's totient function) state.p1 = state.p.subtract(BigInteger.ONE); state.q1 = state.q.subtract(BigInteger.ONE); state.phi = state.p1.multiply(state.q1); // ensure e and phi are coprime if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) { // phi and e aren't coprime, so generate a new p and q state.p = state.q = null; generate(); return; } // create n, ensure n is has the right number of bits state.n = state.p.multiply(state.q); if(state.n.bitLength() !== state.bits) { // failed, get new q state.q = null; getPrime(state.qBits, finish); return; } // set keys var d = state.e.modInverse(state.phi); state.keys = { privateKey: pki.rsa.setPrivateKey( state.n, state.e, d, state.p, state.q, d.mod(state.p1), d.mod(state.q1), state.q.modInverse(state.p)), publicKey: pki.rsa.setPublicKey(state.n, state.e) }; callback(null, state.keys); } } /** * Converts a positive BigInteger into 2's-complement big-endian bytes. * * @param b the big integer to convert. * * @return the bytes. */ function _bnToBytes(b) { // prepend 0x00 if first byte >= 0x80 var hex = b.toString(16); if(hex[0] >= '8') { hex = '00' + hex; } var bytes = forge.util.hexToBytes(hex); // ensure integer is minimally-encoded if(bytes.length > 1 && // leading 0x00 for positive integer ((bytes.charCodeAt(0) === 0 && (bytes.charCodeAt(1) & 0x80) === 0) || // leading 0xFF for negative integer (bytes.charCodeAt(0) === 0xFF && (bytes.charCodeAt(1) & 0x80) === 0x80))) { return bytes.substr(1); } return bytes; } /** * Returns the required number of Miller-Rabin tests to generate a * prime with an error probability of (1/2)^80. * * See Handbook of Applied Cryptography Chapter 4, Table 4.4. * * @param bits the bit size. * * @return the required number of iterations. */ function _getMillerRabinTests(bits) { if(bits <= 100) return 27; if(bits <= 150) return 18; if(bits <= 200) return 15; if(bits <= 250) return 12; if(bits <= 300) return 9; if(bits <= 350) return 8; if(bits <= 400) return 7; if(bits <= 500) return 6; if(bits <= 600) return 5; if(bits <= 800) return 4; if(bits <= 1250) return 3; return 2; } /** * Performs feature detection on the SubtleCrypto interface. * * @param fn the feature (function) to detect. * * @return true if detected, false if not. */ function _detectSubtleCrypto(fn) { return (typeof window !== 'undefined' && typeof window.crypto === 'object' && typeof window.crypto.subtle === 'object' && typeof window.crypto.subtle[fn] === 'function'); } /** * Performs feature detection on the deprecated Microsoft Internet Explorer * outdated SubtleCrypto interface. This function should only be used after * checking for the modern, standard SubtleCrypto interface. * * @param fn the feature (function) to detect. * * @return true if detected, false if not. */ function _detectSubtleMsCrypto(fn) { return (typeof window !== 'undefined' && typeof window.msCrypto === 'object' && typeof window.msCrypto.subtle === 'object' && typeof window.msCrypto.subtle[fn] === 'function'); } function _intToUint8Array(x) { var bytes = forge.util.hexToBytes(x.toString(16)); var buffer = new Uint8Array(bytes.length); for(var i = 0; i < bytes.length; ++i) { buffer[i] = bytes.charCodeAt(i); } return buffer; } function _privateKeyFromJwk(jwk) { if(jwk.kty !== 'RSA') { throw new Error( 'Unsupported key algorithm "' + jwk.kty + '"; algorithm must be "RSA".'); } return pki.setRsaPrivateKey( _base64ToBigInt(jwk.n), _base64ToBigInt(jwk.e), _base64ToBigInt(jwk.d), _base64ToBigInt(jwk.p), _base64ToBigInt(jwk.q), _base64ToBigInt(jwk.dp), _base64ToBigInt(jwk.dq), _base64ToBigInt(jwk.qi)); } function _publicKeyFromJwk(jwk) { if(jwk.kty !== 'RSA') { throw new Error('Key algorithm must be "RSA".'); } return pki.setRsaPublicKey( _base64ToBigInt(jwk.n), _base64ToBigInt(jwk.e)); } function _base64ToBigInt(b64) { return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16); } /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { /** * Javascript implementation of Abstract Syntax Notation Number One. * * @author Dave Longley * * Copyright (c) 2010-2015 Digital Bazaar, Inc. * * An API for storing data using the Abstract Syntax Notation Number One * format using DER (Distinguished Encoding Rules) encoding. This encoding is * commonly used to store data for PKI, i.e. X.509 Certificates, and this * implementation exists for that purpose. * * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract * syntax of information without restricting the way the information is encoded * for transmission. It provides a standard that allows for open systems * communication. ASN.1 defines the syntax of information data and a number of * simple data types as well as a notation for describing them and specifying * values for them. * * The RSA algorithm creates public and private keys that are often stored in * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This * class provides the most basic functionality required to store and load DSA * keys that are encoded according to ASN.1. * * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules) * and DER (Distinguished Encoding Rules). DER is just a subset of BER that * has stricter requirements for how data must be encoded. * * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type) * and a byte array for the value of this ASN1 structure which may be data or a * list of ASN.1 structures. * * Each ASN.1 structure using BER is (Tag-Length-Value): * * | byte 0 | bytes X | bytes Y | * |--------|---------|---------- * | tag | length | value | * * ASN.1 allows for tags to be of "High-tag-number form" which allows a tag to * be two or more octets, but that is not supported by this class. A tag is * only 1 byte. Bits 1-5 give the tag number (ie the data type within a * particular 'class'), 6 indicates whether or not the ASN.1 value is * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set, * then the class is APPLICATION. If only bit 8 is set, then the class is * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE. * The tag numbers for the data types for the class UNIVERSAL are listed below: * * UNIVERSAL 0 Reserved for use by the encoding rules * UNIVERSAL 1 Boolean type * UNIVERSAL 2 Integer type * UNIVERSAL 3 Bitstring type * UNIVERSAL 4 Octetstring type * UNIVERSAL 5 Null type * UNIVERSAL 6 Object identifier type * UNIVERSAL 7 Object descriptor type * UNIVERSAL 8 External type and Instance-of type * UNIVERSAL 9 Real type * UNIVERSAL 10 Enumerated type * UNIVERSAL 11 Embedded-pdv type * UNIVERSAL 12 UTF8String type * UNIVERSAL 13 Relative object identifier type * UNIVERSAL 14-15 Reserved for future editions * UNIVERSAL 16 Sequence and Sequence-of types * UNIVERSAL 17 Set and Set-of types * UNIVERSAL 18-22, 25-30 Character string types * UNIVERSAL 23-24 Time types * * The length of an ASN.1 structure is specified after the tag identifier. * There is a definite form and an indefinite form. The indefinite form may * be used if the encoding is constructed and not all immediately available. * The indefinite form is encoded using a length byte with only the 8th bit * set. The end of the constructed object is marked using end-of-contents * octets (two zero bytes). * * The definite form looks like this: * * The length may take up 1 or more bytes, it depends on the length of the * value of the ASN.1 structure. DER encoding requires that if the ASN.1 * structure has a value that has a length greater than 127, more than 1 byte * will be used to store its length, otherwise just one byte will be used. * This is strict. * * In the case that the length of the ASN.1 value is less than 127, 1 octet * (byte) is used to store the "short form" length. The 8th bit has a value of * 0 indicating the length is "short form" and not "long form" and bits 7-1 * give the length of the data. (The 8th bit is the left-most, most significant * bit: also known as big endian or network format). * * In the case that the length of the ASN.1 value is greater than 127, 2 to * 127 octets (bytes) are used to store the "long form" length. The first * byte's 8th bit is set to 1 to indicate the length is "long form." Bits 7-1 * give the number of additional octets. All following octets are in base 256 * with the most significant digit first (typical big-endian binary unsigned * integer storage). So, for instance, if the length of a value was 257, the * first byte would be set to: * * 10000010 = 130 = 0x82. * * This indicates there are 2 octets (base 256) for the length. The second and * third bytes (the octets just mentioned) would store the length in base 256: * * octet 2: 00000001 = 1 * 256^1 = 256 * octet 3: 00000001 = 1 * 256^0 = 1 * total = 257 * * The algorithm for converting a js integer value of 257 to base-256 is: * * var value = 257; * var bytes = []; * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first * bytes[1] = value & 0xFF; // least significant byte last * * On the ASN.1 UNIVERSAL Object Identifier (OID) type: * * An OID can be written like: "value1.value2.value3...valueN" * * The DER encoding rules: * * The first byte has the value 40 * value1 + value2. * The following bytes, if any, encode the remaining values. Each value is * encoded in base 128, most significant digit first (big endian), with as * few digits as possible, and the most significant bit of each byte set * to 1 except the last in each value's encoding. For example: Given the * OID "1.2.840.113549", its DER encoding is (remember each byte except the * last one in each encoding is OR'd with 0x80): * * byte 1: 40 * 1 + 2 = 42 = 0x2A. * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648 * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D * * The final value is: 0x2A864886F70D. * The full OID (including ASN.1 tag and length of 6 bytes) is: * 0x06062A864886F70D */ var forge = __webpack_require__(0); __webpack_require__(1); __webpack_require__(7); /* ASN.1 API */ var asn1 = module.exports = forge.asn1 = forge.asn1 || {}; /** * ASN.1 classes. */ asn1.Class = { UNIVERSAL: 0x00, APPLICATION: 0x40, CONTEXT_SPECIFIC: 0x80, PRIVATE: 0xC0 }; /** * ASN.1 types. Not all types are supported by this implementation, only * those necessary to implement a simple PKI are implemented. */ asn1.Type = { NONE: 0, BOOLEAN: 1, INTEGER: 2, BITSTRING: 3, OCTETSTRING: 4, NULL: 5, OID: 6, ODESC: 7, EXTERNAL: 8, REAL: 9, ENUMERATED: 10, EMBEDDED: 11, UTF8: 12, ROID: 13, SEQUENCE: 16, SET: 17, PRINTABLESTRING: 19, IA5STRING: 22, UTCTIME: 23, GENERALIZEDTIME: 24, BMPSTRING: 30 }; /** * Creates a new asn1 object. * * @param tagClass the tag class for the object. * @param type the data type (tag number) for the object. * @param constructed true if the asn1 object is in constructed form. * @param value the value for the object, if it is not constructed. * @param [options] the options to use: * [bitStringContents] the plain BIT STRING content including padding * byte. * * @return the asn1 object. */ asn1.create = function(tagClass, type, constructed, value, options) { /* An asn1 object has a tagClass, a type, a constructed flag, and a value. The value's type depends on the constructed flag. If constructed, it will contain a list of other asn1 objects. If not, it will contain the ASN.1 value as an array of bytes formatted according to the ASN.1 data type. */ // remove undefined values if(forge.util.isArray(value)) { var tmp = []; for(var i = 0; i < value.length; ++i) { if(value[i] !== undefined) { tmp.push(value[i]); } } value = tmp; } var obj = { tagClass: tagClass, type: type, constructed: constructed, composed: constructed || forge.util.isArray(value), value: value }; if(options && 'bitStringContents' in options) { // TODO: copy byte buffer if it's a buffer not a string obj.bitStringContents = options.bitStringContents; // TODO: add readonly flag to avoid this overhead // save copy to detect changes obj.original = asn1.copy(obj); } return obj; }; /** * Copies an asn1 object. * * @param obj the asn1 object. * @param [options] copy options: * [excludeBitStringContents] true to not copy bitStringContents * * @return the a copy of the asn1 object. */ asn1.copy = function(obj, options) { var copy; if(forge.util.isArray(obj)) { copy = []; for(var i = 0; i < obj.length; ++i) { copy.push(asn1.copy(obj[i], options)); } return copy; } if(typeof obj === 'string') { // TODO: copy byte buffer if it's a buffer not a string return obj; } copy = { tagClass: obj.tagClass, type: obj.type, constructed: obj.constructed, composed: obj.composed, value: asn1.copy(obj.value, options) }; if(options && !options.excludeBitStringContents) { // TODO: copy byte buffer if it's a buffer not a string copy.bitStringContents = obj.bitStringContents; } return copy; }; /** * Compares asn1 objects for equality. * * Note this function does not run in constant time. * * @param obj1 the first asn1 object. * @param obj2 the second asn1 object. * @param [options] compare options: * [includeBitStringContents] true to compare bitStringContents * * @return true if the asn1 objects are equal. */ asn1.equals = function(obj1, obj2, options) { if(forge.util.isArray(obj1)) { if(!forge.util.isArray(obj2)) { return false; } if(obj1.length !== obj2.length) { return false; } for(var i = 0; i < obj1.length; ++i) { if(!asn1.equals(obj1[i], obj2[i])) { return false; } return true; } } if(typeof obj1 !== typeof obj2) { return false; } if(typeof obj1 === 'string') { return obj1 === obj2; } var equal = obj1.tagClass === obj2.tagClass && obj1.type === obj2.type && obj1.constructed === obj2.constructed && obj1.composed === obj2.composed && asn1.equals(obj1.value, obj2.value); if(options && options.includeBitStringContents) { equal = equal && (obj1.bitStringContents === obj2.bitStringContents); } return equal; }; /** * Gets the length of a BER-encoded ASN.1 value. * * In case the length is not specified, undefined is returned. * * @param b the BER-encoded ASN.1 byte buffer, starting with the first * length byte. * * @return the length of the BER-encoded ASN.1 value or undefined. */ asn1.getBerValueLength = function(b) { // TODO: move this function and related DER/BER functions to a der.js // file; better abstract ASN.1 away from der/ber. var b2 = b.getByte(); if(b2 === 0x80) { return undefined; } // see if the length is "short form" or "long form" (bit 8 set) var length; var longForm = b2 & 0x80; if(!longForm) { // length is just the first byte length = b2; } else { // the number of bytes the length is specified in bits 7 through 1 // and each length byte is in big-endian base-256 length = b.getInt((b2 & 0x7F) << 3); } return length; }; /** * Check if the byte buffer has enough bytes. Throws an Error if not. * * @param bytes the byte buffer to parse from. * @param remaining the bytes remaining in the current parsing state. * @param n the number of bytes the buffer must have. */ function _checkBufferLength(bytes, remaining, n) { if(n > remaining) { var error = new Error('Too few bytes to parse DER.'); error.available = bytes.length(); error.remaining = remaining; error.requested = n; throw error; } } /** * Gets the length of a BER-encoded ASN.1 value. * * In case the length is not specified, undefined is returned. * * @param bytes the byte buffer to parse from. * @param remaining the bytes remaining in the current parsing state. * * @return the length of the BER-encoded ASN.1 value or undefined. */ var _getValueLength = function(bytes, remaining) { // TODO: move this function and related DER/BER functions to a der.js // file; better abstract ASN.1 away from der/ber. // fromDer already checked that this byte exists var b2 = bytes.getByte(); remaining--; if(b2 === 0x80) { return undefined; } // see if the length is "short form" or "long form" (bit 8 set) var length; var longForm = b2 & 0x80; if(!longForm) { // length is just the first byte length = b2; } else { // the number of bytes the length is specified in bits 7 through 1 // and each length byte is in big-endian base-256 var longFormBytes = b2 & 0x7F; _checkBufferLength(bytes, remaining, longFormBytes); length = bytes.getInt(longFormBytes << 3); } // FIXME: this will only happen for 32 bit getInt with high bit set if(length < 0) { throw new Error('Negative length: ' + length); } return length; }; /** * Parses an asn1 object from a byte buffer in DER format. * * @param bytes the byte buffer to parse from. * @param [strict] true to be strict when checking value lengths, false to * allow truncated values (default: true). * @param [options] object with options or boolean strict flag * [strict] true to be strict when checking value lengths, false to * allow truncated values (default: true). * [decodeBitStrings] true to attempt to decode the content of * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that * without schema support to understand the data context this can * erroneously decode values that happen to be valid ASN.1. This * flag will be deprecated or removed as soon as schema support is * available. (default: true) * * @return the parsed asn1 object. */ asn1.fromDer = function(bytes, options) { if(options === undefined) { options = { strict: true, decodeBitStrings: true }; } if(typeof options === 'boolean') { options = { strict: options, decodeBitStrings: true }; } if(!('strict' in options)) { options.strict = true; } if(!('decodeBitStrings' in options)) { options.decodeBitStrings = true; } // wrap in buffer if needed if(typeof bytes === 'string') { bytes = forge.util.createBuffer(bytes); } return _fromDer(bytes, bytes.length(), 0, options); } /** * Internal function to parse an asn1 object from a byte buffer in DER format. * * @param bytes the byte buffer to parse from. * @param remaining the number of bytes remaining for this chunk. * @param depth the current parsing depth. * @param options object with same options as fromDer(). * * @return the parsed asn1 object. */ function _fromDer(bytes, remaining, depth, options) { // temporary storage for consumption calculations var start; // minimum length for ASN.1 DER structure is 2 _checkBufferLength(bytes, remaining, 2); // get the first byte var b1 = bytes.getByte(); // consumed one byte remaining--; // get the tag class var tagClass = (b1 & 0xC0); // get the type (bits 1-5) var type = b1 & 0x1F; // get the variable value length and adjust remaining bytes start = bytes.length(); var length = _getValueLength(bytes, remaining); remaining -= start - bytes.length(); // ensure there are enough bytes to get the value if(length !== undefined && length > remaining) { if(options.strict) { var error = new Error('Too few bytes to read ASN.1 value.'); error.available = bytes.length(); error.remaining = remaining; error.requested = length; throw error; } // Note: be lenient with truncated values and use remaining state bytes length = remaining; } // value storage var value; // possible BIT STRING contents storage var bitStringContents; // constructed flag is bit 6 (32 = 0x20) of the first byte var constructed = ((b1 & 0x20) === 0x20); if(constructed) { // parse child asn1 objects from the value value = []; if(length === undefined) { // asn1 object of indefinite length, read until end tag for(;;) { _checkBufferLength(bytes, remaining, 2); if(bytes.bytes(2) === String.fromCharCode(0, 0)) { bytes.getBytes(2); remaining -= 2; break; } start = bytes.length(); value.push(_fromDer(bytes, remaining, depth + 1, options)); remaining -= start - bytes.length(); } } else { // parsing asn1 object of definite length while(length > 0) { start = bytes.length(); value.push(_fromDer(bytes, length, depth + 1, options)); remaining -= start - bytes.length(); length -= start - bytes.length(); } } } // if a BIT STRING, save the contents including padding if(value === undefined && tagClass === asn1.Class.UNIVERSAL && type === asn1.Type.BITSTRING) { bitStringContents = bytes.bytes(length); } // determine if a non-constructed value should be decoded as a composed // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs) // can be used this way. if(value === undefined && options.decodeBitStrings && tagClass === asn1.Class.UNIVERSAL && // FIXME: OCTET STRINGs not yet supported here // .. other parts of forge expect to decode OCTET STRINGs manually (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) && length > 1) { // save read position var savedRead = bytes.read; var savedRemaining = remaining; var unused = 0; if(type === asn1.Type.BITSTRING) { /* The first octet gives the number of bits by which the length of the bit string is less than the next multiple of eight (this is called the "number of unused bits"). The second and following octets give the value of the bit string converted to an octet string. */ _checkBufferLength(bytes, remaining, 1); unused = bytes.getByte(); remaining--; } // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs if(unused === 0) { try { // attempt to parse child asn1 object from the value // (stored in array to signal composed value) start = bytes.length(); var subOptions = { // enforce strict mode to avoid parsing ASN.1 from plain data verbose: options.verbose, strict: true, decodeBitStrings: true }; var composed = _fromDer(bytes, remaining, depth + 1, subOptions); var used = start - bytes.length(); remaining -= used; if(type == asn1.Type.BITSTRING) { used++; } // if the data all decoded and the class indicates UNIVERSAL or // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object var tc = composed.tagClass; if(used === length && (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) { value = [composed]; } } catch(ex) { } } if(value === undefined) { // restore read position bytes.read = savedRead; remaining = savedRemaining; } } if(value === undefined) { // asn1 not constructed or composed, get raw value // TODO: do DER to OID conversion and vice-versa in .toDer? if(length === undefined) { if(options.strict) { throw new Error('Non-constructed ASN.1 object of indefinite length.'); } // be lenient and use remaining state bytes length = remaining; } if(type === asn1.Type.BMPSTRING) { value = ''; for(; length > 0; length -= 2) { _checkBufferLength(bytes, remaining, 2); value += String.fromCharCode(bytes.getInt16()); remaining -= 2; } } else { value = bytes.getBytes(length); } } // add BIT STRING contents if available var asn1Options = bitStringContents === undefined ? null : { bitStringContents: bitStringContents }; // create and return asn1 object return asn1.create(tagClass, type, constructed, value, asn1Options); } /** * Converts the given asn1 object to a buffer of bytes in DER format. * * @param asn1 the asn1 object to convert to bytes. * * @return the buffer of bytes. */ asn1.toDer = function(obj) { var bytes = forge.util.createBuffer(); // build the first byte var b1 = obj.tagClass | obj.type; // for storing the ASN.1 value var value = forge.util.createBuffer(); // use BIT STRING contents if available and data not changed var useBitStringContents = false; if('bitStringContents' in obj) { useBitStringContents = true; if(obj.original) { useBitStringContents = asn1.equals(obj, obj.original); } } if(useBitStringContents) { value.putBytes(obj.bitStringContents); } else if(obj.composed) { // if composed, use each child asn1 object's DER bytes as value // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed // from other asn1 objects if(obj.constructed) { b1 |= 0x20; } else { // type is a bit string, add unused bits of 0x00 value.putByte(0x00); } // add all of the child DER bytes together for(var i = 0; i < obj.value.length; ++i) { if(obj.value[i] !== undefined) { value.putBuffer(asn1.toDer(obj.value[i])); } } } else { // use asn1.value directly if(obj.type === asn1.Type.BMPSTRING) { for(var i = 0; i < obj.value.length; ++i) { value.putInt16(obj.value.charCodeAt(i)); } } else { // ensure integer is minimally-encoded // TODO: should all leading bytes be stripped vs just one? // .. ex '00 00 01' => '01'? if(obj.type === asn1.Type.INTEGER && obj.value.length > 1 && // leading 0x00 for positive integer ((obj.value.charCodeAt(0) === 0 && (obj.value.charCodeAt(1) & 0x80) === 0) || // leading 0xFF for negative integer (obj.value.charCodeAt(0) === 0xFF && (obj.value.charCodeAt(1) & 0x80) === 0x80))) { value.putBytes(obj.value.substr(1)); } else { value.putBytes(obj.value); } } } // add tag byte bytes.putByte(b1); // use "short form" encoding if(value.length() <= 127) { // one byte describes the length // bit 8 = 0 and bits 7-1 = length bytes.putByte(value.length() & 0x7F); } else { // use "long form" encoding // 2 to 127 bytes describe the length // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes // other bytes: length in base 256, big-endian var len = value.length(); var lenBytes = ''; do { lenBytes += String.fromCharCode(len & 0xFF); len = len >>> 8; } while(len > 0); // set first byte to # bytes used to store the length and turn on // bit 8 to indicate long-form length is used bytes.putByte(lenBytes.length | 0x80); // concatenate length bytes in reverse since they were generated // little endian and we need big endian for(var i = lenBytes.length - 1; i >= 0; --i) { bytes.putByte(lenBytes.charCodeAt(i)); } } // concatenate value bytes bytes.putBuffer(value); return bytes; }; /** * Converts an OID dot-separated string to a byte buffer. The byte buffer * contains only the DER-encoded value, not any tag or length bytes. * * @param oid the OID dot-separated string. * * @return the byte buffer. */ asn1.oidToDer = function(oid) { // split OID into individual values var values = oid.split('.'); var bytes = forge.util.createBuffer(); // first byte is 40 * value1 + value2 bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); // other bytes are each value in base 128 with 8th bit set except for // the last byte for each value var last, valueBytes, value, b; for(var i = 2; i < values.length; ++i) { // produce value bytes in reverse because we don't know how many // bytes it will take to store the value last = true; valueBytes = []; value = parseInt(values[i], 10); do { b = value & 0x7F; value = value >>> 7; // if value is not last, then turn on 8th bit if(!last) { b |= 0x80; } valueBytes.push(b); last = false; } while(value > 0); // add value bytes in reverse (needs to be in big endian) for(var n = valueBytes.length - 1; n >= 0; --n) { bytes.putByte(valueBytes[n]); } } return bytes; }; /** * Converts a DER-encoded byte buffer to an OID dot-separated string. The * byte buffer should contain only the DER-encoded value, not any tag or * length bytes. * * @param bytes the byte buffer. * * @return the OID dot-separated string. */ asn1.derToOid = function(bytes) { var oid; // wrap in buffer if needed if(typeof bytes === 'string') { bytes = forge.util.createBuffer(bytes); } // first byte is 40 * value1 + value2 var b = bytes.getByte(); oid = Math.floor(b / 40) + '.' + (b % 40); // other bytes are each value in base 128 with 8th bit set except for // the last byte for each value var value = 0; while(bytes.length() > 0) { b = bytes.getByte(); value = value << 7; // not the last byte for the value if(b & 0x80) { value += b & 0x7F; } else { // last byte oid += '.' + (value + b); value = 0; } } return oid; }; /** * Converts a UTCTime value to a date. * * Note: GeneralizedTime has 4 digits for the year and is used for X.509 * dates passed 2049. Parsing that structure hasn't been implemented yet. * * @param utc the UTCTime value to convert. * * @return the date. */ asn1.utcTimeToDate = function(utc) { /* The following formats can be used: YYMMDDhhmmZ YYMMDDhhmm+hh'mm' YYMMDDhhmm-hh'mm' YYMMDDhhmmssZ YYMMDDhhmmss+hh'mm' YYMMDDhhmmss-hh'mm' Where: YY is the least significant two digits of the year MM is the month (01 to 12) DD is the day (01 to 31) hh is the hour (00 to 23) mm are the minutes (00 to 59) ss are the seconds (00 to 59) Z indicates that local time is GMT, + indicates that local time is later than GMT, and - indicates that local time is earlier than GMT hh' is the absolute value of the offset from GMT in hours mm' is the absolute value of the offset from GMT in minutes */ var date = new Date(); // if YY >= 50 use 19xx, if YY < 50 use 20xx var year = parseInt(utc.substr(0, 2), 10); year = (year >= 50) ? 1900 + year : 2000 + year; var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month var DD = parseInt(utc.substr(4, 2), 10); var hh = parseInt(utc.substr(6, 2), 10); var mm = parseInt(utc.substr(8, 2), 10); var ss = 0; // not just YYMMDDhhmmZ if(utc.length > 11) { // get character after minutes var c = utc.charAt(10); var end = 10; // see if seconds are present if(c !== '+' && c !== '-') { // get seconds ss = parseInt(utc.substr(10, 2), 10); end += 2; } } // update date date.setUTCFullYear(year, MM, DD); date.setUTCHours(hh, mm, ss, 0); if(end) { // get +/- after end of time c = utc.charAt(end); if(c === '+' || c === '-') { // get hours+minutes offset var hhoffset = parseInt(utc.substr(end + 1, 2), 10); var mmoffset = parseInt(utc.substr(end + 4, 2), 10); // calculate offset in milliseconds var offset = hhoffset * 60 + mmoffset; offset *= 60000; // apply offset if(c === '+') { date.setTime(+date - offset); } else { date.setTime(+date + offset); } } } return date; }; /** * Converts a GeneralizedTime value to a date. * * @param gentime the GeneralizedTime value to convert. * * @return the date. */ asn1.generalizedTimeToDate = function(gentime) { /* The following formats can be used: YYYYMMDDHHMMSS YYYYMMDDHHMMSS.fff YYYYMMDDHHMMSSZ YYYYMMDDHHMMSS.fffZ YYYYMMDDHHMMSS+hh'mm' YYYYMMDDHHMMSS.fff+hh'mm' YYYYMMDDHHMMSS-hh'mm' YYYYMMDDHHMMSS.fff-hh'mm' Where: YYYY is the year MM is the month (01 to 12) DD is the day (01 to 31) hh is the hour (00 to 23) mm are the minutes (00 to 59) ss are the seconds (00 to 59) .fff is the second fraction, accurate to three decimal places Z indicates that local time is GMT, + indicates that local time is later than GMT, and - indicates that local time is earlier than GMT hh' is the absolute value of the offset from GMT in hours mm' is the absolute value of the offset from GMT in minutes */ var date = new Date(); var YYYY = parseInt(gentime.substr(0, 4), 10); var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month var DD = parseInt(gentime.substr(6, 2), 10); var hh = parseInt(gentime.substr(8, 2), 10); var mm = parseInt(gentime.substr(10, 2), 10); var ss = parseInt(gentime.substr(12, 2), 10); var fff = 0; var offset = 0; var isUTC = false; if(gentime.charAt(gentime.length - 1) === 'Z') { isUTC = true; } var end = gentime.length - 5, c = gentime.charAt(end); if(c === '+' || c === '-') { // get hours+minutes offset var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); // calculate offset in milliseconds offset = hhoffset * 60 + mmoffset; offset *= 60000; // apply offset if(c === '+') { offset *= -1; } isUTC = true; } // check for second fraction if(gentime.charAt(14) === '.') { fff = parseFloat(gentime.substr(14), 10) * 1000; } if(isUTC) { date.setUTCFullYear(YYYY, MM, DD); date.setUTCHours(hh, mm, ss, fff); // apply offset date.setTime(+date + offset); } else { date.setFullYear(YYYY, MM, DD); date.setHours(hh, mm, ss, fff); } return date; }; /** * Converts a date to a UTCTime value. * * Note: GeneralizedTime has 4 digits for the year and is used for X.509 * dates passed 2049. Converting to a GeneralizedTime hasn't been * implemented yet. * * @param date the date to convert. * * @return the UTCTime value. */ asn1.dateToUtcTime = function(date) { // TODO: validate; currently assumes proper format if(typeof date === 'string') { return date; } var rval = ''; // create format YYMMDDhhmmssZ var format = []; format.push(('' + date.getUTCFullYear()).substr(2)); format.push('' + (date.getUTCMonth() + 1)); format.push('' + date.getUTCDate()); format.push('' + date.getUTCHours()); format.push('' + date.getUTCMinutes()); format.push('' + date.getUTCSeconds()); // ensure 2 digits are used for each format entry for(var i = 0; i < format.length; ++i) { if(format[i].length < 2) { rval += '0'; } rval += format[i]; } rval += 'Z'; return rval; }; /** * Converts a date to a GeneralizedTime value. * * @param date the date to convert. * * @return the GeneralizedTime value as a string. */ asn1.dateToGeneralizedTime = function(date) { // TODO: validate; currently assumes proper format if(typeof date === 'string') { return date; } var rval = ''; // create format YYYYMMDDHHMMSSZ var format = []; format.push('' + date.getUTCFullYear()); format.push('' + (date.getUTCMonth() + 1)); format.push('' + date.getUTCDate()); format.push('' + date.getUTCHours()); format.push('' + date.getUTCMinutes()); format.push('' + date.getUTCSeconds()); // ensure 2 digits are used for each format entry for(var i = 0; i < format.length; ++i) { if(format[i].length < 2) { rval += '0'; } rval += format[i]; } rval += 'Z'; return rval; }; /** * Converts a javascript integer to a DER-encoded byte buffer to be used * as the value for an INTEGER type. * * @param x the integer. * * @return the byte buffer. */ asn1.integerToDer = function(x) { var rval = forge.util.createBuffer(); if(x >= -0x80 && x < 0x80) { return rval.putSignedInt(x, 8); } if(x >= -0x8000 && x < 0x8000) { return rval.putSignedInt(x, 16); } if(x >= -0x800000 && x < 0x800000) { return rval.putSignedInt(x, 24); } if(x >= -0x80000000 && x < 0x80000000) { return rval.putSignedInt(x, 32); } var error = new Error('Integer too large; max is 32-bits.'); error.integer = x; throw error; }; /** * Converts a DER-encoded byte buffer to a javascript integer. This is * typically used to decode the value of an INTEGER type. * * @param bytes the byte buffer. * * @return the integer. */ asn1.derToInteger = function(bytes) { // wrap in buffer if needed if(typeof bytes === 'string') { bytes = forge.util.createBuffer(bytes); } var n = bytes.length() * 8; if(n > 32) { throw new Error('Integer too large; max is 32-bits.'); } return bytes.getSignedInt(n); }; /** * Validates the that given ASN.1 object is at least a super set of the * given ASN.1 structure. Only tag classes and types are checked. An * optional map may also be provided to capture ASN.1 values while the * structure is checked. * * To capture an ASN.1 value, set an object in the validator's 'capture' * parameter to the key to use in the capture map. To capture the full * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including * the leading unused bits counter byte, specify 'captureBitStringContents'. * To capture BIT STRING bytes, without the leading unused bits counter byte, * specify 'captureBitStringValue'. * * Objects in the validator may set a field 'optional' to true to indicate * that it isn't necessary to pass validation. * * @param obj the ASN.1 object to validate. * @param v the ASN.1 structure validator. * @param capture an optional map to capture values in. * @param errors an optional array for storing validation errors. * * @return true on success, false on failure. */ asn1.validate = function(obj, v, capture, errors) { var rval = false; // ensure tag class and type are the same if specified if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') && (obj.type === v.type || typeof(v.type) === 'undefined')) { // ensure constructed flag is the same if specified if(obj.constructed === v.constructed || typeof(v.constructed) === 'undefined') { rval = true; // handle sub values if(v.value && forge.util.isArray(v.value)) { var j = 0; for(var i = 0; rval && i < v.value.length; ++i) { rval = v.value[i].optional || false; if(obj.value[j]) { rval = asn1.validate(obj.value[j], v.value[i], capture, errors); if(rval) { ++j; } else if(v.value[i].optional) { rval = true; } } if(!rval && errors) { errors.push( '[' + v.name + '] ' + 'Tag class "' + v.tagClass + '", type "' + v.type + '" expected value length "' + v.value.length + '", got "' + obj.value.length + '"'); } } } if(rval && capture) { if(v.capture) { capture[v.capture] = obj.value; } if(v.captureAsn1) { capture[v.captureAsn1] = obj; } if(v.captureBitStringContents && 'bitStringContents' in obj) { capture[v.captureBitStringContents] = obj.bitStringContents; } if(v.captureBitStringValue && 'bitStringContents' in obj) { var value; if(obj.bitStringContents.length < 2) { capture[v.captureBitStringValue] = ''; } else { // FIXME: support unused bits with data shifting var unused = obj.bitStringContents.charCodeAt(0); if(unused !== 0) { throw new Error( 'captureBitStringValue only supported for zero unused bits'); } capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); } } } } else if(errors) { errors.push( '[' + v.name + '] ' + 'Expected constructed "' + v.constructed + '", got "' + obj.constructed + '"'); } } else if(errors) { if(obj.tagClass !== v.tagClass) { errors.push( '[' + v.name + '] ' + 'Expected tag class "' + v.tagClass + '", got "' + obj.tagClass + '"'); } if(obj.type !== v.type) { errors.push( '[' + v.name + '] ' + 'Expected type "' + v.type + '", got "' + obj.type + '"'); } } return rval; }; // regex for testing for non-latin characters var _nonLatinRegex = /[^\\u0000-\\u00ff]/; /** * Pretty prints an ASN.1 object to a string. * * @param obj the object to write out. * @param level the level in the tree. * @param indentation the indentation to use. * * @return the string. */ asn1.prettyPrint = function(obj, level, indentation) { var rval = ''; // set default level and indentation level = level || 0; indentation = indentation || 2; // start new line for deep levels if(level > 0) { rval += '\n'; } // create indent var indent = ''; for(var i = 0; i < level * indentation; ++i) { indent += ' '; } // print class:type rval += indent + 'Tag: '; switch(obj.tagClass) { case asn1.Class.UNIVERSAL: rval += 'Universal:'; break; case asn1.Class.APPLICATION: rval += 'Application:'; break; case asn1.Class.CONTEXT_SPECIFIC: rval += 'Context-Specific:'; break; case asn1.Class.PRIVATE: rval += 'Private:'; break; } if(obj.tagClass === asn1.Class.UNIVERSAL) { rval += obj.type; // known types switch(obj.type) { case asn1.Type.NONE: rval += ' (None)'; break; case asn1.Type.BOOLEAN: rval += ' (Boolean)'; break; case asn1.Type.INTEGER: rval += ' (Integer)'; break; case asn1.Type.BITSTRING: rval += ' (Bit string)'; break; case asn1.Type.OCTETSTRING: rval += ' (Octet string)'; break; case asn1.Type.NULL: rval += ' (Null)'; break; case asn1.Type.OID: rval += ' (Object Identifier)'; break; case asn1.Type.ODESC: rval += ' (Object Descriptor)'; break; case asn1.Type.EXTERNAL: rval += ' (External or Instance of)'; break; case asn1.Type.REAL: rval += ' (Real)'; break; case asn1.Type.ENUMERATED: rval += ' (Enumerated)'; break; case asn1.Type.EMBEDDED: rval += ' (Embedded PDV)'; break; case asn1.Type.UTF8: rval += ' (UTF8)'; break; case asn1.Type.ROID: rval += ' (Relative Object Identifier)'; break; case asn1.Type.SEQUENCE: rval += ' (Sequence)'; break; case asn1.Type.SET: rval += ' (Set)'; break; case asn1.Type.PRINTABLESTRING: rval += ' (Printable String)'; break; case asn1.Type.IA5String: rval += ' (IA5String (ASCII))'; break; case asn1.Type.UTCTIME: rval += ' (UTC time)'; break; case asn1.Type.GENERALIZEDTIME: rval += ' (Generalized time)'; break; case asn1.Type.BMPSTRING: rval += ' (BMP String)'; break; } } else { rval += obj.type; } rval += '\n'; rval += indent + 'Constructed: ' + obj.constructed + '\n'; if(obj.composed) { var subvalues = 0; var sub = ''; for(var i = 0; i < obj.value.length; ++i) { if(obj.value[i] !== undefined) { subvalues += 1; sub += asn1.prettyPrint(obj.value[i], level + 1, indentation); if((i + 1) < obj.value.length) { sub += ','; } } } rval += indent + 'Sub values: ' + subvalues + sub; } else { rval += indent + 'Value: '; if(obj.type === asn1.Type.OID) { var oid = asn1.derToOid(obj.value); rval += oid; if(forge.pki && forge.pki.oids) { if(oid in forge.pki.oids) { rval += ' (' + forge.pki.oids[oid] + ') '; } } } if(obj.type === asn1.Type.INTEGER) { try { rval += asn1.derToInteger(obj.value); } catch(ex) { rval += '0x' + forge.util.bytesToHex(obj.value); } } else if(obj.type === asn1.Type.BITSTRING) { // TODO: shift bits as needed to display without padding if(obj.value.length > 1) { // remove unused bits field rval += '0x' + forge.util.bytesToHex(obj.value.slice(1)); } else { rval += '(none)'; } // show unused bit count if(obj.value.length > 0) { var unused = obj.value.charCodeAt(0); if(unused == 1) { rval += ' (1 unused bit shown)'; } else if(unused > 1) { rval += ' (' + unused + ' unused bits shown)'; } } } else if(obj.type === asn1.Type.OCTETSTRING) { if(!_nonLatinRegex.test(obj.value)) { rval += '(' + obj.value + ') '; } rval += '0x' + forge.util.bytesToHex(obj.value); } else if(obj.type === asn1.Type.UTF8) { rval += forge.util.decodeUtf8(obj.value); } else if(obj.type === asn1.Type.PRINTABLESTRING || obj.type === asn1.Type.IA5String) { rval += obj.value; } else if(_nonLatinRegex.test(obj.value)) { rval += '0x' + forge.util.bytesToHex(obj.value); } else if(obj.value.length === 0) { rval += '[null]'; } else { rval += obj.value; } } return rval; }; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { /** * Partial implementation of PKCS#1 v2.2: RSA-OEAP * * Modified but based on the following MIT and BSD licensed code: * * https://github.com/kjur/jsjws/blob/master/rsa.js: * * The 'jsjws'(JSON Web Signature JavaScript Library) License * * Copyright (c) 2012 Kenji Urushima * * 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. * * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain: * * RSAES-OAEP.js * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $ * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002) * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003. * Contact: ellis@nukinetics.com * Distributed under the BSD License. * * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125 * * @author Evan Jones (http://evanjones.ca/) * @author Dave Longley * * Copyright (c) 2013-2014 Digital Bazaar, Inc. */ var forge = __webpack_require__(0); __webpack_require__(1); __webpack_require__(3); __webpack_require__(18); // shortcut for PKCS#1 API var pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {}; /** * Encode the given RSAES-OAEP message (M) using key, with optional label (L) * and seed. * * This method does not perform RSA encryption, it only encodes the message * using RSAES-OAEP. * * @param key the RSA key to use. * @param message the message to encode. * @param options the options to use: * label an optional label to use. * seed the seed to use. * md the message digest object to use, undefined for SHA-1. * mgf1 optional mgf1 parameters: * md the message digest object to use for MGF1. * * @return the encoded message bytes. */ pkcs1.encode_rsa_oaep = function(key, message, options) { // parse arguments var label; var seed; var md; var mgf1Md; // legacy args (label, seed, md) if(typeof options === 'string') { label = options; seed = arguments[3] || undefined; md = arguments[4] || undefined; } else if(options) { label = options.label || undefined; seed = options.seed || undefined; md = options.md || undefined; if(options.mgf1 && options.mgf1.md) { mgf1Md = options.mgf1.md; } } // default OAEP to SHA-1 message digest if(!md) { md = forge.md.sha1.create(); } else { md.start(); } // default MGF-1 to same as OAEP if(!mgf1Md) { mgf1Md = md; } // compute length in bytes and check output var keyLength = Math.ceil(key.n.bitLength() / 8); var maxLength = keyLength - 2 * md.digestLength - 2; if(message.length > maxLength) { var error = new Error('RSAES-OAEP input message length is too long.'); error.length = message.length; error.maxLength = maxLength; throw error; } if(!label) { label = ''; } md.update(label, 'raw'); var lHash = md.digest(); var PS = ''; var PS_length = maxLength - message.length; for (var i = 0; i < PS_length; i++) { PS += '\x00'; } var DB = lHash.getBytes() + PS + '\x01' + message; if(!seed) { seed = forge.random.getBytes(md.digestLength); } else if(seed.length !== md.digestLength) { var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' + 'match the digest length.'); error.seedLength = seed.length; error.digestLength = md.digestLength; throw error; } var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length); var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length); // return encoded message return '\x00' + maskedSeed + maskedDB; }; /** * Decode the given RSAES-OAEP encoded message (EM) using key, with optional * label (L). * * This method does not perform RSA decryption, it only decodes the message * using RSAES-OAEP. * * @param key the RSA key to use. * @param em the encoded message to decode. * @param options the options to use: * label an optional label to use. * md the message digest object to use for OAEP, undefined for SHA-1. * mgf1 optional mgf1 parameters: * md the message digest object to use for MGF1. * * @return the decoded message bytes. */ pkcs1.decode_rsa_oaep = function(key, em, options) { // parse args var label; var md; var mgf1Md; // legacy args if(typeof options === 'string') { label = options; md = arguments[3] || undefined; } else if(options) { label = options.label || undefined; md = options.md || undefined; if(options.mgf1 && options.mgf1.md) { mgf1Md = options.mgf1.md; } } // compute length in bytes var keyLength = Math.ceil(key.n.bitLength() / 8); if(em.length !== keyLength) { var error = new Error('RSAES-OAEP encoded message length is invalid.'); error.length = em.length; error.expectedLength = keyLength; throw error; } // default OAEP to SHA-1 message digest if(md === undefined) { md = forge.md.sha1.create(); } else { md.start(); } // default MGF-1 to same as OAEP if(!mgf1Md) { mgf1Md = md; } if(keyLength < 2 * md.digestLength + 2) { throw new Error('RSAES-OAEP key is too short for the hash function.'); } if(!label) { label = ''; } md.update(label, 'raw'); var lHash = md.digest().getBytes(); // split the message into its parts var y = em.charAt(0); var maskedSeed = em.substring(1, md.digestLength + 1); var maskedDB = em.substring(1 + md.digestLength); var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length); var lHashPrime = db.substring(0, md.digestLength); // constant time check that all values match what is expected var error = (y !== '\x00'); // constant time check lHash vs lHashPrime for(var i = 0; i < md.digestLength; ++i) { error |= (lHash.charAt(i) !== lHashPrime.charAt(i)); } // "constant time" find the 0x1 byte separating the padding (zeros) from the // message // TODO: It must be possible to do this in a better/smarter way? var in_ps = 1; var index = md.digestLength; for(var j = md.digestLength; j < db.length; j++) { var code = db.charCodeAt(j); var is_0 = (code & 0x1) ^ 0x1; // non-zero if not 0 or 1 in the ps section var error_mask = in_ps ? 0xfffe : 0x0000; error |= (code & error_mask); // latch in_ps to zero after we find 0x1 in_ps = in_ps & is_0; index += in_ps; } if(error || db.charCodeAt(index) !== 0x1) { throw new Error('Invalid RSAES-OAEP padding.'); } return db.substring(index + 1); }; function rsa_mgf1(seed, maskLength, hash) { // default to SHA-1 message digest if(!hash) { hash = forge.md.sha1.create(); } var t = ''; var count = Math.ceil(maskLength / hash.digestLength); for(var i = 0; i < count; ++i) { var c = String.fromCharCode( (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF); hash.start(); hash.update(seed + c); t += hash.digest().getBytes(); } return t.substring(0, maskLength); } /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { /** * A javascript implementation of a cryptographically-secure * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed * here though the use of SHA-256 is not enforced; when generating an * a PRNG context, the hashing algorithm and block cipher used for * the generator are specified via a plugin. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. */ var forge = __webpack_require__(0); __webpack_require__(1); var _crypto = null; if(forge.util.isNodejs && !forge.options.usePureJavaScript && !process.versions['node-webkit']) { _crypto = __webpack_require__(5); } /* PRNG API */ var prng = module.exports = forge.prng = forge.prng || {}; /** * Creates a new PRNG context. * * A PRNG plugin must be passed in that will provide: * * 1. A function that initializes the key and seed of a PRNG context. It * will be given a 16 byte key and a 16 byte seed. Any key expansion * or transformation of the seed from a byte string into an array of * integers (or similar) should be performed. * 2. The cryptographic function used by the generator. It takes a key and * a seed. * 3. A seed increment function. It takes the seed and returns seed + 1. * 4. An api to create a message digest. * * For an example, see random.js. * * @param plugin the PRNG plugin to use. */ prng.create = function(plugin) { var ctx = { plugin: plugin, key: null, seed: null, time: null, // number of reseeds so far reseeds: 0, // amount of data generated so far generated: 0 }; // create 32 entropy pools (each is a message digest) var md = plugin.md; var pools = new Array(32); for(var i = 0; i < 32; ++i) { pools[i] = md.create(); } ctx.pools = pools; // entropy pools are written to cyclically, starting at index 0 ctx.pool = 0; /** * Generates random bytes. The bytes may be generated synchronously or * asynchronously. Web workers must use the asynchronous interface or * else the behavior is undefined. * * @param count the number of random bytes to generate. * @param [callback(err, bytes)] called once the operation completes. * * @return count random bytes as a string. */ ctx.generate = function(count, callback) { // do synchronously if(!callback) { return ctx.generateSync(count); } // simple generator using counter-based CBC var cipher = ctx.plugin.cipher; var increment = ctx.plugin.increment; var formatKey = ctx.plugin.formatKey; var formatSeed = ctx.plugin.formatSeed; var b = forge.util.createBuffer(); // reset key for every request ctx.key = null; generate(); function generate(err) { if(err) { return callback(err); } // sufficient bytes generated if(b.length() >= count) { return callback(null, b.getBytes(count)); } // if amount of data generated is greater than 1 MiB, trigger reseed if(ctx.generated > 0xfffff) { ctx.key = null; } if(ctx.key === null) { // prevent stack overflow return forge.util.nextTick(function() { _reseed(generate); }); } // generate the random bytes var bytes = cipher(ctx.key, ctx.seed); ctx.generated += bytes.length; b.putBytes(bytes); // generate bytes for a new key and seed ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); forge.util.setImmediate(generate); } }; /** * Generates random bytes synchronously. * * @param count the number of random bytes to generate. * * @return count random bytes as a string. */ ctx.generateSync = function(count) { // simple generator using counter-based CBC var cipher = ctx.plugin.cipher; var increment = ctx.plugin.increment; var formatKey = ctx.plugin.formatKey; var formatSeed = ctx.plugin.formatSeed; // reset key for every request ctx.key = null; var b = forge.util.createBuffer(); while(b.length() < count) { // if amount of data generated is greater than 1 MiB, trigger reseed if(ctx.generated > 0xfffff) { ctx.key = null; } if(ctx.key === null) { _reseedSync(); } // generate the random bytes var bytes = cipher(ctx.key, ctx.seed); ctx.generated += bytes.length; b.putBytes(bytes); // generate bytes for a new key and seed ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); } return b.getBytes(count); }; /** * Private function that asynchronously reseeds a generator. * * @param callback(err) called once the operation completes. */ function _reseed(callback) { if(ctx.pools[0].messageLength >= 32) { _seed(); return callback(); } // not enough seed data... var needed = (32 - ctx.pools[0].messageLength) << 5; ctx.seedFile(needed, function(err, bytes) { if(err) { return callback(err); } ctx.collect(bytes); _seed(); callback(); }); } /** * Private function that synchronously reseeds a generator. */ function _reseedSync() { if(ctx.pools[0].messageLength >= 32) { return _seed(); } // not enough seed data... var needed = (32 - ctx.pools[0].messageLength) << 5; ctx.collect(ctx.seedFileSync(needed)); _seed(); } /** * Private function that seeds a generator once enough bytes are available. */ function _seed() { // create a plugin-based message digest var md = ctx.plugin.md.create(); // digest pool 0's entropy and restart it md.update(ctx.pools[0].digest().getBytes()); ctx.pools[0].start(); // digest the entropy of other pools whose index k meet the // condition '2^k mod n == 0' where n is the number of reseeds var k = 1; for(var i = 1; i < 32; ++i) { // prevent signed numbers from being used k = (k === 31) ? 0x80000000 : (k << 2); if(k % ctx.reseeds === 0) { md.update(ctx.pools[i].digest().getBytes()); ctx.pools[i].start(); } } // get digest for key bytes and iterate again for seed bytes var keyBytes = md.digest().getBytes(); md.start(); md.update(keyBytes); var seedBytes = md.digest().getBytes(); // update ctx.key = ctx.plugin.formatKey(keyBytes); ctx.seed = ctx.plugin.formatSeed(seedBytes); ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1; ctx.generated = 0; } /** * The built-in default seedFile. This seedFile is used when entropy * is needed immediately. * * @param needed the number of bytes that are needed. * * @return the random bytes. */ function defaultSeedFile(needed) { // use window.crypto.getRandomValues strong source of entropy if available var getRandomValues = null; if(typeof window !== 'undefined') { var _crypto = window.crypto || window.msCrypto; if(_crypto && _crypto.getRandomValues) { getRandomValues = function(arr) { return _crypto.getRandomValues(arr); }; } } var b = forge.util.createBuffer(); if(getRandomValues) { while(b.length() < needed) { // max byte length is 65536 before QuotaExceededError is thrown // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); var entropy = new Uint32Array(Math.floor(count)); try { getRandomValues(entropy); for(var i = 0; i < entropy.length; ++i) { b.putInt32(entropy[i]); } } catch(e) { /* only ignore QuotaExceededError */ if(!(typeof QuotaExceededError !== 'undefined' && e instanceof QuotaExceededError)) { throw e; } } } } // be sad and add some weak random data if(b.length() < needed) { /* Draws from Park-Miller "minimal standard" 31 bit PRNG, implemented with David G. Carta's optimization: with 32 bit math and without division (Public Domain). */ var hi, lo, next; var seed = Math.floor(Math.random() * 0x010000); while(b.length() < needed) { lo = 16807 * (seed & 0xFFFF); hi = 16807 * (seed >> 16); lo += (hi & 0x7FFF) << 16; lo += hi >> 15; lo = (lo & 0x7FFFFFFF) + (lo >> 31); seed = lo & 0xFFFFFFFF; // consume lower 3 bytes of seed for(var i = 0; i < 3; ++i) { // throw in more pseudo random next = seed >>> (i << 3); next ^= Math.floor(Math.random() * 0x0100); b.putByte(String.fromCharCode(next & 0xFF)); } } } return b.getBytes(needed); } // initialize seed file APIs if(_crypto) { // use nodejs async API ctx.seedFile = function(needed, callback) { _crypto.randomBytes(needed, function(err, bytes) { if(err) { return callback(err); } callback(null, bytes.toString()); }); }; // use nodejs sync API ctx.seedFileSync = function(needed) { return _crypto.randomBytes(needed).toString(); }; } else { ctx.seedFile = function(needed, callback) { try { callback(null, defaultSeedFile(needed)); } catch(e) { callback(e); } }; ctx.seedFileSync = defaultSeedFile; } /** * Adds entropy to a prng ctx's accumulator. * * @param bytes the bytes of entropy as a string. */ ctx.collect = function(bytes) { // iterate over pools distributing entropy cyclically var count = bytes.length; for(var i = 0; i < count; ++i) { ctx.pools[ctx.pool].update(bytes.substr(i, 1)); ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1; } }; /** * Collects an integer of n bits. * * @param i the integer entropy. * @param n the number of bits in the integer. */ ctx.collectInt = function(i, n) { var bytes = ''; for(var x = 0; x < n; x += 8) { bytes += String.fromCharCode((i >> x) & 0xFF); } ctx.collect(bytes); }; /** * Registers a Web Worker to receive immediate entropy from the main thread. * This method is required until Web Workers can access the native crypto * API. This method should be called twice for each created worker, once in * the main thread, and once in the worker itself. * * @param worker the worker to register. */ ctx.registerWorker = function(worker) { // worker receives random bytes if(worker === self) { ctx.seedFile = function(needed, callback) { function listener(e) { var data = e.data; if(data.forge && data.forge.prng) { self.removeEventListener('message', listener); callback(data.forge.prng.err, data.forge.prng.bytes); } } self.addEventListener('message', listener); self.postMessage({forge: {prng: {needed: needed}}}); }; } else { // main thread sends random bytes upon request var listener = function(e) { var data = e.data; if(data.forge && data.forge.prng) { ctx.seedFile(data.forge.prng.needed, function(err, bytes) { worker.postMessage({forge: {prng: {err: err, bytes: bytes}}}); }); } }; // TODO: do we need to remove the event listener when the worker dies? worker.addEventListener('message', listener); } }; return ctx; }; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { /** * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation. * * @author Dave Longley * * Copyright (c) 2010-2015 Digital Bazaar, Inc. */ var forge = __webpack_require__(0); __webpack_require__(2); __webpack_require__(1); var sha1 = module.exports = forge.sha1 = forge.sha1 || {}; forge.md.sha1 = forge.md.algorithms.sha1 = sha1; /** * Creates a SHA-1 message digest object. * * @return a message digest object. */ sha1.create = function() { // do initialization as necessary if(!_initialized) { _init(); } // SHA-1 state contains five 32-bit integers var _state = null; // input buffer var _input = forge.util.createBuffer(); // used for word storage var _w = new Array(80); // message digest object var md = { algorithm: 'sha1', blockLength: 64, digestLength: 20, // 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: 8 }; /** * 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.messageLength64 for backwards-compatibility) md.fullMessageLength = md.messageLength64 = []; var int32s = md.messageLengthSize / 4; for(var i = 0; i < int32s; ++i) { md.fullMessageLength.push(0); } _input = forge.util.createBuffer(); _state = { h0: 0x67452301, h1: 0xEFCDAB89, h2: 0x98BADCFE, h3: 0x10325476, h4: 0xC3D2E1F0 }; 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(_state, _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-1 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 448 mod 512. In other words, the data to be digested must be a multiple of 512 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 8 bytes (64 bits), that means that the last segment of the data must have 56 bytes (448 bits) of message and padding. Therefore, the length of the message plus the padding must be congruent to 448 mod 512 because 512 - 128 = 448. 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 448 mod 512, then 512 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 next, carry; var bits = md.fullMessageLength[0] * 8; for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { next = md.fullMessageLength[i + 1] * 8; carry = (next / 0x100000000) >>> 0; bits += carry; finalBlock.putInt32(bits >>> 0); bits = next >>> 0; } finalBlock.putInt32(bits); var s2 = { h0: _state.h0, h1: _state.h1, h2: _state.h2, h3: _state.h3, h4: _state.h4 }; _update(s2, _w, finalBlock); var rval = forge.util.createBuffer(); rval.putInt32(s2.h0); rval.putInt32(s2.h1); rval.putInt32(s2.h2); rval.putInt32(s2.h3); rval.putInt32(s2.h4); return rval; }; return md; }; // sha-1 padding bytes not initialized yet var _padding = null; var _initialized = false; /** * Initializes the constant tables. */ function _init() { // create padding _padding = String.fromCharCode(128); _padding += forge.util.fillString(String.fromCharCode(0x00), 64); // now initialized _initialized = true; } /** * Updates a SHA-1 state with the given byte buffer. * * @param s the SHA-1 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 (64 byte) chunks var t, a, b, c, d, e, f, i; var len = bytes.length(); while(len >= 64) { // the w array will be populated with sixteen 32-bit big-endian words // and then extended into 80 32-bit words according to SHA-1 algorithm // and for 32-79 using Max Locktyukhin's optimization // initialize hash value for this chunk a = s.h0; b = s.h1; c = s.h2; d = s.h3; e = s.h4; // round 1 for(i = 0; i < 16; ++i) { t = bytes.getInt32(); w[i] = t; f = d ^ (b & (c ^ d)); t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } for(; i < 20; ++i) { t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); t = (t << 1) | (t >>> 31); w[i] = t; f = d ^ (b & (c ^ d)); t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } // round 2 for(; i < 32; ++i) { t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); t = (t << 1) | (t >>> 31); w[i] = t; f = b ^ c ^ d; t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } for(; i < 40; ++i) { t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); t = (t << 2) | (t >>> 30); w[i] = t; f = b ^ c ^ d; t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } // round 3 for(; i < 60; ++i) { t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); t = (t << 2) | (t >>> 30); w[i] = t; f = (b & c) | (d & (b ^ c)); t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } // round 4 for(; i < 80; ++i) { t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); t = (t << 2) | (t >>> 30); w[i] = t; f = b ^ c ^ d; t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } // update hash state s.h0 = (s.h0 + a) | 0; s.h1 = (s.h1 + b) | 0; s.h2 = (s.h2 + c) | 0; s.h3 = (s.h3 + d) | 0; s.h4 = (s.h4 + e) | 0; len -= 64; } } /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { /** * Prime number generation API. * * @author Dave Longley * * Copyright (c) 2014 Digital Bazaar, Inc. */ var forge = __webpack_require__(0); __webpack_require__(1); __webpack_require__(8); __webpack_require__(3); (function() { // forge.prime already defined if(forge.prime) { module.exports = forge.prime; return; } /* PRIME API */ var prime = module.exports = forge.prime = forge.prime || {}; var BigInteger = forge.jsbn.BigInteger; // primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; var THIRTY = new BigInteger(null); THIRTY.fromInt(30); var op_or = function(x, y) {return x|y;}; /** * Generates a random probable prime with the given number of bits. * * Alternative algorithms can be specified by name as a string or as an * object with custom options like so: * * { * name: 'PRIMEINC', * options: { * maxBlockTime: , * millerRabinTests: , * workerScript: , * workers: . * workLoad: the size of the work load, ie: number of possible prime * numbers for each web worker to check per work assignment, * (default: 100). * } * } * * @param bits the number of bits for the prime number. * @param options the options to use. * [algorithm] the algorithm to use (default: 'PRIMEINC'). * [prng] a custom crypto-secure pseudo-random number generator to use, * that must define "getBytesSync". * * @return callback(err, num) called once the operation completes. */ prime.generateProbablePrime = function(bits, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } options = options || {}; // default to PRIMEINC algorithm var algorithm = options.algorithm || 'PRIMEINC'; if(typeof algorithm === 'string') { algorithm = {name: algorithm}; } algorithm.options = algorithm.options || {}; // create prng with api that matches BigInteger secure random var prng = options.prng || forge.random; var rng = { // x is an array to fill with bytes nextBytes: function(x) { var b = prng.getBytesSync(x.length); for(var i = 0; i < x.length; ++i) { x[i] = b.charCodeAt(i); } } }; if(algorithm.name === 'PRIMEINC') { return primeincFindPrime(bits, rng, algorithm.options, callback); } throw new Error('Invalid prime generation algorithm: ' + algorithm.name); }; function primeincFindPrime(bits, rng, options, callback) { if('workers' in options) { return primeincFindPrimeWithWorkers(bits, rng, options, callback); } return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); } function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { // initialize random number var num = generateRandom(bits, rng); /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The number we are given is always aligned at 30k + 1. Each time the number is determined not to be prime we add to get to the next 'i', eg: if the number was at 30k + 1 we add 6. */ var deltaIdx = 0; // get required number of MR tests var mrTests = getMillerRabinTests(num.bitLength()); if('millerRabinTests' in options) { mrTests = options.millerRabinTests; } // find prime nearest to 'num' for maxBlockTime ms // 10 ms gives 5ms of leeway for other calculations before dropping // below 60fps (1000/60 == 16.67), but in reality, the number will // likely be higher due to an 'atomic' big int modPow var maxBlockTime = 10; if('maxBlockTime' in options) { maxBlockTime = options.maxBlockTime; } _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); } function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { var start = +new Date(); do { // overflow, regenerate random number if(num.bitLength() > bits) { num = generateRandom(bits, rng); } // do primality test if(num.isProbablePrime(mrTests)) { return callback(null, num); } // get next potential prime num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime)); // keep trying later forge.util.setImmediate(function() { _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); }); } // NOTE: This algorithm is indeterminate in nature because workers // run in parallel looking at different segments of numbers. Even if this // algorithm is run twice with the same input from a predictable RNG, it // may produce different outputs. function primeincFindPrimeWithWorkers(bits, rng, options, callback) { // web workers unavailable if(typeof Worker === 'undefined') { return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); } // initialize random number var num = generateRandom(bits, rng); // use web workers to generate keys var numWorkers = options.workers; var workLoad = options.workLoad || 100; var range = workLoad * 30 / 8; var workerScript = options.workerScript || 'forge/prime.worker.js'; if(numWorkers === -1) { return forge.util.estimateCores(function(err, cores) { if(err) { // default to 2 cores = 2; } numWorkers = cores - 1; generate(); }); } generate(); function generate() { // require at least 1 worker numWorkers = Math.max(1, numWorkers); // TODO: consider optimizing by starting workers outside getPrime() ... // note that in order to clean up they will have to be made internally // asynchronous which may actually be slower // start workers immediately var workers = []; for(var i = 0; i < numWorkers; ++i) { // FIXME: fix path or use blob URLs workers[i] = new Worker(workerScript); } var running = numWorkers; // listen for requests from workers and assign ranges to find prime for(var i = 0; i < numWorkers; ++i) { workers[i].addEventListener('message', workerMessage); } /* Note: The distribution of random numbers is unknown. Therefore, each web worker is continuously allocated a range of numbers to check for a random number until one is found. Every 30 numbers will be checked just 8 times, because prime numbers have the form: 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this) Therefore, if we want a web worker to run N checks before asking for a new range of numbers, each range must contain N*30/8 numbers. For 100 checks (workLoad), this is a range of 375. */ var found = false; function workerMessage(e) { // ignore message, prime already found if(found) { return; } --running; var data = e.data; if(data.found) { // terminate all workers for(var i = 0; i < workers.length; ++i) { workers[i].terminate(); } found = true; return callback(null, new BigInteger(data.prime, 16)); } // overflow, regenerate random number if(num.bitLength() > bits) { num = generateRandom(bits, rng); } // assign new range to check var hex = num.toString(16); // start prime search e.target.postMessage({ hex: hex, workLoad: workLoad }); num.dAddOffset(range, 0); } } } /** * Generates a random number using the given number of bits and RNG. * * @param bits the number of bits for the number. * @param rng the random number generator to use. * * @return the random number. */ function generateRandom(bits, rng) { var num = new BigInteger(bits, rng); // force MSB set var bits1 = bits - 1; if(!num.testBit(bits1)) { num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); } // align number on 30k+1 boundary num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); return num; } /** * Returns the required number of Miller-Rabin tests to generate a * prime with an error probability of (1/2)^80. * * See Handbook of Applied Cryptography Chapter 4, Table 4.4. * * @param bits the bit size. * * @return the required number of iterations. */ function getMillerRabinTests(bits) { if(bits <= 100) return 27; if(bits <= 150) return 18; if(bits <= 200) return 15; if(bits <= 250) return 12; if(bits <= 300) return 9; if(bits <= 350) return 8; if(bits <= 400) return 7; if(bits <= 500) return 6; if(bits <= 600) return 5; if(bits <= 800) return 4; if(bits <= 1250) return 3; return 2; } })(); /***/ }) /******/ ]); }); /*! ngclipboard - v1.1.1 - 2016-02-26 * https://github.com/sachinchoolur/ngclipboard * Copyright (c) 2016 Sachin; Licensed MIT */ (function() { 'use strict'; var MODULE_NAME = 'ngclipboard'; var angular, Clipboard; // Check for CommonJS support if (typeof module === 'object' && module.exports) { angular = require('angular'); Clipboard = require('clipboard'); module.exports = MODULE_NAME; } else { angular = window.angular; Clipboard = window.Clipboard; } angular.module(MODULE_NAME, []).directive('ngclipboard', function() { return { restrict: 'A', scope: { ngclipboardSuccess: '&', ngclipboardError: '&' }, link: function(scope, element) { var clipboard = new Clipboard(element[0]); clipboard.on('success', function(e) { scope.$apply(function () { scope.ngclipboardSuccess({ e: e }); }); }); clipboard.on('error', function(e) { scope.$apply(function () { scope.ngclipboardError({ e: e }); }); }); } }; }); }()); /*! AdminLTE app.js * ================ * Main JS application file for AdminLTE v2. This file * should be included in all pages. It controls some layout * options and implements exclusive AdminLTE plugins. * * @Author Almsaeed Studio * @Support * @Email * @version 2.3.8 * @license MIT */ //Make sure jQuery has been loaded before app.js if (typeof jQuery === "undefined") { throw new Error("AdminLTE requires jQuery"); } /* AdminLTE * * @type Object * @description $.AdminLTE is the main object for the template's app. * It's used for implementing functions and options related * to the template. Keeping everything wrapped in an object * prevents conflict with other plugins and is a better * way to organize our code. */ $.AdminLTE = {}; /* -------------------- * - AdminLTE Options - * -------------------- * Modify these options to suit your implementation */ $.AdminLTE.options = { //Add slimscroll to navbar menus //This requires you to load the slimscroll plugin //in every page before app.js navbarMenuSlimscroll: true, navbarMenuSlimscrollWidth: "3px", //The width of the scroll bar navbarMenuHeight: "200px", //The height of the inner menu //General animation speed for JS animated elements such as box collapse/expand and //sidebar treeview slide up/down. This options accepts an integer as milliseconds, //'fast', 'normal', or 'slow' animationSpeed: 500, //Sidebar push menu toggle button selector sidebarToggleSelector: "[data-toggle='offcanvas']", //Activate sidebar push menu sidebarPushMenu: true, //Activate sidebar slimscroll if the fixed layout is set (requires SlimScroll Plugin) sidebarSlimScroll: true, //Enable sidebar expand on hover effect for sidebar mini //This option is forced to true if both the fixed layout and sidebar mini //are used together sidebarExpandOnHover: false, //BoxRefresh Plugin enableBoxRefresh: true, //Bootstrap.js tooltip enableBSToppltip: true, BSTooltipSelector: "[data-toggle='tooltip']", //Enable Fast Click. Fastclick.js creates a more //native touch experience with touch devices. If you //choose to enable the plugin, make sure you load the script //before AdminLTE's app.js enableFastclick: false, //Control Sidebar Tree views enableControlTreeView: true, //Control Sidebar Options enableControlSidebar: true, controlSidebarOptions: { //Which button should trigger the open/close event toggleBtnSelector: "[data-toggle='control-sidebar']", //The sidebar selector selector: ".control-sidebar", //Enable slide over content slide: true }, //Box Widget Plugin. Enable this plugin //to allow boxes to be collapsed and/or removed enableBoxWidget: true, //Box Widget plugin options boxWidgetOptions: { boxWidgetIcons: { //Collapse icon collapse: 'fa-minus', //Open icon open: 'fa-plus', //Remove icon remove: 'fa-times' }, boxWidgetSelectors: { //Remove button selector remove: '[data-widget="remove"]', //Collapse button selector collapse: '[data-widget="collapse"]' } }, //Direct Chat plugin options directChat: { //Enable direct chat by default enable: true, //The button to open and close the chat contacts pane contactToggleSelector: '[data-widget="chat-pane-toggle"]' }, //Define the set of colors to use globally around the website colors: { lightBlue: "#3c8dbc", red: "#f56954", green: "#00a65a", aqua: "#00c0ef", yellow: "#f39c12", blue: "#0073b7", navy: "#001F3F", teal: "#39CCCC", olive: "#3D9970", lime: "#01FF70", orange: "#FF851B", fuchsia: "#F012BE", purple: "#8E24AA", maroon: "#D81B60", black: "#222222", gray: "#d2d6de" }, //The standard screen sizes that bootstrap uses. //If you change these in the variables.less file, change //them here too. screenSizes: { xs: 480, sm: 768, md: 992, lg: 1200 } }; /* ------------------ * - Implementation - * ------------------ * The next block of code implements AdminLTE's * functions and plugins as specified by the * options above. */ $(function () { "use strict"; //Fix for IE page transitions $("body").removeClass("hold-transition"); //Extend options if external options exist if (typeof AdminLTEOptions !== "undefined") { $.extend(true, $.AdminLTE.options, AdminLTEOptions); } //Easy access to options var o = $.AdminLTE.options; //Set up the object _init(); //Activate the layout maker $.AdminLTE.layout.activate(); //Enable sidebar tree view controls if (o.enableControlTreeView) { $.AdminLTE.tree('.sidebar'); } //Enable control sidebar if (o.enableControlSidebar) { $.AdminLTE.controlSidebar.activate(); } //Add slimscroll to navbar dropdown if (o.navbarMenuSlimscroll && typeof $.fn.slimscroll != 'undefined') { $(".navbar .menu").slimscroll({ height: o.navbarMenuHeight, alwaysVisible: false, size: o.navbarMenuSlimscrollWidth }).css("width", "100%"); } //Activate sidebar push menu if (o.sidebarPushMenu) { $.AdminLTE.pushMenu.activate(o.sidebarToggleSelector); } //Activate Bootstrap tooltip if (o.enableBSToppltip) { $('body').tooltip({ selector: o.BSTooltipSelector, container: 'body' }); } //Activate box widget if (o.enableBoxWidget) { $.AdminLTE.boxWidget.activate(); } //Activate fast click if (o.enableFastclick && typeof FastClick != 'undefined') { FastClick.attach(document.body); } //Activate direct chat widget if (o.directChat.enable) { $(document).on('click', o.directChat.contactToggleSelector, function () { var box = $(this).parents('.direct-chat').first(); box.toggleClass('direct-chat-contacts-open'); }); } /* * INITIALIZE BUTTON TOGGLE * ------------------------ */ $('.btn-group[data-toggle="btn-toggle"]').each(function () { var group = $(this); $(this).find(".btn").on('click', function (e) { group.find(".btn.active").removeClass("active"); $(this).addClass("active"); e.preventDefault(); }); }); }); /* ---------------------------------- * - Initialize the AdminLTE Object - * ---------------------------------- * All AdminLTE functions are implemented below. */ function _init() { 'use strict'; /* Layout * ====== * Fixes the layout height in case min-height fails. * * @type Object * @usage $.AdminLTE.layout.activate() * $.AdminLTE.layout.fix() * $.AdminLTE.layout.fixSidebar() */ $.AdminLTE.layout = { activate: function () { var _this = this; _this.fix(); _this.fixSidebar(); $('body, html, .wrapper').css('height', 'auto'); $(window, ".wrapper").resize(function () { _this.fix(); _this.fixSidebar(); }); }, fix: function () { // Remove overflow from .wrapper if layout-boxed exists $(".layout-boxed > .wrapper").css('overflow', 'hidden'); //Get window height and the wrapper height var footer_height = $('.main-footer').outerHeight() || 0; var neg = $('.main-header').outerHeight() + footer_height; var window_height = $(window).height(); var sidebar_height = $(".sidebar").height() || 0; //Set the min-height of the content and sidebar based on the //the height of the document. if ($("body").hasClass("fixed")) { $(".content-wrapper, .right-side").css('min-height', window_height - footer_height); } else { var postSetWidth; if (window_height >= sidebar_height) { $(".content-wrapper, .right-side").css('min-height', window_height - neg); postSetWidth = window_height - neg; } else { $(".content-wrapper, .right-side").css('min-height', sidebar_height); postSetWidth = sidebar_height; } //Fix for the control sidebar height var controlSidebar = $($.AdminLTE.options.controlSidebarOptions.selector); if (typeof controlSidebar !== "undefined") { if (controlSidebar.height() > postSetWidth) $(".content-wrapper, .right-side").css('min-height', controlSidebar.height()); } } }, fixSidebar: function () { //Make sure the body tag has the .fixed class if (!$("body").hasClass("fixed")) { if (typeof $.fn.slimScroll != 'undefined') { $(".sidebar").slimScroll({destroy: true}).height("auto"); } return; } else if (typeof $.fn.slimScroll == 'undefined' && window.console) { window.console.error("Error: the fixed layout requires the slimscroll plugin!"); } //Enable slimscroll for fixed layout if ($.AdminLTE.options.sidebarSlimScroll) { if (typeof $.fn.slimScroll != 'undefined') { //Destroy if it exists $(".sidebar").slimScroll({destroy: true}).height("auto"); //Add slimscroll $(".sidebar").slimScroll({ height: ($(window).height() - $(".main-header").height()) + "px", color: "rgba(0,0,0,0.2)", size: "3px" }); } } } }; /* PushMenu() * ========== * Adds the push menu functionality to the sidebar. * * @type Function * @usage: $.AdminLTE.pushMenu("[data-toggle='offcanvas']") */ $.AdminLTE.pushMenu = { activate: function (toggleBtn) { //Get the screen sizes var screenSizes = $.AdminLTE.options.screenSizes; //Enable sidebar toggle $(document).on('click', toggleBtn, function (e) { e.preventDefault(); //Enable sidebar push menu if ($(window).width() > (screenSizes.sm - 1)) { if ($("body").hasClass('sidebar-collapse')) { $("body").removeClass('sidebar-collapse').trigger('expanded.pushMenu'); } else { $("body").addClass('sidebar-collapse').trigger('collapsed.pushMenu'); } } //Handle sidebar push menu for small screens else { if ($("body").hasClass('sidebar-open')) { $("body").removeClass('sidebar-open').removeClass('sidebar-collapse').trigger('collapsed.pushMenu'); } else { $("body").addClass('sidebar-open').trigger('expanded.pushMenu'); } } }); $(".content-wrapper").click(function () { //Enable hide menu when clicking on the content-wrapper on small screens if ($(window).width() <= (screenSizes.sm - 1) && $("body").hasClass("sidebar-open")) { $("body").removeClass('sidebar-open'); } }); //Enable expand on hover for sidebar mini if ($.AdminLTE.options.sidebarExpandOnHover || ($('body').hasClass('fixed') && $('body').hasClass('sidebar-mini'))) { this.expandOnHover(); } }, expandOnHover: function () { var _this = this; var screenWidth = $.AdminLTE.options.screenSizes.sm - 1; //Expand sidebar on hover $('.main-sidebar').hover(function () { if ($('body').hasClass('sidebar-mini') && $("body").hasClass('sidebar-collapse') && $(window).width() > screenWidth) { _this.expand(); } }, function () { if ($('body').hasClass('sidebar-mini') && $('body').hasClass('sidebar-expanded-on-hover') && $(window).width() > screenWidth) { _this.collapse(); } }); }, expand: function () { $("body").removeClass('sidebar-collapse').addClass('sidebar-expanded-on-hover'); }, collapse: function () { if ($('body').hasClass('sidebar-expanded-on-hover')) { $('body').removeClass('sidebar-expanded-on-hover').addClass('sidebar-collapse'); } } }; /* Tree() * ====== * Converts the sidebar into a multilevel * tree view menu. * * @type Function * @Usage: $.AdminLTE.tree('.sidebar') */ $.AdminLTE.tree = function (menu) { var _this = this; var animationSpeed = $.AdminLTE.options.animationSpeed; $(document).off('click', menu + ' li a') .on('click', menu + ' li a', function (e) { //Get the clicked link and the next element var $this = $(this); var checkElement = $this.next(); //Check if the next element is a menu and is visible if ((checkElement.is('.treeview-menu')) && (checkElement.is(':visible')) && (!$('body').hasClass('sidebar-collapse'))) { //Close the menu checkElement.slideUp(animationSpeed, function () { checkElement.removeClass('menu-open'); //Fix the layout in case the sidebar stretches over the height of the window //_this.layout.fix(); }); checkElement.parent("li").removeClass("active"); } //If the menu is not visible else if ((checkElement.is('.treeview-menu')) && (!checkElement.is(':visible'))) { //Get the parent menu var parent = $this.parents('ul').first(); //Close all open menus within the parent var ul = parent.find('ul:visible').slideUp(animationSpeed); //Remove the menu-open class from the parent ul.removeClass('menu-open'); //Get the parent li var parent_li = $this.parent("li"); //Open the target menu and add the menu-open class checkElement.slideDown(animationSpeed, function () { //Add the class active to the parent li checkElement.addClass('menu-open'); parent.find('li.active').removeClass('active'); parent_li.addClass('active'); //Fix the layout in case the sidebar stretches over the height of the window _this.layout.fix(); }); } //if this isn't a link, prevent the page from being redirected if (checkElement.is('.treeview-menu')) { e.preventDefault(); } }); }; /* ControlSidebar * ============== * Adds functionality to the right sidebar * * @type Object * @usage $.AdminLTE.controlSidebar.activate(options) */ $.AdminLTE.controlSidebar = { //instantiate the object activate: function () { //Get the object var _this = this; //Update options var o = $.AdminLTE.options.controlSidebarOptions; //Get the sidebar var sidebar = $(o.selector); //The toggle button var btn = $(o.toggleBtnSelector); //Listen to the click event btn.on('click', function (e) { e.preventDefault(); //If the sidebar is not open if (!sidebar.hasClass('control-sidebar-open') && !$('body').hasClass('control-sidebar-open')) { //Open the sidebar _this.open(sidebar, o.slide); } else { _this.close(sidebar, o.slide); } }); //If the body has a boxed layout, fix the sidebar bg position var bg = $(".control-sidebar-bg"); _this._fix(bg); //If the body has a fixed layout, make the control sidebar fixed if ($('body').hasClass('fixed')) { _this._fixForFixed(sidebar); } else { //If the content height is less than the sidebar's height, force max height if ($('.content-wrapper, .right-side').height() < sidebar.height()) { _this._fixForContent(sidebar); } } }, //Open the control sidebar open: function (sidebar, slide) { //Slide over content if (slide) { sidebar.addClass('control-sidebar-open'); } else { //Push the content by adding the open class to the body instead //of the sidebar itself $('body').addClass('control-sidebar-open'); } }, //Close the control sidebar close: function (sidebar, slide) { if (slide) { sidebar.removeClass('control-sidebar-open'); } else { $('body').removeClass('control-sidebar-open'); } }, _fix: function (sidebar) { var _this = this; if ($("body").hasClass('layout-boxed')) { sidebar.css('position', 'absolute'); sidebar.height($(".wrapper").height()); if (_this.hasBindedResize) { return; } $(window).resize(function () { _this._fix(sidebar); }); _this.hasBindedResize = true; } else { sidebar.css({ 'position': 'fixed', 'height': 'auto' }); } }, _fixForFixed: function (sidebar) { sidebar.css({ 'position': 'fixed', 'max-height': '100%', 'overflow': 'auto', 'padding-bottom': '50px' }); }, _fixForContent: function (sidebar) { $(".content-wrapper, .right-side").css('min-height', sidebar.height()); } }; /* BoxWidget * ========= * BoxWidget is a plugin to handle collapsing and * removing boxes from the screen. * * @type Object * @usage $.AdminLTE.boxWidget.activate() * Set all your options in the main $.AdminLTE.options object */ $.AdminLTE.boxWidget = { selectors: $.AdminLTE.options.boxWidgetOptions.boxWidgetSelectors, icons: $.AdminLTE.options.boxWidgetOptions.boxWidgetIcons, animationSpeed: $.AdminLTE.options.animationSpeed, activate: function (_box) { var _this = this; if (!_box) { _box = document; // activate all boxes per default } //Listen for collapse event triggers $(_box).on('click', _this.selectors.collapse, function (e) { e.preventDefault(); _this.collapse($(this)); }); //Listen for remove event triggers $(_box).on('click', _this.selectors.remove, function (e) { e.preventDefault(); _this.remove($(this)); }); }, collapse: function (element) { var _this = this; //Find the box parent var box = element.parents(".box").first(); //Find the body and the footer var box_content = box.find("> .box-body, > .box-footer, > form >.box-body, > form > .box-footer"); if (!box.hasClass("collapsed-box")) { //Convert minus into plus element.children(":first") .removeClass(_this.icons.collapse) .addClass(_this.icons.open); //Hide the content box_content.slideUp(_this.animationSpeed, function () { box.addClass("collapsed-box"); }); } else { //Convert plus into minus element.children(":first") .removeClass(_this.icons.open) .addClass(_this.icons.collapse); //Show the content box_content.slideDown(_this.animationSpeed, function () { box.removeClass("collapsed-box"); }); } }, remove: function (element) { //Find the box parent var box = element.parents(".box").first(); box.slideUp(this.animationSpeed); } }; } /* ------------------ * - Custom Plugins - * ------------------ * All custom plugins are defined below. */ /* * BOX REFRESH BUTTON * ------------------ * This is a custom plugin to use with the component BOX. It allows you to add * a refresh button to the box. It converts the box's state to a loading state. * * @type plugin * @usage $("#box-widget").boxRefresh( options ); */ (function ($) { "use strict"; $.fn.boxRefresh = function (options) { // Render options var settings = $.extend({ //Refresh button selector trigger: ".refresh-btn", //File source to be loaded (e.g: ajax/src.php) source: "", //Callbacks onLoadStart: function (box) { return box; }, //Right after the button has been clicked onLoadDone: function (box) { return box; } //When the source has been loaded }, options); //The overlay var overlay = $('
      '); return this.each(function () { //if a source is specified if (settings.source === "") { if (window.console) { window.console.log("Please specify a source first - boxRefresh()"); } return; } //the box var box = $(this); //the button var rBtn = box.find(settings.trigger).first(); //On trigger click rBtn.on('click', function (e) { e.preventDefault(); //Add loading overlay start(box); //Perform ajax call box.find(".box-body").load(settings.source, function () { done(box); }); }); }); function start(box) { //Add overlay and loading img box.append(overlay); settings.onLoadStart.call(box); } function done(box) { //Remove overlay and loading img box.find(overlay).remove(); settings.onLoadDone.call(box); } }; })(jQuery); /* * EXPLICIT BOX CONTROLS * ----------------------- * This is a custom plugin to use with the component BOX. It allows you to activate * a box inserted in the DOM after the app.js was loaded, toggle and remove box. * * @type plugin * @usage $("#box-widget").activateBox(); * @usage $("#box-widget").toggleBox(); * @usage $("#box-widget").removeBox(); */ (function ($) { 'use strict'; $.fn.activateBox = function () { $.AdminLTE.boxWidget.activate(this); }; $.fn.toggleBox = function () { var button = $($.AdminLTE.boxWidget.selectors.collapse, this); $.AdminLTE.boxWidget.collapse(button); }; $.fn.removeBox = function () { var button = $($.AdminLTE.boxWidget.selectors.remove, this); $.AdminLTE.boxWidget.remove(button); }; })(jQuery); /* * TODO LIST CUSTOM PLUGIN * ----------------------- * This plugin depends on iCheck plugin for checkbox and radio inputs * * @type plugin * @usage $("#todo-widget").todolist( options ); */ (function ($) { 'use strict'; $.fn.todolist = function (options) { // Render options var settings = $.extend({ //When the user checks the input onCheck: function (ele) { return ele; }, //When the user unchecks the input onUncheck: function (ele) { return ele; } }, options); return this.each(function () { if (typeof $.fn.iCheck != 'undefined') { $('input', this).on('ifChecked', function () { var ele = $(this).parents("li").first(); ele.toggleClass("done"); settings.onCheck.call(ele); }); $('input', this).on('ifUnchecked', function () { var ele = $(this).parents("li").first(); ele.toggleClass("done"); settings.onUncheck.call(ele); }); } else { $('input', this).on('change', function () { var ele = $(this).parents("li").first(); ele.toggleClass("done"); if ($('input', ele).is(":checked")) { settings.onCheck.call(ele); } else { settings.onUncheck.call(ele); } }); } }); }; }(jQuery));